text
stringlengths
2
1.04M
meta
dict
""" RBAC related utility functions. """ from oslo_config import cfg from st2common.constants.rbac import SystemRole __all__ = [ 'request_user_is_admin', 'request_user_has_role', 'user_is_admin', 'user_has_role' ] def request_user_is_admin(request): """ Check if the logged-in request user has admin role. :rtype: ``bool`` """ return request_user_has_role(request=request, role=SystemRole.ADMIN) def request_user_has_role(request, role): """ Check if the logged-in request user has the provided role. :rtype: ``bool`` """ # TODO: Once RBAC is implemented, we should not support running production (non-dev) # deployments with auth disabled. if not cfg.CONF.auth.enable: return True auth_context = request.context.get('auth', {}) if not auth_context: return False user_db = auth_context.get('user', None) if not user_db: return False if user_has_role(user=user_db, role=role): return True return False def user_is_admin(user): """ Return True if the provided user has admin rule, false otherwise. :param user: User object to check for. :type user: :class:`UserDB` :rtype: ``bool`` """ return user_has_role(user=user, role=SystemRole.ADMIN) def user_has_role(user, role): """ :param user: User object to check for. :type user: :class:`UserDB` :rtype: ``bool`` """ # Note: atm, we onl'y support admin role if role == SystemRole.ADMIN and user.name in cfg.CONF.system.admin_users: return True return False
{ "content_hash": "2f107661c080f4a30fbdcd8e6bbabfc5", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 88, "avg_line_length": 20.948051948051948, "alnum_prop": 0.6323620582765034, "repo_name": "grengojbo/st2", "id": "388968aa33fcdfe3f463e338f670f42d10b4b732", "size": "2393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "st2common/st2common/rbac/utils.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "198" }, { "name": "Makefile", "bytes": "21186" }, { "name": "PowerShell", "bytes": "299" }, { "name": "Python", "bytes": "2091976" }, { "name": "Shell", "bytes": "7518" }, { "name": "Slash", "bytes": "677" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using QuantConnect.Configuration; using QuantConnect.Data; using QuantConnect.Logging; using QuantConnect.Util; namespace QuantConnect.ToolBox.YahooDownloader { public static class YahooDownloaderProgram { /// <summary> /// Yahoo Downloader Toolbox Project For LEAN Algorithmic Trading Engine. /// Original by @chrisdk2015, tidied by @jaredbroad /// </summary> public static void YahooDownloader(IList<string> tickers, string resolution, DateTime startDate, DateTime endDate) { if (resolution.IsNullOrEmpty() || tickers.IsNullOrEmpty()) { Console.WriteLine("YahooDownloader ERROR: '--tickers=' or '--resolution=' parameter is missing"); Console.WriteLine("--tickers=eg SPY,AAPL"); Console.WriteLine("--resolution=Daily"); Environment.Exit(1); } try { // Load settings from command line var castResolution = (Resolution)Enum.Parse(typeof(Resolution), resolution); // Load settings from config.json var dataDirectory = Config.Get("data-directory", "../../../Data"); // Create an instance of the downloader const string market = Market.USA; var downloader = new YahooDataDownloader(); foreach (var ticker in tickers) { // Download the data var symbolObject = Symbol.Create(ticker, SecurityType.Equity, market); var data = downloader.Get(symbolObject, castResolution, startDate, endDate); // Save the data var writer = new LeanDataWriter(castResolution, symbolObject, dataDirectory); writer.Write(data); } } catch (Exception err) { Log.Error(err); } } } }
{ "content_hash": "141e194074886780d92300b8d30fdf24", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 122, "avg_line_length": 37.127272727272725, "alnum_prop": 0.5656219392752204, "repo_name": "StefanoRaggi/Lean", "id": "59467b7e5626870ac4d19c47375c075e293e89e5", "size": "2746", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ToolBox/YahooDownloader/YahooDownloaderProgram.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1841" }, { "name": "C#", "bytes": "21581235" }, { "name": "CSS", "bytes": "10299" }, { "name": "Dockerfile", "bytes": "1352" }, { "name": "F#", "bytes": "1646" }, { "name": "HTML", "bytes": "15710" }, { "name": "Java", "bytes": "852" }, { "name": "Jupyter Notebook", "bytes": "22419" }, { "name": "Python", "bytes": "1012106" }, { "name": "Shell", "bytes": "1390" }, { "name": "Visual Basic .NET", "bytes": "2448" } ], "symlink_target": "" }
@interface NIMGroupUser() @property (nonatomic,copy) NSString *userId; @property (nonatomic,strong) NIMKitInfo *info; @end @implementation NIMGroupUser - (instancetype)initWithUserId:(NSString *)userId{ self = [super init]; if (self) { _userId = userId; _info = [[NIMKit sharedKit] infoByUser:userId option:nil]; } return self; } - (NSString *)groupTitle{ NSString *title = [[NIMSpellingCenter sharedCenter] firstLetter:self.info.showName].capitalizedString; unichar character = [title characterAtIndex:0]; if (character >= 'A' && character <= 'Z') { return title; }else{ return @"#"; } } - (NSString *)showName{ return self.info.showName; } - (NSString *)memberId{ return self.userId; } - (id)sortKey{ return [[NIMSpellingCenter sharedCenter] spellingForString:self.info.showName].shortSpelling; } - (UIImage *)avatarImage { return self.info.avatarImage; } - (NSString *)avatarUrlString { return self.info.avatarUrlString; } @end @interface NIMGroupTeamMember() @property (nonatomic,copy) NSString *userId; @property (nonatomic,strong) NIMKitInfo *info; @end @implementation NIMGroupTeamMember - (instancetype)initWithUserId:(NSString *)userId session:(NIMSession *)session { self = [super init]; if (self) { _userId = userId; NIMKitInfoFetchOption *option = [[NIMKitInfoFetchOption alloc] init]; option.session = session; _info = [[NIMKit sharedKit] infoByUser:userId option:option]; } return self; } - (NSString *)groupTitle{ NSString *title = [[NIMSpellingCenter sharedCenter] firstLetter:self.showName].capitalizedString; unichar character = [title characterAtIndex:0]; if (character >= 'A' && character <= 'Z') { return title; }else{ return @"#"; } } - (id)sortKey{ return [[NIMSpellingCenter sharedCenter] spellingForString:self.showName].shortSpelling; } - (NSString *)showName{ return self.info.showName; } - (NSString *)memberId{ return self.userId; } - (UIImage *)avatarImage { return self.info.avatarImage; } - (NSString *)avatarUrlString { return self.info.avatarUrlString; } @end @interface NIMGroupTeam() @property (nonatomic,copy) NSString *teamId; @property (nonatomic,strong) NIMKitInfo *info; @end @implementation NIMGroupTeam - (instancetype)initWithTeamId:(NSString *)teamId teamType:(NIMKitTeamType)teamType { self = [super init]; if (self) { _teamId = teamId; if (teamType == NIMKitTeamTypeNomal) { _info = [[NIMKit sharedKit] infoByTeam:teamId option:nil]; } else if (teamType == NIMKitTeamTypeSuper) { _info = [[NIMKit sharedKit] infoBySuperTeam:teamId option:nil]; } } return self; } - (NSString *)groupTitle{ NSString *title = [[NIMSpellingCenter sharedCenter] firstLetter:self.showName].capitalizedString; unichar character = [title characterAtIndex:0]; if (character >= 'A' && character <= 'Z') { return title; }else{ return @"#"; } } - (id)sortKey{ return [[NIMSpellingCenter sharedCenter] spellingForString:[self showName]].shortSpelling; } - (NSString *)showName{ return self.info.showName; } - (NSString *)memberId{ return self.teamId; } - (UIImage *)avatarImage { return self.info.avatarImage; } - (NSString *)avatarUrlString { return self.info.avatarUrlString; } @end
{ "content_hash": "313ebb177e6527794726ab2ac414a362", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 106, "avg_line_length": 21.795031055900623, "alnum_prop": 0.658592191507552, "repo_name": "netease-im/NIM_iOS_UIKit", "id": "0c9612ebda21faf3a4b6be499e18cd84fc3f5366", "size": "3736", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NIMKit/NIMKit/Classes/Sections/Contact/ContactGroup/NIMGroupedUsrInfo.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "529" }, { "name": "Objective-C", "bytes": "850479" }, { "name": "Ruby", "bytes": "2108" } ], "symlink_target": "" }
/** * Base interfaces and annotations defining Joda-Beans. * <p> * Joda-Beans is a library that can be used to provide enhanced Java Beans. * These extensions provide the tools for framework writers to access bean and property * information in a consistent and fast manner, typically without reflection. * <p> * A Joda-Bean implements the {@code Bean} interface. In turn, this requires the * creation of a {@code MetaBean} implementation, typically an inner class. * Both also require the provision of implementations of {@code Property} and * {@code MetaProperty} to express the properties of the bean. * <p> * Other packages provide implementations of the interfaces and a code generator. */ package org.joda.beans;
{ "content_hash": "cafb8560d251b5acb38137e80f74dc9c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 87, "avg_line_length": 43.11764705882353, "alnum_prop": 0.7544338335607094, "repo_name": "fengshao0907/joda-beans", "id": "a93df5706bb30ff0d8a0aa48db885439da4455e4", "size": "1349", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/joda/beans/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "941" }, { "name": "HTML", "bytes": "153" }, { "name": "Java", "bytes": "2192572" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe User, type: :model do it { should have_many :projects } it { should respond_to :email } describe 'Create User' do it 'with valid parameters' do User.create( email: "test@test.test", password: "test12333") expect(User.count).to eq(1) end it 'with no valid parameters' do User.create() expect(User.count).to eq(0) end end describe 'Delete User' do it 'with DEL Request' do user = User.create( email: "test@test.test", password: "test12333") user.destroy() expect(User.count).to eq(0) end end end
{ "content_hash": "340ba12b168448f64fac7ed053748219", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 73, "avg_line_length": 25.541666666666668, "alnum_prop": 0.634584013050571, "repo_name": "venarius/adoptMyGit", "id": "57009292aec830cffa4d16a0237109539ea669f3", "size": "613", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/models/user_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "931" }, { "name": "CoffeeScript", "bytes": "211" }, { "name": "HTML", "bytes": "29148" }, { "name": "JavaScript", "bytes": "1979" }, { "name": "Ruby", "bytes": "61034" } ], "symlink_target": "" }
package com.yundroid.kokpit.commands; public enum ControlLevel { MAX, ACE, BEGINNER; }
{ "content_hash": "de9fa38a2d2716c66ffac13a37803e8b", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 37, "avg_line_length": 13, "alnum_prop": 0.7472527472527473, "repo_name": "syagbasan/Kokpit", "id": "7356e8800037e25721b21e219a70902c9f9a1b9e", "size": "91", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/yundroid/kokpit/commands/ControlLevel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "111178" } ], "symlink_target": "" }
import color from 'color'; import { Platform, Dimensions, PixelRatio } from 'react-native'; const deviceHeight = Dimensions.get('window').height; const deviceWidth = Dimensions.get('window').width; const platform = Platform.OS; const platformStyle = undefined; const isIphoneX = platform === 'ios' && deviceHeight === 812 && deviceWidth === 375; const monteColor = '#f95346'; export default { platformStyle, platform, // Android androidRipple: true, androidRippleColor: 'rgba(256, 256, 256, 0.3)', androidRippleColorDark: 'rgba(0, 0, 0, 0.15)', btnUppercaseAndroidText: true, // Badge badgeBg: '#ED1727', badgeColor: '#fff', badgePadding: platform === 'ios' ? 3 : 0, // Button btnFontFamily: platform === 'ios' ? 'System' : 'Roboto_medium', btnDisabledBg: '#b5b5b5', buttonPadding: 6, get btnPrimaryBg() { return this.brandPrimary; }, get btnPrimaryColor() { return this.inverseTextColor; }, get btnInfoBg() { return this.brandInfo; }, get btnInfoColor() { return this.inverseTextColor; }, get btnSuccessBg() { return this.brandSuccess; }, get btnSuccessColor() { return this.inverseTextColor; }, get btnDangerBg() { return this.brandDanger; }, get btnDangerColor() { return this.inverseTextColor; }, get btnWarningBg() { return this.brandWarning; }, get btnWarningColor() { return this.inverseTextColor; }, get btnTextSize() { return platform === 'ios' ? this.fontSizeBase * 1.1 : this.fontSizeBase - 1; }, get btnTextSizeLarge() { return this.fontSizeBase * 1.5; }, get btnTextSizeSmall() { return this.fontSizeBase * 0.8; }, get borderRadiusLarge() { return this.fontSizeBase * 3.8; }, get iconSizeLarge() { return this.iconFontSize * 1.5; }, get iconSizeSmall() { return this.iconFontSize * 0.6; }, // Card cardDefaultBg: '#fff', cardBorderColor: '#ccc', // CheckBox CheckboxRadius: platform === 'ios' ? 13 : 0, CheckboxBorderWidth: platform === 'ios' ? 1 : 2, CheckboxPaddingLeft: platform === 'ios' ? 4 : 2, CheckboxPaddingBottom: platform === 'ios' ? 0 : 5, CheckboxIconSize: platform === 'ios' ? 21 : 14, CheckboxIconMarginTop: platform === 'ios' ? undefined : 1, CheckboxFontSize: platform === 'ios' ? 23 / 0.9 : 18, DefaultFontSize: 17, checkboxBgColor: '#039BE5', checkboxSize: 20, checkboxTickColor: '#fff', // Color brandPrimary: '#007aff', brandInfo: '#62B1F6', brandSuccess: '#5cb85c', brandDanger: '#d9534f', brandWarning: '#f0ad4e', brandDark: '#000', brandLight: '#f4f4f4', // Font fontFamily: platform === 'ios' ? 'System' : 'Roboto', fontSizeBase: 15, get fontSizeH1() { return this.fontSizeBase * 1.8; }, get fontSizeH2() { return this.fontSizeBase * 1.6; }, get fontSizeH3() { return this.fontSizeBase * 1.4; }, // Footer footerHeight: isIphoneX ? 89 : 55, footerDefaultBg: '#F8F8F8', footerPaddingBottom: isIphoneX ? 34 : 0, // FooterTab tabBarTextColor: monteColor, tabBarTextSize: platform === 'ios' ? 14 : 11, activeTab: '#fff', sTabBarActiveTextColor: '#007aff', tabBarActiveTextColor: '#2874F0', tabActiveBgColor: '#ffffff', // Header toolbarBtnColor: '#fff', toolbarDefaultBg: monteColor, toolbarHeight: platform === 'ios' ? (isIphoneX ? 88 : 64) : 56, toolbarSearchIconSize: platform === 'ios' ? 20 : 23, toolbarInputColor: platform === 'ios' ? '#CECDD2' : '#fff', searchBarHeight: platform === 'ios' ? 30 : 40, searchBarInputHeight: platform === 'ios' ? 30 : 50, toolbarBtnTextColor: '#ffffff', toolbarDefaultBorder: '#a7a6ab', iosStatusbar: 'light-content', get statusBarColor() { return this.toolbarDefaultBg; // return color(this.toolbarDefaultBg) // .darken(0.2) // .hex(); }, get darkenHeader() { return color(this.tabBgColor) .darken(0.03) .hex(); }, // Icon iconFamily: 'Ionicons', iconFontSize: platform === 'ios' ? 30 : 28, iconHeaderSize: platform === 'ios' ? 33 : 24, // InputGroup inputFontSize: 17, inputBorderColor: '#D9D5DC', inputSuccessBorderColor: '#2b8339', inputErrorBorderColor: '#ed2f2f', inputHeightBase: 50, get inputColor() { return this.textColor; }, get inputColorPlaceholder() { return '#575757'; }, // Line Height btnLineHeight: 19, lineHeightH1: 32, lineHeightH2: 27, lineHeightH3: 22, lineHeight: platform === 'ios' ? 20 : 24, // List listBg: 'transparent', listBorderColor: '#c9c9c9', listDividerBg: '#f4f4f4', listBtnUnderlayColor: '#DDD', listItemPadding: platform === 'ios' ? 10 : 12, listNoteColor: '#808080', listNoteSize: 13, // Progress Bar defaultProgressColor: '#E4202D', inverseProgressColor: '#1A191B', // Radio Button radioBtnSize: platform === 'ios' ? 25 : 23, radioSelectedColorAndroid: '#3F51B5', radioBtnLineHeight: platform === 'ios' ? 29 : 24, radioColor: this.brandPrimary, // Segment segmentBackgroundColor: platform === 'ios' ? '#F8F8F8' : '#3F51B5', segmentActiveBackgroundColor: platform === 'ios' ? '#007aff' : '#fff', segmentTextColor: platform === 'ios' ? '#007aff' : '#fff', segmentActiveTextColor: platform === 'ios' ? '#fff' : '#3F51B5', segmentBorderColor: platform === 'ios' ? '#007aff' : '#fff', segmentBorderColorMain: platform === 'ios' ? '#a7a6ab' : '#3F51B5', // Spinner defaultSpinnerColor: '#45D56E', inverseSpinnerColor: '#1A191B', // Tab tabDefaultBg: platform === 'ios' ? '#F8F8F8' : '#3F51B5', topTabBarTextColor: platform === 'ios' ? '#6b6b6b' : '#b3c7f9', topTabBarActiveTextColor: platform === 'ios' ? '#007aff' : '#fff', topTabBarBorderColor: platform === 'ios' ? '#a7a6ab' : '#fff', topTabBarActiveBorderColor: platform === 'ios' ? '#007aff' : '#fff', // Tabs tabBgColor: '#F8F8F8', tabFontSize: 15, // Text textColor: '#000', inverseTextColor: '#fff', noteFontSize: 14, get defaultTextColor() { return this.textColor; }, // Title titleFontfamily: platform === 'ios' ? 'System' : 'Roboto_medium', titleFontSize: platform === 'ios' ? 17 : 19, subTitleFontSize: platform === 'ios' ? 12 : 14, subtitleColor: platform === 'ios' ? '#8e8e93' : '#FFF', titleFontColor: '#FFF', // Other borderRadiusBase: platform === 'ios' ? 5 : 2, borderWidth: 1 / PixelRatio.getPixelSizeForLayoutSize(1), contentPadding: 10, dropdownLinkColor: '#414142', inputLineHeight: 24, deviceWidth, deviceHeight, isIphoneX, inputGroupRoundedBorderRadius: 30, };
{ "content_hash": "5fd7de1464644954b1d03b4360dea7b3", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 80, "avg_line_length": 26.333333333333332, "alnum_prop": 0.6464846728686899, "repo_name": "kapone89/MonteOfficeExpo", "id": "4b93eb39fbc35f14f74543a187b489082a23947c", "size": "6557", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "native-base-theme/variables/monte_platform.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "146455" } ], "symlink_target": "" }
require "rprompt/version" require "rprompt/deco" require "rprompt/termcolor" module Rprompt class PromptItem include Deco attr_reader :symbol, :color # @param config [Hash] Prompt item configuration: # - :cmd => shell command # - :symbol => character # - :color => color name def initialize(config) @cmd = config[:cmd] @symbol = config[:symbol] @color = config[:color] end # executes prompt item command # @return [String] command result def commandResult %x(#{@cmd} 2> /dev/null) end end class GitNumbers < PromptItem # @return [Integer] number of files returned by a git command def numberOfFiles commandResult.split(/\r?\n/).count end # @return [String] terminal representation of the number of files def show numberOfFiles != 0 ? termShow({:color => color, :symbol => symbol, :content => numberOfFiles}) : '' end end class GitBranch < PromptItem # @return [String] branch name def shortBranchName commandResult.chomp.split('/').last end # @return [String] terminal representation of the branch name def show termShow({:color => color, :symbol => symbol, :content => shortBranchName}) end end class GitSha < PromptItem # @return [String] last five numbers form the sha1 def sha commandResult.chomp[-6,6] end # @return [String] terminal representation of the number returned by 'sha' def show termShow({:color => color, :symbol => symbol, :content => sha}) end end class GitTrack < PromptItem # @param (see PromptItem#initialize) # @param [Symbol] state ("ahead" or "behind") def initialize(config, state) @state = state super(config) end # @return [Integer] number of commits ahead or behind remote # @note works only if remote branch is tracked def count commandResult.match(/#{@state}\s+([0-9]+)/) $1.to_i end # @return [String] terminal representation of the tracking def show count != 0 ? termShow({:color => color, :symbol => symbol, :content => count}) : '' end end class RvmRuby < PromptItem # @return [String] ruby used def ruby text = commandResult.chomp if text.include?('@') text.match(/ruby-(.+)@/)[1] else text.gsub!(/ruby-/, '') end end # @return [String] terminal representation of the ruby version def show termShow({:color => color, :symbol => symbol, :content => ruby}) end end class RvmGemset < PromptItem # @return [String] gemset used def gemset text = commandResult.chomp if text.include?('@') text.match(/.+@(.+)/)[1] else '' end end # @return [String] terminal representation of the gemset used def show !gemset.empty? ? termShow({:color => color, :symbol => symbol, :content => gemset}) : '' end end end
{ "content_hash": "cc6357b5cc897e6d8af81f28d82a3d45", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 102, "avg_line_length": 23.361344537815125, "alnum_prop": 0.6550359712230216, "repo_name": "olibob/rprompt", "id": "24ff7ef5327a3aceb3b1ef3156aee976032e0bc4", "size": "2780", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/rprompt.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Perl", "bytes": "967" }, { "name": "Ruby", "bytes": "8392" } ], "symlink_target": "" }
package net.ontopia.topicmaps.query.core; /** * PUBLIC: Represents a set of parsed query declarations. There is no * support at present for seeing what these declarations are, but the * context containing these declarations can be passed in to a query * processor. * * @since 2.1 */ public interface DeclarationContextIF { }
{ "content_hash": "f5a4ce2d3c75d01bd541392a50dc8160", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 69, "avg_line_length": 21.1875, "alnum_prop": 0.7374631268436578, "repo_name": "ontopia/ontopia", "id": "a1bcc989b957e953ed8f289808bc08999ef1bcfd", "size": "994", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ontopia-engine/src/main/java/net/ontopia/topicmaps/query/core/DeclarationContextIF.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "229" }, { "name": "CSS", "bytes": "102701" }, { "name": "GAP", "bytes": "55644" }, { "name": "HTML", "bytes": "56107" }, { "name": "Java", "bytes": "11884136" }, { "name": "JavaScript", "bytes": "365763" }, { "name": "Lex", "bytes": "19344" }, { "name": "Python", "bytes": "27528" }, { "name": "SCSS", "bytes": "6338" }, { "name": "Shell", "bytes": "202" } ], "symlink_target": "" }
#include "py/runtime.h" #include "py/mphal.h" #include "py/mpthread.h" #include <sys/time.h> #include <windows.h> #include <unistd.h> HANDLE std_in = NULL; HANDLE con_out = NULL; DWORD orig_mode = 0; STATIC void assure_stdin_handle() { if (!std_in) { std_in = GetStdHandle(STD_INPUT_HANDLE); assert(std_in != INVALID_HANDLE_VALUE); } } STATIC void assure_conout_handle() { if (!con_out) { con_out = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); assert(con_out != INVALID_HANDLE_VALUE); } } void mp_hal_stdio_mode_raw(void) { assure_stdin_handle(); GetConsoleMode(std_in, &orig_mode); DWORD mode = orig_mode; mode &= ~ENABLE_ECHO_INPUT; mode &= ~ENABLE_LINE_INPUT; mode &= ~ENABLE_PROCESSED_INPUT; SetConsoleMode(std_in, mode); } void mp_hal_stdio_mode_orig(void) { assure_stdin_handle(); SetConsoleMode(std_in, orig_mode); } // Handler to be installed by SetConsoleCtrlHandler, currently used only to handle Ctrl-C. // This handler has to be installed just once (this has to be done elswhere in init code). // Previous versions of the mp_hal code would install a handler whenever Ctrl-C input is // allowed and remove the handler again when it is not. That is not necessary though (1), // and it might introduce problems (2) because console notifications are delivered to the // application in a separate thread. // (1) mp_hal_set_interrupt_char effectively enables/disables processing of Ctrl-C via the // ENABLE_PROCESSED_INPUT flag so in raw mode console_sighandler won't be called. // (2) if mp_hal_set_interrupt_char would remove the handler while Ctrl-C was issued earlier, // the thread created for handling it might not be running yet so we'd miss the notification. BOOL WINAPI console_sighandler(DWORD evt) { if (evt == CTRL_C_EVENT) { if (MP_STATE_MAIN_THREAD(mp_pending_exception) == MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_kbd_exception))) { // this is the second time we are called, so die straight away exit(1); } mp_sched_keyboard_interrupt(); return TRUE; } return FALSE; } void mp_hal_set_interrupt_char(char c) { assure_stdin_handle(); if (c == CHAR_CTRL_C) { DWORD mode; GetConsoleMode(std_in, &mode); mode |= ENABLE_PROCESSED_INPUT; SetConsoleMode(std_in, mode); } else { DWORD mode; GetConsoleMode(std_in, &mode); mode &= ~ENABLE_PROCESSED_INPUT; SetConsoleMode(std_in, mode); } } void mp_hal_move_cursor_back(uint pos) { if (!pos) { return; } assure_conout_handle(); CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(con_out, &info); info.dwCursorPosition.X -= (short)pos; // Move up a line if needed. while (info.dwCursorPosition.X < 0) { info.dwCursorPosition.X = info.dwSize.X + info.dwCursorPosition.X; info.dwCursorPosition.Y -= 1; } // Caller requested to move out of the screen. That's not possible so just clip, // it's the caller's responsibility to not let this happen. if (info.dwCursorPosition.Y < 0) { info.dwCursorPosition.X = 0; info.dwCursorPosition.Y = 0; } SetConsoleCursorPosition(con_out, info.dwCursorPosition); } void mp_hal_erase_line_from_cursor(uint n_chars_to_erase) { assure_conout_handle(); CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(con_out, &info); DWORD written; FillConsoleOutputCharacter(con_out, ' ', n_chars_to_erase, info.dwCursorPosition, &written); FillConsoleOutputAttribute(con_out, info.wAttributes, n_chars_to_erase, info.dwCursorPosition, &written); } typedef struct item_t { WORD vkey; const char *seq; } item_t; // map virtual key codes to key sequences known by MicroPython's readline implementation STATIC item_t keyCodeMap[] = { {VK_UP, "[A"}, {VK_DOWN, "[B"}, {VK_RIGHT, "[C"}, {VK_LEFT, "[D"}, {VK_HOME, "[H"}, {VK_END, "[F"}, {VK_DELETE, "[3~"}, {0, ""} // sentinel }; // likewise, but with Ctrl key down STATIC item_t ctrlKeyCodeMap[] = { {VK_LEFT, "b"}, {VK_RIGHT, "f"}, {VK_DELETE, "d"}, {VK_BACK, "\x7F"}, {0, ""} // sentinel }; STATIC const char *cur_esc_seq = NULL; STATIC int esc_seq_process_vk(WORD vk, bool ctrl_key_down) { for (item_t *p = (ctrl_key_down ? ctrlKeyCodeMap : keyCodeMap); p->vkey != 0; ++p) { if (p->vkey == vk) { cur_esc_seq = p->seq; return 27; // ESC, start of escape sequence } } return 0; // nothing found } STATIC int esc_seq_chr() { if (cur_esc_seq) { const char c = *cur_esc_seq++; if (c) { return c; } cur_esc_seq = NULL; } return 0; } int mp_hal_stdin_rx_chr(void) { // currently processing escape seq? const int ret = esc_seq_chr(); if (ret) { return ret; } // poll until key which we handle is pressed assure_stdin_handle(); BOOL status; DWORD num_read; INPUT_RECORD rec; for (;;) { MP_THREAD_GIL_EXIT(); status = ReadConsoleInput(std_in, &rec, 1, &num_read); MP_THREAD_GIL_ENTER(); if (!status || !num_read) { return CHAR_CTRL_C; // EOF, ctrl-D } if (rec.EventType != KEY_EVENT || !rec.Event.KeyEvent.bKeyDown) { // only want key down events continue; } const bool ctrl_key_down = (rec.Event.KeyEvent.dwControlKeyState & LEFT_CTRL_PRESSED) || (rec.Event.KeyEvent.dwControlKeyState & RIGHT_CTRL_PRESSED); const int ret = esc_seq_process_vk(rec.Event.KeyEvent.wVirtualKeyCode, ctrl_key_down); if (ret) { return ret; } const char c = rec.Event.KeyEvent.uChar.AsciiChar; if (c) { // plain ascii char, return it return c; } } } void mp_hal_stdout_tx_strn(const char *str, size_t len) { MP_THREAD_GIL_EXIT(); write(STDOUT_FILENO, str, len); MP_THREAD_GIL_ENTER(); } void mp_hal_stdout_tx_strn_cooked(const char *str, size_t len) { mp_hal_stdout_tx_strn(str, len); } void mp_hal_stdout_tx_str(const char *str) { mp_hal_stdout_tx_strn(str, strlen(str)); } mp_uint_t mp_hal_ticks_ms(void) { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; } mp_uint_t mp_hal_ticks_us(void) { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000000 + tv.tv_usec; } mp_uint_t mp_hal_ticks_cpu(void) { LARGE_INTEGER value; QueryPerformanceCounter(&value); #ifdef _WIN64 return value.QuadPart; #else return value.LowPart; #endif } uint64_t mp_hal_time_ns(void) { struct timeval tv; gettimeofday(&tv, NULL); return (uint64_t)tv.tv_sec * 1000000000ULL + (uint64_t)tv.tv_usec * 1000ULL; } // TODO: POSIX et al. define usleep() as guaranteedly capable only of 1s sleep: // "The useconds argument shall be less than one million." void mp_hal_delay_ms(mp_uint_t ms) { usleep((ms) * 1000); }
{ "content_hash": "b2ea7e68d753f44c581e3a7000dc23f1", "timestamp": "", "source": "github", "line_count": 245, "max_line_length": 109, "avg_line_length": 29.37142857142857, "alnum_prop": 0.622568093385214, "repo_name": "bvernoux/micropython", "id": "7a3d881a34430f99c6de8bf67ec097c9573b3023", "size": "8420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ports/windows/windows_mphal.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "50694" }, { "name": "C", "bytes": "19869126" }, { "name": "C++", "bytes": "2489380" }, { "name": "HTML", "bytes": "84456" }, { "name": "Makefile", "bytes": "49218" }, { "name": "Objective-C", "bytes": "8382" }, { "name": "Python", "bytes": "856777" }, { "name": "Shell", "bytes": "6229" } ], "symlink_target": "" }
const fs = require('fs'); const path = require('path'); const Sequelize = require('sequelize'); const basename = path.basename(module.filename); const env = process.env.NODE_ENV || 'development'; // eslint-disable-line const config = require(`${__dirname}/../config/config.js`)[env]; const db = {}; let sequelize; if (config.use_env_variable) { sequelize = new Sequelize(process.env[config.use_env_variable]); // eslint-disable-line } else { sequelize = new Sequelize( config.database, config.username, config.password, config ); } fs .readdirSync(__dirname) .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')) .forEach(file => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(modelName => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
{ "content_hash": "5435ed39071db0be4fffe2f4d1fc15fa", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 90, "avg_line_length": 26.105263157894736, "alnum_prop": 0.6512096774193549, "repo_name": "andela-ieyo/docify", "id": "db5ca242411b2239f53a3ef28f9d66dd6983a5a7", "size": "992", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "server/models/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13451" }, { "name": "HTML", "bytes": "6395" }, { "name": "JavaScript", "bytes": "248582" } ], "symlink_target": "" }
import openmc import pytest @pytest.fixture def th232_model(): # URR boundaries for Th232 e_min, e_max = 4000.0, 100000.0 model = openmc.model.Model() th232 = openmc.Material() th232.add_nuclide('Th232', 1.0) surf = openmc.Sphere(r=100.0, boundary_type='reflective') cell = openmc.Cell(fill=th232, region=-surf) model.geometry = openmc.Geometry([cell]) model.settings.particles = 100 model.settings.batches = 10 model.settings.run_mode = 'fixed source' energies = openmc.stats.Uniform(e_min, e_max) model.settings.source = openmc.Source(energy=energies) tally = openmc.Tally(name='rates') tally.filters = [openmc.EnergyFilter([e_min, e_max])] tally.scores = ['(n,gamma)', 'absorption', 'fission'] model.tallies.append(tally) return model def test_urr_capture(run_in_tmpdir, th232_model): # Export and run model th232_model.export_to_xml() openmc.run() # Get reaction rates from tally with openmc.StatePoint('statepoint.10.h5') as sp: t = sp.get_tally(name='rates') ngamma, absorption, fission = t.mean.flatten() # In URR, the (n,gamma) rate should be equal to absorption - fission assert ngamma == pytest.approx(absorption - fission)
{ "content_hash": "03a811c6ba049b346604fc2f0c977717", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 72, "avg_line_length": 30, "alnum_prop": 0.6682539682539682, "repo_name": "walshjon/openmc", "id": "745d62cef0fc7c6d42f4e84d75e21b96da7028de", "size": "1260", "binary": false, "copies": "5", "ref": "refs/heads/develop", "path": "tests/unit_tests/test_urr_capture.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7703" }, { "name": "C++", "bytes": "573709" }, { "name": "CMake", "bytes": "32233" }, { "name": "Fortran", "bytes": "1742097" }, { "name": "Python", "bytes": "2227872" }, { "name": "Shell", "bytes": "2107" } ], "symlink_target": "" }
{% extends 'templates/nhs_transaction_layout.html' %} {% import 'includes/form_macros.html' as form_macros %} {% import 'includes/ui_element_macros.html' as ui_element_macros %} {% block content %} <main id="content" role="main"> <h1 class="heading-large" style="padding-top:0px;padding-bottom:10px;">Booking Confirmation</h1> <div class="container-fluid" style="background-color:#00953A;margin-bottom:20px;"> <div class="row-fluid" style="padding:0 0 0 0;"> <div class="span2 offset1"> <p style="padding:25px 0 25px 0;"> <img src="/public/images/tick.png" width="50px" /></p> </div> <div class="span8 offset1"> <h1 class="heading-large" style="color:#fff;"> Your appointment has been booked</h1> </div> </div> </div> <div class="text"> <div class="bookbox"> <h1 class="heading-large" style="padding-bottom:20px;color:#231f20;">Your Appointment Details</h1> <ul style="padding-bottom:20px;list-style-type: none;"> <li style="padding-left: 0px !important;"> <a href="#" class="icomoon icomoon-calendar">Add to your calendar</a> </li> <li style="padding-left: 0px !important;"> <a href="#" class="icomoon icomoon-location" data-toggle="modal" data-target="#map">Show a map</a> </li> <li style="padding-left: 0px !important;"> <a href="#" class="icomoon icomoon-phone">Set Text Reminders</a> </li> </ul> {% include 'book-an-appointment/appointment-summary.html' %} </div> <div style="text-align:center;padding-top:20px;"> <p> <a class="button " href="/book-an-appointment/home-screen" style="color:#fff">Finish and return to the home screen</a> </p> </div> </div> <!-- MODALS --> <div class="container"> <!-- Modal CHANGE POSTCODE START --> <div class="modal fade" id="map" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">See on a map</h4> </div> <div class=" " style="padding:20px;"> <iframe width="450" height="250" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?key={{gmap_key}}&q={{clinic.location|url_encode}}&zoom=14" allowfullscreen> </iframe> </div> <div class="modal-footer" style="border-top:0px;"></div> </div> </div> </div> <!-- Modal CHANGE POSTCODE END --> </div> </main> {% endblock %}
{ "content_hash": "ee3140681c59be70ac6c808f612b60f1", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 135, "avg_line_length": 40.25757575757576, "alnum_prop": 0.5912683477606323, "repo_name": "st3v3nhunt/prototype-ers", "id": "b06a5720b04615908b91b27e84212190bee7874b", "size": "2657", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/book-an-appointment/confirmation.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "129031" }, { "name": "HTML", "bytes": "861142" }, { "name": "JavaScript", "bytes": "61952" }, { "name": "Ruby", "bytes": "299" }, { "name": "Shell", "bytes": "929" } ], "symlink_target": "" }
def do_something (name, address, phone_num) end
{ "content_hash": "cacbce0aed05962f79382dee7062a83c", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 43, "avg_line_length": 23.5, "alnum_prop": 0.7659574468085106, "repo_name": "FrizzBolt/phase-0", "id": "300d6758100a21581744bdf8e5779b5aee670bf3", "size": "139", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "week-4/define-method/my_solution.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4627" }, { "name": "HTML", "bytes": "29715" }, { "name": "JavaScript", "bytes": "34231" }, { "name": "Ruby", "bytes": "111592" } ], "symlink_target": "" }
title: Slides permalink: /slides/ layout: page profile: false --- <ul class="archive-list"> {% for slide in site.data.slides %} <li> <a href="/slides/{{ slide.path }}/">{{ slide.name }}</a> <div class="iframe-wrapper"><iframe src="/slides/{{ slide.path }}/"></iframe></div> </li> {% endfor %} </ul>
{ "content_hash": "83589258653ead1d2c9d91c95809b91b", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 88, "avg_line_length": 20, "alnum_prop": 0.58125, "repo_name": "aqafiam/aqafiam.github.io", "id": "a16771f718ea6bbe7eacd4f43eb2ddab88ac606b", "size": "324", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "slides/index.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "222152" }, { "name": "HTML", "bytes": "37337" }, { "name": "JavaScript", "bytes": "856733" }, { "name": "PHP", "bytes": "2441" }, { "name": "Ruby", "bytes": "4930" } ], "symlink_target": "" }
#ifndef MC_SPID_H_ #define MC_SPID_H_ /** Service provider Identifier type. */ typedef uint32_t mcSpid_t; /** SPID value used as free marker in root containers. */ static const mcSpid_t MC_SPID_FREE = 0xFFFFFFFF; /** Reserved SPID value. */ static const mcSpid_t MC_SPID_RESERVED = 0; /** SPID for system applications. */ static const mcSpid_t MC_SPID_SYSTEM = 0xFFFFFFFE; #endif // MC_SPID_H_ /** @} */
{ "content_hash": "25152d8e9e157301d0ae28eba9041773", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 57, "avg_line_length": 18.043478260869566, "alnum_prop": 0.6795180722891566, "repo_name": "indashnet/InDashNet.Open.UN2000", "id": "2e8f80c7457b02968e51f619d0b6954813a89185", "size": "1980", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "android/hardware/samsung_slsi/exynos5/mobicore/common/MobiCore/inc/mcSpid.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import pygame as pg from ext import evthandler as eh import conf from level import Level class Title: def __init__ (self, game, event_handler, ID = 0): self.game = game self.event_handler = event_handler self.level_ID = ID self.frame = conf.FRAME event_handler.add_event_handlers({ pg.MOUSEBUTTONDOWN: self.start }) event_handler.add_key_handlers([ (conf.KEYS_NEXT, self.start, eh.MODE_ONDOWN), (conf.KEYS_BACK, lambda *args: self.game.quit(), eh.MODE_ONDOWN) ]) def start (self, *args): self.game.start_backend(Level, self.level_ID) def update (self): pass def draw (self, screen): if self.dirty: # BG screen.fill(conf.BG) # text w, h = self.game.res x = conf.TITLE_PADDING * w y = conf.TITLE_PADDING * h w -= 2 * x font = (conf.FONT, conf.FONT_SIZE * h, False) font_args = (font, conf.TITLE_TEXT, conf.FONT_COLOUR, None, w) sfc = self.game.img(font_args)[0] screen.blit(sfc, (x, y)) self.dirty = False return True else: return False
{ "content_hash": "b708d522612f879379da32bc0e60b239", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 76, "avg_line_length": 29.209302325581394, "alnum_prop": 0.5294585987261147, "repo_name": "ikn/sequence", "id": "5c9d642a67059873ea4b40722f6ff3eca55fae02", "size": "1256", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sequence/title.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "44264" }, { "name": "Shell", "bytes": "202" } ], "symlink_target": "" }
#ifndef COUNTER_H_ #define COUNTER_H_ #include "OS_Types.h" #include "OS_cfg.h" #include "common.h" /************************************************************************************ * COUNTER TYPES * ************************************************************************************/ typedef struct { BYTE AlarmsCount; AlarmType* AlarmRef; TickType MaxAllowedValue; TickType MinCycle; TickType TicksPerBase; } CounterConstType; typedef struct { TickType Time; }CounterVarType; /************************************************************************************ * EXPORTED DATA * ************************************************************************************/ extern CounterVarType CountersVar[]; extern const CounterConstType CountersConst[]; /************************************************************************************ * EXPORTED FUNCTION * ************************************************************************************/ extern StatusType IAdvanceCounter(CounterType CounterID); extern AlarmIncrementType IncrementAlarm(AlarmType AlarmID, AlarmIncrementType Increment); extern CounterIncrementType IncrementCounter(CounterType CounterID, CounterIncrementType Increment); extern const AlarmType COUNTER_1_LIST[]; extern CounterVarType CountersVar[]; extern const CounterConstType CountersConst[]; #endif /*COUNTER_H_*/
{ "content_hash": "8468ce43f28fe1031e7b6c6bdd91f81e", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 100, "avg_line_length": 44.542857142857144, "alnum_prop": 0.43553559974342526, "repo_name": "janiex/OSEK_GEN", "id": "0020606c1d76a53e9fc0e11787509ae75671b91f", "size": "1559", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NewOSEKGen/Includes/Counter.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3168" }, { "name": "Batchfile", "bytes": "15713" }, { "name": "C", "bytes": "404964" }, { "name": "C#", "bytes": "26088" }, { "name": "C++", "bytes": "21329" }, { "name": "Objective-C", "bytes": "46785" }, { "name": "Smalltalk", "bytes": "468466" } ], "symlink_target": "" }
/* * Description : All wrapper functions related to performing hashing. */ #ifndef _QUARK_HASH_H_ #define _QUARK_HASH_H_ #ifdef __cplusplus extern "C" { #endif #include <stddef.h> #include <stdint.h> #include "endian_utils.h" #include "sha256.h" /*----------------------------------------------------------------------------------------------------*/ /* Type Definitions */ /*----------------------------------------------------------------------------------------------------*/ enum { HASH_SHA256 = 1 }; union hash_ctx { QUARK_SHA256_CTX sha256; }; /*----------------------------------------------------------------------------------------------------*/ /* Function Prototypes */ /*----------------------------------------------------------------------------------------------------*/ void quark_hashInit(uint32_t hashAlgorithm, union hash_ctx* ctx); void quark_hashUpdate(uint32_t hashAlgorithm, union hash_ctx* ctx, const void* src, size_t srcLen); void quark_hashFinal(uint32_t hashAlgorithm, union hash_ctx* ctx, void* dst); void quark_hash(uint32_t hashAlgorithm, union hash_ctx* ctx, void* dst, const void* src, size_t srcLen); #ifdef __cplusplus } #endif #endif /* _QUARK_HASH_H */
{ "content_hash": "8b54f350adaf591407fe9111ca24ef1c", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 104, "avg_line_length": 27.285714285714285, "alnum_prop": 0.4158563949139865, "repo_name": "google/quark", "id": "26d0461d851ea691f288a326ae2c443ab6379948", "size": "1931", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/common/hash_wrappers.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "15975" }, { "name": "C", "bytes": "1624988" }, { "name": "CMake", "bytes": "10112" }, { "name": "Makefile", "bytes": "8730" }, { "name": "Objective-C", "bytes": "21502" }, { "name": "Perl", "bytes": "12545" }, { "name": "Roff", "bytes": "1504" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Text; using System.Windows.Forms; namespace AvatarTest { public partial class AvatarForm : Form { public AvatarForm() { InitializeComponent(); avatarControl = new AvatarAX.AvatarControl(); avatarControl.Name = "avatarControl"; avatarControl.OnLoadAvatar += OnLoadAvatar; avatarControl.OnLoadAnim += AddAnimation; loadAnimDialog.InitialDirectory = avatarControl.MediaDir + "\\anim\\amy"; loadAnimDialog.Filter = "Motion files|*.bvh"; twoPanes.Panel2.Controls.Add(avatarControl); dynamic config = avatarControl.LoadConfig("c:\\projects\\vixen\\data\\magicmirror\\amyconfig.json"); if ((config != null) && (config.mediadir != null)) avatarControl.MediaDir = config.mediadir; } /* * Called every time an avatar is loaded. * We load the green dress and put it on her. */ private void OnLoadAvatar(String name) { avatarControl.LoadGarment(avatarControl.ConfigOpts.defaultoutfit, null); } /* * Called every time an animation is loaded. * We add the name of the animation to a list box. */ private void AddAnimation(String name, String url) { if (!animationsLoaded.Items.Contains(name)) animationsLoaded.Items.Add(name); } /* * Called when "pause" button is clicked. * Stops the currently running animation. */ private void pauseButton_Click(object sender, EventArgs e) { try { string selected = animationsLoaded.SelectedItem as string; if (selected != null) avatarControl.PauseAnimation(selected); } catch (Exception ex) { Vixen.SharedWorld.LogError("OnPauseAnimation EXCEPTION: " + ex.Message); } } /* * Called when an animation is selected. * Plays the selected animation. */ private void OnAnimSelected(object sender, EventArgs e) { try { string selected = animationsLoaded.SelectedItem as string; if (selected != null) avatarControl.PlayAnimation(selected, 0); } catch (Exception ex) { Vixen.SharedWorld.LogError("OnAnimSelected EXCEPTION: " + ex.Message); } } /* * Called when the "load" button is pressed. * Brings up a file open dialog to select the animation file to open. */ private void OnOpenAnimFile(object sender, EventArgs e) { DialogResult result = loadAnimDialog.ShowDialog(); if (result == DialogResult.OK) avatarControl.LoadAnimation(loadAnimDialog.FileName, null); } } }
{ "content_hash": "da66b1a24b76558cdabfbef7b3b6a4d3", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 103, "avg_line_length": 26.239583333333332, "alnum_prop": 0.6994839221913458, "repo_name": "Caprica666/vixen", "id": "accaef7645fc88a8c9744cdacfb29f8ab9489ca1", "size": "2521", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/MagicMirror/ActiveX/AvatarTest/AvatarForm.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "497" }, { "name": "C", "bytes": "135338" }, { "name": "C#", "bytes": "1100615" }, { "name": "C++", "bytes": "4679902" }, { "name": "CMake", "bytes": "8595" }, { "name": "Clarion", "bytes": "5270" }, { "name": "GLSL", "bytes": "39084" }, { "name": "HLSL", "bytes": "43657" }, { "name": "HTML", "bytes": "70015" }, { "name": "Java", "bytes": "524219" }, { "name": "Makefile", "bytes": "5635" }, { "name": "Mathematica", "bytes": "1229773" }, { "name": "Objective-C", "bytes": "1332" }, { "name": "XSLT", "bytes": "8061" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pl"> <head> <!-- Generated by javadoc (1.8.0_60) on Wed Mar 30 11:39:23 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class play.libs.F.None (Play! API)</title> <meta name="date" content="2016-03-30"> <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 Class play.libs.F.None (Play! 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><a href="../../../play/libs/F.None.html" title="class in play.libs">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?play/libs/class-use/F.None.html" target="_top">Frames</a></li> <li><a href="F.None.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"> <h2 title="Uses of Class play.libs.F.None" class="title">Uses of Class<br>play.libs.F.None</h2> </div> <div class="classUseContainer"> <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="../../../play/libs/F.None.html" title="class in play.libs">F.None</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="#play.libs">play.libs</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="play.libs"> <!-- --> </a> <h3>Uses of <a href="../../../play/libs/F.None.html" title="class in play.libs">F.None</a> in <a href="../../../play/libs/package-summary.html">play.libs</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../play/libs/package-summary.html">play.libs</a> declared as <a href="../../../play/libs/F.None.html" title="class in play.libs">F.None</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>static <a href="../../../play/libs/F.None.html" title="class in play.libs">F.None</a>&lt;java.lang.Object&gt;</code></td> <td class="colLast"><span class="typeNameLabel">F.</span><code><span class="memberNameLink"><a href="../../../play/libs/F.html#None">None</a></span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../play/libs/package-summary.html">play.libs</a> that return <a href="../../../play/libs/F.None.html" title="class in play.libs">F.None</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>static &lt;T&gt;&nbsp;<a href="../../../play/libs/F.None.html" title="class in play.libs">F.None</a>&lt;T&gt;</code></td> <td class="colLast"><span class="typeNameLabel">F.Option.</span><code><span class="memberNameLink"><a href="../../../play/libs/F.Option.html#None--">None</a></span>()</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </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><a href="../../../play/libs/F.None.html" title="class in play.libs">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?play/libs/class-use/F.None.html" target="_top">Frames</a></li> <li><a href="F.None.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><a href="http://guillaume.bort.fr">Guillaume Bort</a> &amp; <a href="http://www.zenexity.fr">zenexity</a> - Distributed under <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2 licence</a>, without any warrantly</small></p> </body> </html>
{ "content_hash": "48a88b2579e0d086550ffeb4d997c641", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 267, "avg_line_length": 39.04469273743017, "alnum_prop": 0.6295607383030476, "repo_name": "play1-maven-plugin/play1-maven-plugin.github.io", "id": "822420a9423f8cab22357ab5f1113378e5396208", "size": "6989", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "external-apidocs/com/google/code/maven-play-plugin/org/playframework/play/1.4.2/play/libs/class-use/F.None.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "245466" }, { "name": "HTML", "bytes": "161333450" }, { "name": "JavaScript", "bytes": "11578" } ], "symlink_target": "" }
<?php namespace Smalot\PdfParser; use Smalot\PdfParser\Element\ElementArray; use Smalot\PdfParser\Element\ElementMissing; use Smalot\PdfParser\Element\ElementStruct; use Smalot\PdfParser\Element\ElementXRef; /** * Class Header * * @package Smalot\PdfParser */ class Header { /** * @var Document */ protected $document = null; /** * @var Element[] */ protected $elements = null; /** * @param Element[] $elements List of elements. * @param Document $document Document. */ public function __construct($elements = array(), Document $document = null) { $this->elements = $elements; $this->document = $document; } /** * Returns all elements. * * @return mixed */ public function getElements() { foreach ($this->elements as $name => $element) { $this->resolveXRef($name); } return $this->elements; } /** * Used only for debug. * * @return array */ public function getElementTypes() { $types = array(); foreach ($this->elements as $key => $element) { $types[$key] = get_class($element); } return $types; } /** * @param bool $deep * * @return array */ public function getDetails($deep = true) { $values = array(); $elements = $this->getElements(); foreach ($elements as $key => $element) { if ($element instanceof Header && $deep) { $values[$key] = $element->getDetails($deep); } elseif ($element instanceof Object && $deep) { $values[$key] = $element->getDetails(false); } elseif ($element instanceof ElementArray) { if ($deep) { $values[$key] = $element->getDetails(); } } elseif ($element instanceof Element) { $values[$key] = (string) $element; } } return $values; } /** * Indicate if an element name is available in header. * * @param string $name The name of the element * * @return bool */ public function has($name) { if (array_key_exists($name, $this->elements)) { return true; } else { return false; } } /** * @param string $name * * @return Element|Object */ public function get($name) { if (array_key_exists($name, $this->elements)) { return $this->resolveXRef($name); } return new ElementMissing(null, null); } /** * Resolve XRef to object. * * @param string $name * * @return Element|Object * @throws \Exception */ protected function resolveXRef($name) { if (($obj = $this->elements[$name]) instanceof ElementXRef && !is_null($this->document)) { /** @var ElementXRef $obj */ $object = $this->document->getObjectById($obj->getId()); if (is_null($object)) { return null; } // Update elements list for future calls. $this->elements[$name] = $object; } return $this->elements[$name]; } /** * @param string $content The content to parse * @param Document $document The document * @param int $position The new position of the cursor after parsing * * @return Header */ public static function parse($content, Document $document, &$position = 0) { /** @var Header $header */ if (substr(trim($content), 0, 2) == '<<') { $header = ElementStruct::parse($content, $document, $position); } else { $elements = ElementArray::parse($content, $document, $position); if ($elements) { $header = new self($elements->getRawContent(), null);//$document); } else { $header = new self(array(), $document); } } if ($header) { return $header; } else { // Build an empty header. return new self(array(), $document); } } }
{ "content_hash": "7cc4901c41aea3f3d4c0dc2526d0e790", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 98, "avg_line_length": 23.87150837988827, "alnum_prop": 0.5076058974959046, "repo_name": "fweber1/Annies-Ancestors", "id": "3c4fcac3769957f98d6f5695d27685f1d393bb8b", "size": "5332", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "php/vendor/smalot/pdfparser/src/Smalot/PdfParser/Header.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1064" }, { "name": "Awk", "bytes": "4697" }, { "name": "Batchfile", "bytes": "6467" }, { "name": "CSS", "bytes": "1554235" }, { "name": "ColdFusion", "bytes": "51038" }, { "name": "HTML", "bytes": "2801894" }, { "name": "JavaScript", "bytes": "7729578" }, { "name": "Makefile", "bytes": "7342" }, { "name": "PHP", "bytes": "36634191" }, { "name": "Python", "bytes": "16289" }, { "name": "Roff", "bytes": "29" }, { "name": "Shell", "bytes": "755" }, { "name": "Smarty", "bytes": "38024" }, { "name": "XSLT", "bytes": "11742" } ], "symlink_target": "" }
package OSMPBF import proto "github.com/golang/protobuf/proto" import json "encoding/json" import math "math" // Reference proto, json, and math imports to suppress error if they are not otherwise used. var _ = proto.Marshal var _ = &json.SyntaxError{} var _ = math.Inf type Relation_MemberType int32 const ( Relation_NODE Relation_MemberType = 0 Relation_WAY Relation_MemberType = 1 Relation_RELATION Relation_MemberType = 2 ) var Relation_MemberType_name = map[int32]string{ 0: "NODE", 1: "WAY", 2: "RELATION", } var Relation_MemberType_value = map[string]int32{ "NODE": 0, "WAY": 1, "RELATION": 2, } func (x Relation_MemberType) Enum() *Relation_MemberType { p := new(Relation_MemberType) *p = x return p } func (x Relation_MemberType) String() string { return proto.EnumName(Relation_MemberType_name, int32(x)) } func (x *Relation_MemberType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Relation_MemberType_value, data, "Relation_MemberType") if err != nil { return err } *x = Relation_MemberType(value) return nil } type HeaderBlock struct { Bbox *HeaderBBox `protobuf:"bytes,1,opt,name=bbox" json:"bbox,omitempty"` // Additional tags to aid in parsing this dataset RequiredFeatures []string `protobuf:"bytes,4,rep,name=required_features" json:"required_features,omitempty"` OptionalFeatures []string `protobuf:"bytes,5,rep,name=optional_features" json:"optional_features,omitempty"` Writingprogram *string `protobuf:"bytes,16,opt,name=writingprogram" json:"writingprogram,omitempty"` Source *string `protobuf:"bytes,17,opt,name=source" json:"source,omitempty"` // replication timestamp, expressed in seconds since the epoch, // otherwise the same value as in the "timestamp=..." field // in the state.txt file used by Osmosis OsmosisReplicationTimestamp *int64 `protobuf:"varint,32,opt,name=osmosis_replication_timestamp" json:"osmosis_replication_timestamp,omitempty"` // replication sequence number (sequenceNumber in state.txt) OsmosisReplicationSequenceNumber *int64 `protobuf:"varint,33,opt,name=osmosis_replication_sequence_number" json:"osmosis_replication_sequence_number,omitempty"` // replication base URL (from Osmosis' configuration.txt file) OsmosisReplicationBaseUrl *string `protobuf:"bytes,34,opt,name=osmosis_replication_base_url" json:"osmosis_replication_base_url,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *HeaderBlock) Reset() { *m = HeaderBlock{} } func (m *HeaderBlock) String() string { return proto.CompactTextString(m) } func (*HeaderBlock) ProtoMessage() {} func (m *HeaderBlock) GetBbox() *HeaderBBox { if m != nil { return m.Bbox } return nil } func (m *HeaderBlock) GetRequiredFeatures() []string { if m != nil { return m.RequiredFeatures } return nil } func (m *HeaderBlock) GetOptionalFeatures() []string { if m != nil { return m.OptionalFeatures } return nil } func (m *HeaderBlock) GetWritingprogram() string { if m != nil && m.Writingprogram != nil { return *m.Writingprogram } return "" } func (m *HeaderBlock) GetSource() string { if m != nil && m.Source != nil { return *m.Source } return "" } func (m *HeaderBlock) GetOsmosisReplicationTimestamp() int64 { if m != nil && m.OsmosisReplicationTimestamp != nil { return *m.OsmosisReplicationTimestamp } return 0 } func (m *HeaderBlock) GetOsmosisReplicationSequenceNumber() int64 { if m != nil && m.OsmosisReplicationSequenceNumber != nil { return *m.OsmosisReplicationSequenceNumber } return 0 } func (m *HeaderBlock) GetOsmosisReplicationBaseUrl() string { if m != nil && m.OsmosisReplicationBaseUrl != nil { return *m.OsmosisReplicationBaseUrl } return "" } type HeaderBBox struct { Left *int64 `protobuf:"zigzag64,1,req,name=left" json:"left,omitempty"` Right *int64 `protobuf:"zigzag64,2,req,name=right" json:"right,omitempty"` Top *int64 `protobuf:"zigzag64,3,req,name=top" json:"top,omitempty"` Bottom *int64 `protobuf:"zigzag64,4,req,name=bottom" json:"bottom,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *HeaderBBox) Reset() { *m = HeaderBBox{} } func (m *HeaderBBox) String() string { return proto.CompactTextString(m) } func (*HeaderBBox) ProtoMessage() {} func (m *HeaderBBox) GetLeft() int64 { if m != nil && m.Left != nil { return *m.Left } return 0 } func (m *HeaderBBox) GetRight() int64 { if m != nil && m.Right != nil { return *m.Right } return 0 } func (m *HeaderBBox) GetTop() int64 { if m != nil && m.Top != nil { return *m.Top } return 0 } func (m *HeaderBBox) GetBottom() int64 { if m != nil && m.Bottom != nil { return *m.Bottom } return 0 } type PrimitiveBlock struct { Stringtable *StringTable `protobuf:"bytes,1,req,name=stringtable" json:"stringtable,omitempty"` Primitivegroup []*PrimitiveGroup `protobuf:"bytes,2,rep,name=primitivegroup" json:"primitivegroup,omitempty"` // Granularity, units of nanodegrees, used to store coordinates in this block Granularity *int32 `protobuf:"varint,17,opt,name=granularity,def=100" json:"granularity,omitempty"` // Offset value between the output coordinates coordinates and the granularity grid in unites of nanodegrees. LatOffset *int64 `protobuf:"varint,19,opt,name=lat_offset,def=0" json:"lat_offset,omitempty"` LonOffset *int64 `protobuf:"varint,20,opt,name=lon_offset,def=0" json:"lon_offset,omitempty"` // Granularity of dates, normally represented in units of milliseconds since the 1970 epoch. DateGranularity *int32 `protobuf:"varint,18,opt,name=date_granularity,def=1000" json:"date_granularity,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *PrimitiveBlock) Reset() { *m = PrimitiveBlock{} } func (m *PrimitiveBlock) String() string { return proto.CompactTextString(m) } func (*PrimitiveBlock) ProtoMessage() {} const Default_PrimitiveBlock_Granularity int32 = 100 const Default_PrimitiveBlock_LatOffset int64 = 0 const Default_PrimitiveBlock_LonOffset int64 = 0 const Default_PrimitiveBlock_DateGranularity int32 = 1000 func (m *PrimitiveBlock) GetStringtable() *StringTable { if m != nil { return m.Stringtable } return nil } func (m *PrimitiveBlock) GetPrimitivegroup() []*PrimitiveGroup { if m != nil { return m.Primitivegroup } return nil } func (m *PrimitiveBlock) GetGranularity() int32 { if m != nil && m.Granularity != nil { return *m.Granularity } return Default_PrimitiveBlock_Granularity } func (m *PrimitiveBlock) GetLatOffset() int64 { if m != nil && m.LatOffset != nil { return *m.LatOffset } return Default_PrimitiveBlock_LatOffset } func (m *PrimitiveBlock) GetLonOffset() int64 { if m != nil && m.LonOffset != nil { return *m.LonOffset } return Default_PrimitiveBlock_LonOffset } func (m *PrimitiveBlock) GetDateGranularity() int32 { if m != nil && m.DateGranularity != nil { return *m.DateGranularity } return Default_PrimitiveBlock_DateGranularity } // Group of OSMPrimitives. All primitives in a group must be the same type. type PrimitiveGroup struct { Nodes []*Node `protobuf:"bytes,1,rep,name=nodes" json:"nodes,omitempty"` Dense *DenseNodes `protobuf:"bytes,2,opt,name=dense" json:"dense,omitempty"` Ways []*Way `protobuf:"bytes,3,rep,name=ways" json:"ways,omitempty"` Relations []*Relation `protobuf:"bytes,4,rep,name=relations" json:"relations,omitempty"` Changesets []*ChangeSet `protobuf:"bytes,5,rep,name=changesets" json:"changesets,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *PrimitiveGroup) Reset() { *m = PrimitiveGroup{} } func (m *PrimitiveGroup) String() string { return proto.CompactTextString(m) } func (*PrimitiveGroup) ProtoMessage() {} func (m *PrimitiveGroup) GetNodes() []*Node { if m != nil { return m.Nodes } return nil } func (m *PrimitiveGroup) GetDense() *DenseNodes { if m != nil { return m.Dense } return nil } func (m *PrimitiveGroup) GetWays() []*Way { if m != nil { return m.Ways } return nil } func (m *PrimitiveGroup) GetRelations() []*Relation { if m != nil { return m.Relations } return nil } func (m *PrimitiveGroup) GetChangesets() []*ChangeSet { if m != nil { return m.Changesets } return nil } // * String table, contains the common strings in each block. // // Note that we reserve index '0' as a delimiter, so the entry at that // index in the table is ALWAYS blank and unused. // type StringTable struct { S []string `protobuf:"bytes,1,rep,name=s" json:"s,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *StringTable) Reset() { *m = StringTable{} } func (m *StringTable) String() string { return proto.CompactTextString(m) } func (*StringTable) ProtoMessage() {} func (m *StringTable) GetS() []string { if m != nil { return m.S } return nil } // Optional metadata that may be included into each primitive. type Info struct { Version *int32 `protobuf:"varint,1,opt,name=version,def=-1" json:"version,omitempty"` Timestamp *int64 `protobuf:"varint,2,opt,name=timestamp" json:"timestamp,omitempty"` Changeset *int64 `protobuf:"varint,3,opt,name=changeset" json:"changeset,omitempty"` Uid *int32 `protobuf:"varint,4,opt,name=uid" json:"uid,omitempty"` UserSid *uint32 `protobuf:"varint,5,opt,name=user_sid" json:"user_sid,omitempty"` // The visible flag is used to store history information. It indicates that // the current object version has been created by a delete operation on the // OSM API. // When a writer sets this flag, it MUST add a required_features tag with // value "HistoricalInformation" to the HeaderBlock. // If this flag is not available for some object it MUST be assumed to be // true if the file has the required_features tag "HistoricalInformation" // set. Visible *bool `protobuf:"varint,6,opt,name=visible" json:"visible,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Info) Reset() { *m = Info{} } func (m *Info) String() string { return proto.CompactTextString(m) } func (*Info) ProtoMessage() {} const Default_Info_Version int32 = -1 func (m *Info) GetVersion() int32 { if m != nil && m.Version != nil { return *m.Version } return Default_Info_Version } func (m *Info) GetTimestamp() int64 { if m != nil && m.Timestamp != nil { return *m.Timestamp } return 0 } func (m *Info) GetChangeset() int64 { if m != nil && m.Changeset != nil { return *m.Changeset } return 0 } func (m *Info) GetUid() int32 { if m != nil && m.Uid != nil { return *m.Uid } return 0 } func (m *Info) GetUserSid() uint32 { if m != nil && m.UserSid != nil { return *m.UserSid } return 0 } func (m *Info) GetVisible() bool { if m != nil && m.Visible != nil { return *m.Visible } return false } // * Optional metadata that may be included into each primitive. Special dense format used in DenseNodes. type DenseInfo struct { Version []int32 `protobuf:"varint,1,rep,packed,name=version" json:"version,omitempty"` Timestamp []int64 `protobuf:"zigzag64,2,rep,packed,name=timestamp" json:"timestamp,omitempty"` Changeset []int64 `protobuf:"zigzag64,3,rep,packed,name=changeset" json:"changeset,omitempty"` Uid []int32 `protobuf:"zigzag32,4,rep,packed,name=uid" json:"uid,omitempty"` UserSid []int32 `protobuf:"zigzag32,5,rep,packed,name=user_sid" json:"user_sid,omitempty"` // The visible flag is used to store history information. It indicates that // the current object version has been created by a delete operation on the // OSM API. // When a writer sets this flag, it MUST add a required_features tag with // value "HistoricalInformation" to the HeaderBlock. // If this flag is not available for some object it MUST be assumed to be // true if the file has the required_features tag "HistoricalInformation" // set. Visible []bool `protobuf:"varint,6,rep,packed,name=visible" json:"visible,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *DenseInfo) Reset() { *m = DenseInfo{} } func (m *DenseInfo) String() string { return proto.CompactTextString(m) } func (*DenseInfo) ProtoMessage() {} func (m *DenseInfo) GetVersion() []int32 { if m != nil { return m.Version } return nil } func (m *DenseInfo) GetTimestamp() []int64 { if m != nil { return m.Timestamp } return nil } func (m *DenseInfo) GetChangeset() []int64 { if m != nil { return m.Changeset } return nil } func (m *DenseInfo) GetUid() []int32 { if m != nil { return m.Uid } return nil } func (m *DenseInfo) GetUserSid() []int32 { if m != nil { return m.UserSid } return nil } func (m *DenseInfo) GetVisible() []bool { if m != nil { return m.Visible } return nil } // THIS IS STUB DESIGN FOR CHANGESETS. NOT USED RIGHT NOW. // TODO: REMOVE THIS? type ChangeSet struct { Id *int64 `protobuf:"varint,1,req,name=id" json:"id,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *ChangeSet) Reset() { *m = ChangeSet{} } func (m *ChangeSet) String() string { return proto.CompactTextString(m) } func (*ChangeSet) ProtoMessage() {} func (m *ChangeSet) GetId() int64 { if m != nil && m.Id != nil { return *m.Id } return 0 } type Node struct { Id *int64 `protobuf:"zigzag64,1,req,name=id" json:"id,omitempty"` // Parallel arrays. Keys []uint32 `protobuf:"varint,2,rep,packed,name=keys" json:"keys,omitempty"` Vals []uint32 `protobuf:"varint,3,rep,packed,name=vals" json:"vals,omitempty"` Info *Info `protobuf:"bytes,4,opt,name=info" json:"info,omitempty"` Lat *int64 `protobuf:"zigzag64,8,req,name=lat" json:"lat,omitempty"` Lon *int64 `protobuf:"zigzag64,9,req,name=lon" json:"lon,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Node) Reset() { *m = Node{} } func (m *Node) String() string { return proto.CompactTextString(m) } func (*Node) ProtoMessage() {} func (m *Node) GetId() int64 { if m != nil && m.Id != nil { return *m.Id } return 0 } func (m *Node) GetKeys() []uint32 { if m != nil { return m.Keys } return nil } func (m *Node) GetVals() []uint32 { if m != nil { return m.Vals } return nil } func (m *Node) GetInfo() *Info { if m != nil { return m.Info } return nil } func (m *Node) GetLat() int64 { if m != nil && m.Lat != nil { return *m.Lat } return 0 } func (m *Node) GetLon() int64 { if m != nil && m.Lon != nil { return *m.Lon } return 0 } type DenseNodes struct { Id []int64 `protobuf:"zigzag64,1,rep,packed,name=id" json:"id,omitempty"` // repeated Info info = 4; Denseinfo *DenseInfo `protobuf:"bytes,5,opt,name=denseinfo" json:"denseinfo,omitempty"` Lat []int64 `protobuf:"zigzag64,8,rep,packed,name=lat" json:"lat,omitempty"` Lon []int64 `protobuf:"zigzag64,9,rep,packed,name=lon" json:"lon,omitempty"` // Special packing of keys and vals into one array. May be empty if all nodes in this block are tagless. KeysVals []int32 `protobuf:"varint,10,rep,packed,name=keys_vals" json:"keys_vals,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *DenseNodes) Reset() { *m = DenseNodes{} } func (m *DenseNodes) String() string { return proto.CompactTextString(m) } func (*DenseNodes) ProtoMessage() {} func (m *DenseNodes) GetId() []int64 { if m != nil { return m.Id } return nil } func (m *DenseNodes) GetDenseinfo() *DenseInfo { if m != nil { return m.Denseinfo } return nil } func (m *DenseNodes) GetLat() []int64 { if m != nil { return m.Lat } return nil } func (m *DenseNodes) GetLon() []int64 { if m != nil { return m.Lon } return nil } func (m *DenseNodes) GetKeysVals() []int32 { if m != nil { return m.KeysVals } return nil } type Way struct { Id *int64 `protobuf:"varint,1,req,name=id" json:"id,omitempty"` // Parallel arrays. Keys []uint32 `protobuf:"varint,2,rep,packed,name=keys" json:"keys,omitempty"` Vals []uint32 `protobuf:"varint,3,rep,packed,name=vals" json:"vals,omitempty"` Info *Info `protobuf:"bytes,4,opt,name=info" json:"info,omitempty"` Refs []int64 `protobuf:"zigzag64,8,rep,packed,name=refs" json:"refs,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Way) Reset() { *m = Way{} } func (m *Way) String() string { return proto.CompactTextString(m) } func (*Way) ProtoMessage() {} func (m *Way) GetId() int64 { if m != nil && m.Id != nil { return *m.Id } return 0 } func (m *Way) GetKeys() []uint32 { if m != nil { return m.Keys } return nil } func (m *Way) GetVals() []uint32 { if m != nil { return m.Vals } return nil } func (m *Way) GetInfo() *Info { if m != nil { return m.Info } return nil } func (m *Way) GetRefs() []int64 { if m != nil { return m.Refs } return nil } type Relation struct { Id *int64 `protobuf:"varint,1,req,name=id" json:"id,omitempty"` // Parallel arrays. Keys []uint32 `protobuf:"varint,2,rep,packed,name=keys" json:"keys,omitempty"` Vals []uint32 `protobuf:"varint,3,rep,packed,name=vals" json:"vals,omitempty"` Info *Info `protobuf:"bytes,4,opt,name=info" json:"info,omitempty"` // Parallel arrays RolesSid []int32 `protobuf:"varint,8,rep,packed,name=roles_sid" json:"roles_sid,omitempty"` Memids []int64 `protobuf:"zigzag64,9,rep,packed,name=memids" json:"memids,omitempty"` Types []Relation_MemberType `protobuf:"varint,10,rep,packed,name=types,enum=OSMPBF.Relation_MemberType" json:"types,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Relation) Reset() { *m = Relation{} } func (m *Relation) String() string { return proto.CompactTextString(m) } func (*Relation) ProtoMessage() {} func (m *Relation) GetId() int64 { if m != nil && m.Id != nil { return *m.Id } return 0 } func (m *Relation) GetKeys() []uint32 { if m != nil { return m.Keys } return nil } func (m *Relation) GetVals() []uint32 { if m != nil { return m.Vals } return nil } func (m *Relation) GetInfo() *Info { if m != nil { return m.Info } return nil } func (m *Relation) GetRolesSid() []int32 { if m != nil { return m.RolesSid } return nil } func (m *Relation) GetMemids() []int64 { if m != nil { return m.Memids } return nil } func (m *Relation) GetTypes() []Relation_MemberType { if m != nil { return m.Types } return nil } func init() { proto.RegisterEnum("OSMPBF.Relation_MemberType", Relation_MemberType_name, Relation_MemberType_value) }
{ "content_hash": "d102725ca206b565a56063bd476077f0", "timestamp": "", "source": "github", "line_count": 674, "max_line_length": 161, "avg_line_length": 27.632047477744806, "alnum_prop": 0.6740764604810997, "repo_name": "buckhx/diglet", "id": "d96605a22004556d1a3d10c8d97c0924e10ead32", "size": "18704", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "vendor/github.com/qedus/osmpbf/OSMPBF/osmformat.pb.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10183" }, { "name": "Go", "bytes": "115176" }, { "name": "HTML", "bytes": "225527" }, { "name": "JavaScript", "bytes": "238094" }, { "name": "Makefile", "bytes": "1364" }, { "name": "Protocol Buffer", "bytes": "3042" }, { "name": "Python", "bytes": "1217" } ], "symlink_target": "" }
interface FlexibleStat { /** A localized name for the data point, suitable for display to users. The text is title cased. */ name: string; /** The type of stat this represents, it is one of the following options: - Count - Duration */ type: string; /** The ID that uniquely identifies this stat. */ id: guid; /* Internal use only. Do not use. contentId: guid; */ } /** A list of defined flexible stat entries for the title. There is no significance to the ordering. */ declare type FlexibleStats = FlexibleStat[];
{ "content_hash": "f8b1abc6d5181f845cbf5e6174c7169c", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 84, "avg_line_length": 20.322580645161292, "alnum_prop": 0.5920634920634921, "repo_name": "DerFlatulator/haloapi.js", "id": "d6b27153b28b064a284e1fe2445f0834a4e8393c", "size": "630", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ts/metadata/FlexibleStats.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "57083" }, { "name": "TypeScript", "bytes": "21290" } ], "symlink_target": "" }
package com.interopbridges.scx.mbeans; import java.io.StringWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Set; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.QueryExp; import com.interopbridges.scx.ScxException; import com.interopbridges.scx.ScxExceptionCode; import com.interopbridges.scx.jmx.IJMX; import com.interopbridges.scx.log.ILogger; import com.interopbridges.scx.log.LoggingFactory; import com.interopbridges.scx.xml.MBeanTransformer; /** * <p> * Retrieves MBeans from the JMX Store and transforms them to XML. * </p> * * @author Christopher Crammond * */ public class MBeanGetter { /** * <p> * Abstraction representing the JMX Store * </p> */ protected List<IJMX> _jmxStores; /** * <p> * Logger for the class. * </p> */ protected ILogger _logger; /** * <p> * Default Constructor * </p> */ public MBeanGetter(List<IJMX> jmxStores) { this._jmxStores = jmxStores; this._logger = LoggingFactory.getLogger(); } /** * <p> * For a given mbean, generate the appropriate XML. This method is an * abstraction/wrapper for generating the XML. * </p> * * @param jmxQuery * JMX Query string * @param mbean * List of MBeans to tranform into XML * * @return Stream containing a XML representation of the MBean * * @throws ScxException * If there was an inspecting the MBean or if there was an error * generating the XML */ private StringWriter generateXmlforMBeans(String jmxQuery, HashMap<IJMX, Set<ObjectInstance>> mbeans, HashMap<String,String[]> Params) throws ScxException { MBeanTransformer mtf = new MBeanTransformer(); /* * pass _JMXQuery to MBeanTransformer.java. */ mtf.setJMXQuery(jmxQuery); return mtf.transformMultipleMBeans(mbeans, Params); } /** * <p> * Return a set of MBeans that match the given query. * </p> * * @param name * Name * * @param query * A JMX Query * * * @return List of matching MBeans which match the given query */ public List<ObjectName> getAllMatchingMBeans(ObjectName name, QueryExp query) throws IOException { List<ObjectName> ret = new ArrayList<ObjectName>(); for(int i=0;i<this._jmxStores.size();i++) { ret.addAll(this._jmxStores.get(i).queryNames(name, query)); } return ret; } /** * <p> * Get a XML representation of the the MBeans that match the given JMX Type. * </p> * * @param jmxQuery * JMX Query * * @throws ScxException * If there was a problem getting the MBean, inspecting it, or * transforming it to XML. For more details review the inner * exception. * */ public StringWriter getMBeansAsXml(String jmxQuery,HashMap<String,String[]> Params) throws ScxException, IOException { try { StringWriter xmlResponse = new StringWriter(); HashMap<IJMX, Set<ObjectInstance>> mbeans = getMBeans(jmxQuery); xmlResponse.append(this.generateXmlforMBeans(jmxQuery,mbeans,Params).getBuffer()); this._logger.finest(new StringBuffer("Resulting XML for query: ") .append(xmlResponse.toString()).toString()); return xmlResponse; } catch (NullPointerException npe) { /* * The only declared method to throw this exception is the creation * of the ObjectName. which cannot happen (at least as of this * writing) due to constructor having a string built in its * argument. */ throw new ScxException(ScxExceptionCode.NULL_POINTER_EXCEPTION, npe); } } /** * <p> * Get all MBeans that have an Objectname matching the input parameter. * All relevant JMX stores are checked for the matching MBeans. * </p> * * @param objectName * JMX Query * @return Map containing all matching MBeans and their associated MBean stores. * * @throws ScxException * If there was a problem getting the MBean, inspecting it, or * transforming it to XML. For more details review the inner * exception. * @throws MalformedObjectNameException * The format of the string does not correspond to a valid ObjectName. */ public HashMap<IJMX, Set<ObjectInstance>> getMBeans(String objectName) throws ScxException { int TotalMBeanCount=0; HashMap<IJMX, Set<ObjectInstance>> mbeans = new HashMap<IJMX,Set<ObjectInstance>>(); this._logger.finer(new StringBuffer("Executing query for MBeans: ") .append(objectName).toString()); ObjectName objName; try { // Try and use the String constructor of the ObjectName // this will fail if a property has embedded quotes in a property value // This JMXQuery will cause a failure - [interopbridges:Age=42,Name=Test"MBean's"] objName = new ObjectName(objectName); } catch (MalformedObjectNameException e) { /* * The argument to the ObjectName constructor * contains illegal characters */ try { // Try and use the key value pair constructor of the ObjectName // this will fail if a property has wildcard values // This JMXQuery will cause a failure - [interopbridges:Name=Test"MBean's",*] // If the complete MBeans ObjectName is used with no wildcard this will work correctly // [interopbridges:Name=Test"MBean's",Age=42] String dom = GetDomain (objectName); Hashtable<String, String> keyVal = SplitStringObjectNameToTokens (objectName); objName = new ObjectName(dom, keyVal); } catch (MalformedObjectNameException ee) { /* * At this point we have tried the String based constructor and the * hashtable based constructor and both have failed, we throw an * exception and don't process the request. */ throw new ScxException(ScxExceptionCode.MALFORMED_OBJECT_NAME, ee); } catch (NullPointerException npe) { /* * One of the parameters passed into the ObjectName constructor is null. */ throw new ScxException(ScxExceptionCode.NULL_POINTER_EXCEPTION, npe); } } catch (NullPointerException npe) { /* * The string passed into the ObjectName constructor is null. */ throw new ScxException(ScxExceptionCode.NULL_POINTER_EXCEPTION, npe); } try { for(int i=0;i<this._jmxStores.size();i++) { this._logger.fine(new StringBuffer("Query mbean store: ") .append(this._jmxStores.get(i).getClass().getName()).toString()); Set<ObjectInstance> theBeans = this._jmxStores.get(i).queryMBeans( objName, null); if(theBeans.size()>0) { mbeans.put(this._jmxStores.get(i), theBeans ); } TotalMBeanCount += theBeans.size(); } this._logger.finer(new StringBuffer("Found ").append(TotalMBeanCount) .append(" MBeans matching the ObjectName '").append( objectName).append("'").toString()); } catch (IOException ioe) { /* * The only declared method to throw this exception is queryMBeans * call */ throw new ScxException(ScxExceptionCode.IO_ERROR_EXCEPTION, ioe); } return mbeans; } /** * <p> * Get the domain part of the JMX Query. * </p> * * @param objName * JMX Query * @return String containing the domain part of the JMX Query. */ private String GetDomain (String objName) { String retval=""; int pos = objName.indexOf(':'); if(pos>=0) { retval = objName.substring(0, pos); } return(retval); } /** * <p> * Split up the JMX Query into <key><value> pairs. * </p> * * @param objName * JMX Query * @return Table containing Key, Value pairs for each property in the MBean objectname. * */ private Hashtable<String, String> SplitStringObjectNameToTokens (String objName) { Hashtable<String, String> result = new Hashtable<String, String>(); boolean inDoubleQuotes=false; int pos; // strip off the Domain portion pos = objName.indexOf(':'); String properties = objName.substring(pos+1); char[] name_chars = properties.toCharArray(); //Split string on ',' but only if not quoted pos = 0; for(int ix=0;ix<name_chars.length;ix++) { switch(name_chars[ix]) { case '"' : inDoubleQuotes = !inDoubleQuotes; break; case ',' : if(!inDoubleQuotes) { SplitAndAddValuePair(result, properties.substring(pos,ix)); pos=ix+1; } break; } } if(!inDoubleQuotes) { SplitAndAddValuePair(result, properties.substring(pos)); } return result; } /** * <p> * Split a Key=Value pair into separate components and add it to a Hashtable. * </p> * * @param table * Output Hashtable containing the Key,Value pair. * @param keyValPair * String containing the Key,Value pair to be split. */ private void SplitAndAddValuePair(Hashtable<String, String> table, String keyValPair) { int pos = keyValPair.indexOf('='); if(pos>=0) { String key = keyValPair.substring(0,pos); String val = keyValPair.substring(pos+1); table.put(key,val); } else { table.put(keyValPair,""); } } }
{ "content_hash": "6c3a95be643b99d777340ad469a9f8a0", "timestamp": "", "source": "github", "line_count": 350, "max_line_length": 138, "avg_line_length": 32.87428571428571, "alnum_prop": 0.5366765166000348, "repo_name": "Microsoft/BeanSpy", "id": "3902f3f90a6d553ff17077b82e67a6b0289fa9de", "size": "12194", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/code/JEE/Common/src/com/interopbridges/scx/mbeans/MBeanGetter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1234233" }, { "name": "XSLT", "bytes": "4220" } ], "symlink_target": "" }
package org.ensor.robots.simulator; import java.util.logging.Level; import java.util.logging.Logger; import org.ensor.robots.motors.IEncoder; import org.ensor.algorithms.control.pid.IServo; import org.junit.Test; /** * * @author jona */ public class SimulateMotorTest { @Test public void testSimulator() { SimulatedMotor sm = new SimulatedMotor(Math.PI / 180, 2000); IServo s = sm.getSpeedServo(); IEncoder e = sm.getEncoder(); s.setPosition(1000); for (int i = 0; i < 10; i++) { long pos = e.getEncoderPosition(); System.out.println("Position : " + pos); try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(SimulateMotorTest.class.getName()).log(Level.SEVERE, null, ex); } } } }
{ "content_hash": "fba18f97eb1ea88d48f446f7b0ee4f63", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 96, "avg_line_length": 22.547619047619047, "alnum_prop": 0.5469904963041182, "repo_name": "jarney/snackbot", "id": "1fe6e0803f285a0b9ecdd378831902ae12bea012", "size": "2095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/ensor/robots/simulator/SimulateMotorTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "12684" }, { "name": "CSS", "bytes": "5637" }, { "name": "HTML", "bytes": "22684" }, { "name": "Java", "bytes": "849550" }, { "name": "JavaScript", "bytes": "56968" }, { "name": "Makefile", "bytes": "13049" }, { "name": "Python", "bytes": "12585" }, { "name": "Shell", "bytes": "4841" } ], "symlink_target": "" }
/** * Seed. * * @type {Object} */ var seed = require('seed'); /** * Memory Storage. * * @type {Object} */ var store = new seed.MemoryStore(); /** * Example user model. * * @type {Function} */ module.exports.User = seed.Model.extend('User', { store: store, schema: new seed.Schema({ name: String, url: String, eyes: { left: String, right: String, }, age: Number, email: String, admin: Boolean, disabled: Boolean }) }); /** * Invalid model (without a storage). * * @type {Function} */ module.exports.Invalid = seed.Model.extend('Invalid', {});
{ "content_hash": "e86e194822eb590e8b2511de3bce3fd1", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 58, "avg_line_length": 13.391304347826088, "alnum_prop": 0.5616883116883117, "repo_name": "vesln/seed-forge", "id": "9f1ffd46b53f6f5e1d472f48e528c29b73ad0eaf", "size": "616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/support/models.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "14081" }, { "name": "Makefile", "bytes": "204" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff"> <RelativeLayout android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary"> <TextView android:id="@+id/title_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="#fff" android:textSize="20sp"/> <Button android:id="@+id/back_button" android:layout_width="25dp" android:layout_height="25dp" android:layout_marginLeft="10dp" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:background="@drawable/ic_back"/> </RelativeLayout> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent"> </ListView> </LinearLayout>
{ "content_hash": "82598a873f5ac769b16f1d2b9af6384d", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 72, "avg_line_length": 37.39393939393939, "alnum_prop": 0.6223662884927067, "repo_name": "IAmSeanWang/CoolWeather", "id": "a3eda00b98c0a6b13646a2d38362307bdd93f330", "size": "1234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/choose_area.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "32487" } ], "symlink_target": "" }
#ifndef CONF_H #define CONF_H struct conf { char *ip; short port; char *log_file; int client_timeout; int max_connections; }; struct conf * conf_read(const char *filename); void conf_free(struct conf *conf); #endif /* CONF_H */
{ "content_hash": "2e60122bd6d6a0fd4f26a6ee7ddfbc15", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 32, "avg_line_length": 10.521739130434783, "alnum_prop": 0.6694214876033058, "repo_name": "nicolasff/river", "id": "e307981953972d2540ee07bc4e1841112e5c93d8", "size": "242", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/conf.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "101154" }, { "name": "JavaScript", "bytes": "6108" }, { "name": "Shell", "bytes": "310" } ], "symlink_target": "" }
FOUNDATION_EXPORT double Pods_Homework_14VersionNumber; FOUNDATION_EXPORT const unsigned char Pods_Homework_14VersionString[];
{ "content_hash": "69fc5b91fb45563c1a9c84048f80af86", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 70, "avg_line_length": 42.666666666666664, "alnum_prop": 0.8515625, "repo_name": "BanyaKrylov/Learn-Swift", "id": "7d43cc87e2b1a35002f56d41339bc9c1c1ae4fb9", "size": "324", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Skill/Homework 14/Pods/Target Support Files/Pods-Homework 14/Pods-Homework 14-umbrella.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "1135" }, { "name": "Ruby", "bytes": "920" }, { "name": "Swift", "bytes": "288313" } ], "symlink_target": "" }
from Utils.WAAgentUtil import waagent import Utils.HandlerUtil as Util import commands import os import re import json waagent.LoggerInit('/var/log/waagent.log','/dev/stdout') hutil = Util.HandlerUtility(waagent.Log, waagent.Error, "bosh-deploy-script") hutil.do_parse_context("enable") settings= hutil.get_public_settings() from subprocess import call call("mkdir -p ./bosh",shell=True) call("mkdir -p ./bosh/.ssh",shell=True) for f in ['micro_bosh.yml','deploy_micro_bosh.sh','micro_cf.yml']: if not os.path.exists(f): continue with open (f,"r") as tmpfile: content = tmpfile.read() for i in settings.keys(): if i == 'fileUris': continue content=re.compile(re.escape("#"+i+"#"), re.IGNORECASE).sub(settings[i],content) with open (os.path.join('bosh',f),"w") as tmpfile: tmpfile.write(content) with open (os.path.join('bosh','settings'),"w") as tmpfile: tmpfile.write(json.dumps(settings, indent=4, sort_keys=True)) call("sh create_cert.sh >> ./bosh/micro_bosh.yml",shell=True) call("chmod 700 myPrivateKey.key",shell=True) call("chmod 744 ./bosh/deploy_micro_bosh.sh",shell=True) call("cp myPrivateKey.key ./bosh/.ssh/bosh.key",shell=True) call("cp -r ./bosh/* /home/"+settings['username'],shell=True) call("chown -R "+settings['username']+" "+"/home/"+settings['username'],shell=True) call("rm -r /tmp; mkdir /mnt/tmp; ln -s /mnt/tmp /tmp; chmod 777 /mnt/tmp ;chmod 777 /tmp", shell=True) call("mkdir /mnt/bosh_install; cp install_bosh_client.sh /mnt/bosh_install; cd /mnt/bosh_install ; sh install_bosh_client.sh;",shell=True) exit(0)
{ "content_hash": "caf0f6ed295598400cc14eb3f7a719a7", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 138, "avg_line_length": 39.48780487804878, "alnum_prop": 0.6849907350216183, "repo_name": "AlanSt/azure-quickstart-templates", "id": "38e81cedce4290aabdce963fab0361ea2fc888a6", "size": "1619", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "microbosh-setup/setup_devbox.py", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "393" }, { "name": "PHP", "bytes": "645" }, { "name": "PowerShell", "bytes": "74861" }, { "name": "Python", "bytes": "131960" }, { "name": "Shell", "bytes": "217347" } ], "symlink_target": "" }
namespace base { namespace android { // Returns a new Java byte array converted from the given bytes array. BASE_EXPORT ScopedJavaLocalRef<jbyteArray> ToJavaByteArray( JNIEnv* env, const uint8* bytes, size_t len); // Returns a array of Java byte array converted from |v|. BASE_EXPORT ScopedJavaLocalRef<jobjectArray> ToJavaArrayOfByteArray( JNIEnv* env, const std::vector<std::string>& v); BASE_EXPORT ScopedJavaLocalRef<jobjectArray> ToJavaArrayOfStrings( JNIEnv* env, const std::vector<std::string>& v); BASE_EXPORT ScopedJavaLocalRef<jobjectArray> ToJavaArrayOfStrings( JNIEnv* env, const std::vector<string16>& v); // Converts a Java string array to a native array. BASE_EXPORT void AppendJavaStringArrayToStringVector( JNIEnv* env, jobjectArray array, std::vector<string16>* out); BASE_EXPORT void AppendJavaStringArrayToStringVector( JNIEnv* env, jobjectArray array, std::vector<std::string>* out); // Appends the Java bytes in |bytes_array| onto the end of |out|. BASE_EXPORT void AppendJavaByteArrayToByteVector( JNIEnv* env, jbyteArray byte_array, std::vector<uint8>* out); // Replaces the content of |out| with the Java bytes in |bytes_array|. BASE_EXPORT void JavaByteArrayToByteVector( JNIEnv* env, jbyteArray byte_array, std::vector<uint8>* out); // Replaces the content of |out| with the Java ints in |int_array|. BASE_EXPORT void JavaIntArrayToIntVector( JNIEnv* env, jintArray int_array, std::vector<int>* out); } // namespace android } // namespace base #endif // BASE_ANDROID_JNI_ARRAY_H_
{ "content_hash": "5641e8dff0ba51daca3bae24136a72a4", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 70, "avg_line_length": 31.98, "alnum_prop": 0.7323327079424641, "repo_name": "leighpauls/k2cro4", "id": "86433a358c55a6509e7ae490521da8612d349bd4", "size": "1991", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "base/android/jni_array.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "3062" }, { "name": "AppleScript", "bytes": "25392" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "68131038" }, { "name": "C", "bytes": "242794338" }, { "name": "C#", "bytes": "11024" }, { "name": "C++", "bytes": "353525184" }, { "name": "Common Lisp", "bytes": "3721" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "F#", "bytes": "4992" }, { "name": "FORTRAN", "bytes": "10404" }, { "name": "Java", "bytes": "3845159" }, { "name": "JavaScript", "bytes": "39146656" }, { "name": "Lua", "bytes": "13768" }, { "name": "Matlab", "bytes": "22373" }, { "name": "Objective-C", "bytes": "21887598" }, { "name": "PHP", "bytes": "2344144" }, { "name": "Perl", "bytes": "49033099" }, { "name": "Prolog", "bytes": "2926122" }, { "name": "Python", "bytes": "39863959" }, { "name": "R", "bytes": "262" }, { "name": "Racket", "bytes": "359" }, { "name": "Ruby", "bytes": "304063" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "9195117" }, { "name": "Tcl", "bytes": "1919771" }, { "name": "Verilog", "bytes": "3092" }, { "name": "Visual Basic", "bytes": "1430" }, { "name": "eC", "bytes": "5079" } ], "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.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>tesseract: /home/stweil/src/github/tesseract-ocr/tesseract/classify/intfeaturemap.h File 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); </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> <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 id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">tesseract &#160;<span id="projectnumber">4.0.0-beta.1-59-g2cc4</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></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('a00743.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="#nested-classes">Classes</a> &#124; <a href="#namespaces">Namespaces</a> </div> <div class="headertitle"> <div class="title">intfeaturemap.h File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &quot;<a class="el" href="a00749_source.html">intfeaturespace.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="a00551_source.html">indexmapbidi.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="a00767_source.html">intproto.h</a>&quot;</code><br /> </div> <p><a href="a00743_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a04183.html">tesseract::IntFeatureMap</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a> Namespaces</h2></td></tr> <tr class="memitem:a01743"><td class="memItemLeft" align="right" valign="top"> &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a01743.html">tesseract</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </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="dir_31c6146c13abcc5d811ec2a212816f48.html">classify</a></li><li class="navelem"><a class="el" href="a00743.html">intfeaturemap.h</a></li> <li class="footer">Generated on Wed Mar 28 2018 20:00:40 for tesseract by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
{ "content_hash": "effedcbd2222d0c7fc7e11a57f76a6ab", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 201, "avg_line_length": 43.516949152542374, "alnum_prop": 0.6751703992210322, "repo_name": "stweil/tesseract-ocr.github.io", "id": "deced3a3791194d410f6fd6ea7b7a655adefa0dd", "size": "5135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "4.0.0/a00743.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1481625" }, { "name": "CSS", "bytes": "136547" }, { "name": "HTML", "bytes": "489171589" }, { "name": "JavaScript", "bytes": "9187479" } ], "symlink_target": "" }
import os import re from app import db, config, socketio, app from app.library.formatters import formatted_file_data from app.models.file import File from app.models.package import Package from app.modules.mod_process.file_repository import FileRepository from app.modules.mod_process.status_map import StatusMap class ProcessRepository: # this dict holds all the currently active processes as id-instance pairs # example: {1: <...>, 2: <...>, ...} processes = {} # this controls whether or not the encoding processing is active # notice: do not modify this directly, but use set_encoding_active() encoding_active = False @staticmethod def set_encoding_active(new_state): """ change the state of whether encoding should be active or not to a new state :param new_state: should the encoding be active now """ ProcessRepository.encoding_active = new_state # notify client socketio.emit("active_changed", {"active": new_state}) # check if it's necessary to start new processes ProcessRepository.check_and_start_processes() @staticmethod def cancel_all_processes(): """ cancel all currently running Processes """ # iterate over a copy of processes because cancel_process modifies the dictionary # while we are iterating over it for file_id in ProcessRepository.processes.copy(): ProcessRepository.cancel_process(file_id) @staticmethod def is_running(file_id): return file_id in ProcessRepository.processes @staticmethod def cancel_process(file_id): """ cancel a specific Process :param file_id: the id of the file corresponding to the Process """ # stop thread ProcessRepository.processes[file_id].stop() # update status file = File.query.filter_by(id=file_id).first() file.status = StatusMap.failed.value file.clear() db.session.commit() # emit file_done event socketio.emit("file_done", {"data": formatted_file_data(file)}) # remove from processes dict ProcessRepository.processes.pop(file_id) @staticmethod def check_and_start_processes(): """ check if it's required to start new Processes and do so if needed """ while ProcessRepository.encoding_active: # grab next potential file to process file = FileRepository.get_queued_query().order_by(Package.position.asc(), File.position.asc()).first() if file is None or ProcessRepository.count_processes_active() >= config["general"].getint( "parallel_processes"): break # update file.status in DB file.status = StatusMap.processing.value db.session.commit() # start the Process from app.modules.mod_process.process import Process process = Process(file) process.daemon = True # todo debug # file.status = 0 # db.session.commit() # ProcessRepository.encoding_active = False # add to "processes" dict ProcessRepository.processes[file.id] = process process.start() # emit file_started event data = formatted_file_data(file) data["count_active"] = ProcessRepository.count_processes_active() data["count_queued"] = ProcessRepository.count_processes_queued() socketio.emit("file_started", {"data": data}) @staticmethod def count_processes_active(): """ :return: the amount of processes currently active """ return len(ProcessRepository.processes) @staticmethod def count_processes_queued(): """ :return: the amount of Files currently queued """ return FileRepository.get_queued_query().count() @staticmethod def count_processes_total(): """ :return: count of all Files that are in packages that are queued """ # return ProcessRepository.count_processes_active() + ProcessRepository.count_processes_queued() return Package.query.filter_by(queue=True).join(File).count() # TODO @staticmethod def file_done(file): """ will be called whenever a Process is finished :param file: the File object of the File that is done """ # delete from "processes" ProcessRepository.processes.pop(file.id) # remove original file from disk if desired if config.getboolean("encoding", "delete_old_file"): os.remove(file.filename) # rename file if desired if config.getboolean("encoding", "rename_enabled"): rename_search = config.get("encoding", "rename_search") rename_replace = config.get("encoding", "rename_replace") # get pathinfo pathinfo = os.path.split(file.filename) path = pathinfo[0] old_filename = pathinfo[1] # only rename if match occurs if re.match(rename_search, old_filename): new_filename = re.sub(rename_search, rename_replace, old_filename) # rename output_filename (created by ffmpeg, see process.py) to new_filename os.rename(path + os.sep + file.output_filename, path + os.sep + new_filename) # update status to "finished" db.session.query(File).filter_by(id=file.id).update(dict(status=StatusMap.finished.value)) db.session.commit() # check if it's necessary to start new processes ProcessRepository.check_and_start_processes() # notify client socketio.emit("file_done", { "data": { "id": file.id, "count_active": ProcessRepository.count_processes_active(), "count_queued": ProcessRepository.count_processes_queued(), "count_total": ProcessRepository.count_processes_total(), } }) app.logger.debug("Done with encoding of %s" % file.filename) @staticmethod def file_failed(file): """ will be called whenever a File fails :param file: the File object of the File that has failed """ # delete from "processes" ProcessRepository.processes.pop(file.id) # update status and set attributes to zero file = db.session.query(File).filter_by(id=file.id).first() file.status = StatusMap.failed.value file.clear() db.session.commit() # check if it's necessary to start new processes ProcessRepository.check_and_start_processes() # notify client socketio.emit("file_done", { "data": { "id": file.id, "count_active": ProcessRepository.count_processes_active(), "count_queued": ProcessRepository.count_processes_queued(), "count_total": ProcessRepository.count_processes_total(), } }) @staticmethod def file_progress(file): """ will be called whenever a file makes progress :param file: the File object of the File that has made progress """ # format data info = formatted_file_data(file) socketio.emit("file_progress", {"data": info})
{ "content_hash": "4b19831dc9d36a982c4f24b04f09ceb2", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 114, "avg_line_length": 33.30222222222222, "alnum_prop": 0.6093687441612171, "repo_name": "dhardtke/pyEncode", "id": "e48d10236b7f90c5a7135510773d06073cb41fa0", "size": "7493", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/modules/mod_process/process_repository.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4488" }, { "name": "HTML", "bytes": "29041" }, { "name": "JavaScript", "bytes": "20857" }, { "name": "Python", "bytes": "68936" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("OpenCube.Game.Models.Specs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OpenCube.Game.Models.Specs")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("70364f4b-677a-4f5d-b767-4ebaf82be160")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "ffd00570b954a4ad7626ec6503745eaa", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.583333333333336, "alnum_prop": 0.7459649122807017, "repo_name": "Beaker73/OpenCube", "id": "e1b0c2784a67803026c77a72a20ae2643322163b", "size": "1428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/OpenCube.Game.Models.Specs/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "312370" }, { "name": "PowerShell", "bytes": "6116" } ], "symlink_target": "" }
var assert = require('assert'), metalsmith = require('metalsmith'), convert = require('..'); fs = require('fs'), sizeOf = require('image-size'); function convert_test(options, fn) { // build callback can be called multiple times if an error condition occurs var once = false; metalsmith('test/fixtures/simple').use(convert(options)).build(function(err, files) { if (once) return; once = true; fn(err, files); }) } describe('metalsmith-convert', function() { it('should croak on missing paramters', function(done){ convert_test({}, function(err, files) { if(!err) return done(new Error("Didn't error out on missing arguments.")); assert.equal(err.message, 'metalsmith-convert: "src" and "target" args required', 'Correct error was thrown'); return done(); }); }); it('should croak on partially missing paramters', function(done){ convert_test([ { src: '**/*.svg', target: 'png', resize: { width: 320, height: 240 } }, {}], function(err, files) { if(!err) return done(new Error("Didn't error out on missing arguments.")); assert.equal(err.message, 'metalsmith-convert: "src" and "target" args required', 'Correct error was thrown'); return done(); }); }); it('should convert from .svg to .png', function(done) { convert_test({ src: '**/*.svg', target: 'png', IM: false, remove: true }, function(err, files) { if (err) return done(err); assert(files['static/images/test.png'], 'file was converted'); return done(); }); }); it('should identify the image size', function(done) { convert_test({ src: '**/*.svg', target: 'png', IM: false, remove: true, nameFormat: '%b_%x_%y%e' }, function(err, files) { if (err) return done(err); assert(files['static/images/test_1052_744.png'], 'size was identified'); return done(); }); }); it('should resize the image', function(done) { convert_test({ src: '**/*.svg', target: 'png', remove: true, resize: { width: 320, height: 240 } }, function(err, files){ if (err) return done(err); assert(files['static/images/test_320_240.png'], 'file was resized'); return done(); }); }); it('should resize and convert the image', function(done) { convert_test([ { src: '**/*.svg', target: 'png', resize: { width: 160, height: 120 } }, { src: '**/*.svg', target: 'png', IM: false, remove: true }], function(err, files){ if (err) return done(err); assert(files['static/images/test.png'] && files['static/images/test_160_120.png'], 'file was converted and resized'); return done(); }); }); it('should resize two sizes', function(done) { convert_test([ { src: '**/*.svg', target: 'png', resize: { width: 320, height: 240 } }, { src: '**/*.svg', target: 'png', resize: { width: 640, height: 480 } }], function(err, files){ if (err) return done(err); assert(files['static/images/test_320_240.png'] && files['static/images/test_640_480.png'], 'file was two times resized'); return done(); }); }); it('should honour the nameFormat option', function(done) { convert_test([ { src: '**/*.svg', target: 'png', resize: { width: 320, height: 240 }, nameFormat: '%b_thumb%e' }, { src: '**/*.svg', target: 'png', resize: { width: 640, height: 480 }, nameFormat: '%b_thumb_large%e' }], function(err, files){ if (err) return done(err); assert(files['static/images/test_thumb.png'] && files['static/images/test_thumb_large.png'], 'fileFormat was correctly used'); return done(); }); }); it('should honour the resizeStyle option', function(done) { convert_test( { src: '**/*.svg', target: 'png', resize: { width: 320, height: 320, resizeStyle: 'aspectfit'}, nameFormat: '%b_thumb%e' }, function(err, files){ if (err) return done(err); var result = sizeOf(files['static/images/test_thumb.png'].contents); sizeOf('test/fixtures/simple/expected/test_thumb.png', function (err, dimensions) { if (err) return done(err); assert.deepEqual(result, dimensions, 'aspectFit was correctly used'); done(); }); }); }); });
{ "content_hash": "4e0f9ab61ba74a766f73522ca837905e", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 134, "avg_line_length": 32.673758865248224, "alnum_prop": 0.551334925113957, "repo_name": "gchallen/metalsmith-convert", "id": "e1ac000553ea988fa7b5dc0f00499196d3c4b981", "size": "4607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "7396" } ], "symlink_target": "" }
package controller import ( "context" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "os" "strings" "time" "github.com/container-storage-interface/spec/lib/go/csi" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" v1 "k8s.io/api/core/v1" storagev1 "k8s.io/api/storage/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" _ "k8s.io/apimachinery/pkg/util/json" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/validation" coreinformers "k8s.io/client-go/informers/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" corev1 "k8s.io/client-go/kubernetes/typed/core/v1" corelisters "k8s.io/client-go/listers/core/v1" storagelistersv1 "k8s.io/client-go/listers/storage/v1" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/record" "k8s.io/client-go/util/workqueue" "k8s.io/klog/v2" "sigs.k8s.io/sig-storage-lib-external-provisioner/v6/controller" "sigs.k8s.io/sig-storage-lib-external-provisioner/v6/util" "github.com/kubernetes-csi/csi-lib-utils/connection" "github.com/kubernetes-csi/csi-lib-utils/metrics" "github.com/kubernetes-csi/csi-lib-utils/rpc" snapapi "github.com/kubernetes-csi/external-snapshotter/client/v3/apis/volumesnapshot/v1beta1" snapclientset "github.com/kubernetes-csi/external-snapshotter/client/v3/clientset/versioned" ) //secretParamsMap provides a mapping of current as well as deprecated secret keys type secretParamsMap struct { name string deprecatedSecretNameKey string deprecatedSecretNamespaceKey string secretNameKey string secretNamespaceKey string } const ( // CSI Parameters prefixed with csiParameterPrefix are not passed through // to the driver on CreateVolumeRequest calls. Instead they are intended // to used by the CSI external-provisioner and maybe used to populate // fields in subsequent CSI calls or Kubernetes API objects. csiParameterPrefix = "csi.storage.k8s.io/" prefixedFsTypeKey = csiParameterPrefix + "fstype" prefixedDefaultSecretNameKey = csiParameterPrefix + "secret-name" prefixedDefaultSecretNamespaceKey = csiParameterPrefix + "secret-namespace" prefixedProvisionerSecretNameKey = csiParameterPrefix + "provisioner-secret-name" prefixedProvisionerSecretNamespaceKey = csiParameterPrefix + "provisioner-secret-namespace" prefixedControllerPublishSecretNameKey = csiParameterPrefix + "controller-publish-secret-name" prefixedControllerPublishSecretNamespaceKey = csiParameterPrefix + "controller-publish-secret-namespace" prefixedNodeStageSecretNameKey = csiParameterPrefix + "node-stage-secret-name" prefixedNodeStageSecretNamespaceKey = csiParameterPrefix + "node-stage-secret-namespace" prefixedNodePublishSecretNameKey = csiParameterPrefix + "node-publish-secret-name" prefixedNodePublishSecretNamespaceKey = csiParameterPrefix + "node-publish-secret-namespace" prefixedControllerExpandSecretNameKey = csiParameterPrefix + "controller-expand-secret-name" prefixedControllerExpandSecretNamespaceKey = csiParameterPrefix + "controller-expand-secret-namespace" // [Deprecated] CSI Parameters that are put into fields but // NOT stripped from the parameters passed to CreateVolume provisionerSecretNameKey = "csiProvisionerSecretName" provisionerSecretNamespaceKey = "csiProvisionerSecretNamespace" controllerPublishSecretNameKey = "csiControllerPublishSecretName" controllerPublishSecretNamespaceKey = "csiControllerPublishSecretNamespace" nodeStageSecretNameKey = "csiNodeStageSecretName" nodeStageSecretNamespaceKey = "csiNodeStageSecretNamespace" nodePublishSecretNameKey = "csiNodePublishSecretName" nodePublishSecretNamespaceKey = "csiNodePublishSecretNamespace" // PV and PVC metadata, used for sending to drivers in the create requests, added as parameters, optional. pvcNameKey = "csi.storage.k8s.io/pvc/name" pvcNamespaceKey = "csi.storage.k8s.io/pvc/namespace" pvNameKey = "csi.storage.k8s.io/pv/name" // Defines parameters for ExponentialBackoff used for executing // CSI CreateVolume API call, it gives approx 4 minutes for the CSI // driver to complete a volume creation. backoffDuration = time.Second * 5 backoffFactor = 1.2 backoffSteps = 10 snapshotKind = "VolumeSnapshot" snapshotAPIGroup = snapapi.GroupName // "snapshot.storage.k8s.io" pvcKind = "PersistentVolumeClaim" // Native types don't require an API group tokenPVNameKey = "pv.name" tokenPVCNameKey = "pvc.name" tokenPVCNameSpaceKey = "pvc.namespace" ResyncPeriodOfCsiNodeInformer = 1 * time.Hour deleteVolumeRetryCount = 5 annMigratedTo = "pv.kubernetes.io/migrated-to" annStorageProvisioner = "volume.beta.kubernetes.io/storage-provisioner" annSelectedNode = "volume.kubernetes.io/selected-node" snapshotNotBound = "snapshot %s not bound" pvcCloneFinalizer = "provisioner.storage.kubernetes.io/cloning-protection" operationTimeout = 10 * time.Second sodaProfileEndpoint = "soda-proxy.default.svc.cluster.local:50029/getprofile/" sodaSnapShotEnableEndpoint = "soda-proxy.default.svc.cluster.local:50029/snapshot/" ) var ( defaultSecretParams = secretParamsMap{ name: "Default", secretNameKey: prefixedDefaultSecretNameKey, secretNamespaceKey: prefixedDefaultSecretNamespaceKey, } provisionerSecretParams = secretParamsMap{ name: "Provisioner", deprecatedSecretNameKey: provisionerSecretNameKey, deprecatedSecretNamespaceKey: provisionerSecretNamespaceKey, secretNameKey: prefixedProvisionerSecretNameKey, secretNamespaceKey: prefixedProvisionerSecretNamespaceKey, } nodePublishSecretParams = secretParamsMap{ name: "NodePublish", deprecatedSecretNameKey: nodePublishSecretNameKey, deprecatedSecretNamespaceKey: nodePublishSecretNamespaceKey, secretNameKey: prefixedNodePublishSecretNameKey, secretNamespaceKey: prefixedNodePublishSecretNamespaceKey, } controllerPublishSecretParams = secretParamsMap{ name: "ControllerPublish", deprecatedSecretNameKey: controllerPublishSecretNameKey, deprecatedSecretNamespaceKey: controllerPublishSecretNamespaceKey, secretNameKey: prefixedControllerPublishSecretNameKey, secretNamespaceKey: prefixedControllerPublishSecretNamespaceKey, } nodeStageSecretParams = secretParamsMap{ name: "NodeStage", deprecatedSecretNameKey: nodeStageSecretNameKey, deprecatedSecretNamespaceKey: nodeStageSecretNamespaceKey, secretNameKey: prefixedNodeStageSecretNameKey, secretNamespaceKey: prefixedNodeStageSecretNamespaceKey, } controllerExpandSecretParams = secretParamsMap{ name: "ControllerExpand", secretNameKey: prefixedControllerExpandSecretNameKey, secretNamespaceKey: prefixedControllerExpandSecretNamespaceKey, } ) // ProvisionerCSITranslator contains the set of CSI Translation functionality // required by the provisioner type ProvisionerCSITranslator interface { TranslateInTreeStorageClassToCSI(inTreePluginName string, sc *storagev1.StorageClass) (*storagev1.StorageClass, error) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) IsPVMigratable(pv *v1.PersistentVolume) bool TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) IsMigratedCSIDriverByName(csiPluginName string) bool GetInTreeNameFromCSIName(pluginName string) (string, error) } // requiredCapabilities provides a set of extra capabilities required for special/optional features provided by a plugin type requiredCapabilities struct { snapshot bool clone bool } // NodeDeployment contains additional parameters for running external-provisioner alongside a // CSI driver on one or more nodes in the cluster. type NodeDeployment struct { // NodeName is the name of the node in Kubernetes on which the external-provisioner runs. NodeName string // ClaimInformer is needed to detect when some other external-provisioner // became the owner of a PVC while the local one is still waiting before // trying to become the owner itself. ClaimInformer coreinformers.PersistentVolumeClaimInformer // NodeInfo is the result of NodeGetInfo. It is need to determine which // PVs were created for the node. NodeInfo csi.NodeGetInfoResponse // ImmediateBinding enables support for PVCs with immediate binding. ImmediateBinding bool // BaseDelay is the initial time that the external-provisioner waits // before trying to become the owner of a PVC with immediate binding. BaseDelay time.Duration // MaxDelay is the maximum for the initial wait time. MaxDelay time.Duration } type internalNodeDeployment struct { NodeDeployment rateLimiter workqueue.RateLimiter } type csiProvisioner struct { client kubernetes.Interface csiClient csi.ControllerClient grpcClient *grpc.ClientConn snapshotClient snapclientset.Interface timeout time.Duration identity string volumeNamePrefix string defaultFSType string volumeNameUUIDLength int config *rest.Config driverName string pluginCapabilities rpc.PluginCapabilitySet controllerCapabilities rpc.ControllerCapabilitySet supportsMigrationFromInTreePluginName string strictTopology bool immediateTopology bool translator ProvisionerCSITranslator scLister storagelistersv1.StorageClassLister csiNodeLister storagelistersv1.CSINodeLister nodeLister corelisters.NodeLister claimLister corelisters.PersistentVolumeClaimLister vaLister storagelistersv1.VolumeAttachmentLister extraCreateMetadata bool eventRecorder record.EventRecorder nodeDeployment *internalNodeDeployment } var _ controller.Provisioner = &csiProvisioner{} var _ controller.BlockProvisioner = &csiProvisioner{} var _ controller.Qualifier = &csiProvisioner{} var ( // Each provisioner have a identify string to distinguish with others. This // identify string will be added in PV annoations under this key. provisionerIDKey = "storage.kubernetes.io/csiProvisionerIdentity" ) func Connect(address string, metricsManager metrics.CSIMetricsManager) (*grpc.ClientConn, error) { return connection.Connect(address, metricsManager, connection.OnConnectionLoss(connection.ExitOnConnectionLoss())) } func Probe(conn *grpc.ClientConn, singleCallTimeout time.Duration) error { return rpc.ProbeForever(conn, singleCallTimeout) } func GetDriverName(conn *grpc.ClientConn, timeout time.Duration) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() return rpc.GetDriverName(ctx, conn) } func GetDriverCapabilities(conn *grpc.ClientConn, timeout time.Duration) (rpc.PluginCapabilitySet, rpc.ControllerCapabilitySet, error) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() pluginCapabilities, err := rpc.GetPluginCapabilities(ctx, conn) if err != nil { return nil, nil, err } /* Each CSI operation gets its own timeout / context */ ctx, cancel = context.WithTimeout(context.Background(), timeout) defer cancel() controllerCapabilities, err := rpc.GetControllerCapabilities(ctx, conn) if err != nil { return nil, nil, err } return pluginCapabilities, controllerCapabilities, nil } func GetNodeInfo(conn *grpc.ClientConn, timeout time.Duration) (*csi.NodeGetInfoResponse, error) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() client := csi.NewNodeClient(conn) return client.NodeGetInfo(ctx, &csi.NodeGetInfoRequest{}) } // NewCSIProvisioner creates new CSI provisioner. // // vaLister is optional and only needed when VolumeAttachments are // meant to be checked before deleting a volume. func NewCSIProvisioner(client kubernetes.Interface, connectionTimeout time.Duration, identity string, volumeNamePrefix string, volumeNameUUIDLength int, grpcClient *grpc.ClientConn, snapshotClient snapclientset.Interface, driverName string, pluginCapabilities rpc.PluginCapabilitySet, controllerCapabilities rpc.ControllerCapabilitySet, supportsMigrationFromInTreePluginName string, strictTopology bool, immediateTopology bool, translator ProvisionerCSITranslator, scLister storagelistersv1.StorageClassLister, csiNodeLister storagelistersv1.CSINodeLister, nodeLister corelisters.NodeLister, claimLister corelisters.PersistentVolumeClaimLister, vaLister storagelistersv1.VolumeAttachmentLister, extraCreateMetadata bool, defaultFSType string, nodeDeployment *NodeDeployment, ) controller.Provisioner { broadcaster := record.NewBroadcaster() broadcaster.StartLogging(klog.Infof) broadcaster.StartRecordingToSink(&corev1.EventSinkImpl{Interface: client.CoreV1().Events(v1.NamespaceAll)}) eventRecorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: fmt.Sprintf("external-provisioner")}) csiClient := csi.NewControllerClient(grpcClient) provisioner := &csiProvisioner{ client: client, grpcClient: grpcClient, csiClient: csiClient, snapshotClient: snapshotClient, timeout: connectionTimeout, identity: identity, volumeNamePrefix: volumeNamePrefix, defaultFSType: defaultFSType, volumeNameUUIDLength: volumeNameUUIDLength, driverName: driverName, pluginCapabilities: pluginCapabilities, controllerCapabilities: controllerCapabilities, supportsMigrationFromInTreePluginName: supportsMigrationFromInTreePluginName, strictTopology: strictTopology, immediateTopology: immediateTopology, translator: translator, scLister: scLister, csiNodeLister: csiNodeLister, nodeLister: nodeLister, claimLister: claimLister, vaLister: vaLister, extraCreateMetadata: extraCreateMetadata, eventRecorder: eventRecorder, } if nodeDeployment != nil { provisioner.nodeDeployment = &internalNodeDeployment{ NodeDeployment: *nodeDeployment, rateLimiter: newItemExponentialFailureRateLimiterWithJitter(nodeDeployment.BaseDelay, nodeDeployment.MaxDelay), } // Remove deleted PVCs from rate limiter. claimHandler := cache.ResourceEventHandlerFuncs{ DeleteFunc: func(obj interface{}) { if claim, ok := obj.(*v1.PersistentVolumeClaim); ok { provisioner.nodeDeployment.rateLimiter.Forget(claim.UID) } }, } provisioner.nodeDeployment.ClaimInformer.Informer().AddEventHandler(claimHandler) } return provisioner } // This function get called before any attempt to communicate with the driver. // Before initiating Create/Delete API calls provisioner checks if Capabilities: // PluginControllerService, ControllerCreateVolume sre supported and gets the driver name. func (p *csiProvisioner) checkDriverCapabilities(rc *requiredCapabilities) error { if !p.pluginCapabilities[csi.PluginCapability_Service_CONTROLLER_SERVICE] { return fmt.Errorf("CSI driver does not support dynamic provisioning: plugin CONTROLLER_SERVICE capability is not reported") } if !p.controllerCapabilities[csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME] { return fmt.Errorf("CSI driver does not support dynamic provisioning: controller CREATE_DELETE_VOLUME capability is not reported") } if rc.snapshot { // Check whether plugin supports create snapshot // If not, create volume from snapshot cannot proceed if !p.controllerCapabilities[csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT] { return fmt.Errorf("CSI driver does not support snapshot restore: controller CREATE_DELETE_SNAPSHOT capability is not reported") } } if rc.clone { // Check whether plugin supports clone operations // If not, create volume from pvc cannot proceed if !p.controllerCapabilities[csi.ControllerServiceCapability_RPC_CLONE_VOLUME] { return fmt.Errorf("CSI driver does not support clone operations: controller CLONE_VOLUME capability is not reported") } } return nil } func makeVolumeName(prefix, pvcUID string, volumeNameUUIDLength int) (string, error) { // create persistent name based on a volumeNamePrefix and volumeNameUUIDLength // of PVC's UID if len(prefix) == 0 { return "", fmt.Errorf("Volume name prefix cannot be of length 0") } if len(pvcUID) == 0 { return "", fmt.Errorf("corrupted PVC object, it is missing UID") } if volumeNameUUIDLength == -1 { // Default behavior is to not truncate or remove dashes return fmt.Sprintf("%s-%s", prefix, pvcUID), nil } // Else we remove all dashes from UUID and truncate to volumeNameUUIDLength return fmt.Sprintf("%s-%s", prefix, strings.Replace(string(pvcUID), "-", "", -1)[0:volumeNameUUIDLength]), nil } func getAccessTypeBlock() *csi.VolumeCapability_Block { return &csi.VolumeCapability_Block{ Block: &csi.VolumeCapability_BlockVolume{}, } } func getAccessTypeMount(fsType string, mountFlags []string) *csi.VolumeCapability_Mount { return &csi.VolumeCapability_Mount{ Mount: &csi.VolumeCapability_MountVolume{ FsType: fsType, MountFlags: mountFlags, }, } } func getAccessMode(pvcAccessMode v1.PersistentVolumeAccessMode) *csi.VolumeCapability_AccessMode { switch pvcAccessMode { case v1.ReadWriteOnce: return &csi.VolumeCapability_AccessMode{ Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER, } case v1.ReadWriteMany: return &csi.VolumeCapability_AccessMode{ Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER, } case v1.ReadOnlyMany: return &csi.VolumeCapability_AccessMode{ Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY, } default: return nil } } func getVolumeCapability( claim *v1.PersistentVolumeClaim, sc *storagev1.StorageClass, pvcAccessMode v1.PersistentVolumeAccessMode, fsType string, ) *csi.VolumeCapability { if util.CheckPersistentVolumeClaimModeBlock(claim) { return &csi.VolumeCapability{ AccessType: getAccessTypeBlock(), AccessMode: getAccessMode(pvcAccessMode), } } return &csi.VolumeCapability{ AccessType: getAccessTypeMount(fsType, sc.MountOptions), AccessMode: getAccessMode(pvcAccessMode), } } type prepareProvisionResult struct { fsType string migratedVolume bool req *csi.CreateVolumeRequest csiPVSource *v1.CSIPersistentVolumeSource } type CustomPropertiesSpec map[string]interface{} //GetDriverPreference get the driver name from the customProperties of Soda Profile func (cps CustomPropertiesSpec) GetDriverPreference() (string, error) { var driverName string if cps != nil { for k, v := range cps { if k != "driver" { continue } driverName = fmt.Sprintf("%v", v) return driverName, nil } } return driverName, fmt.Errorf("DriverName not found in the customProperties of Soda Profile") } //func to equate the driverNameFromPlugin to driverNameFromProfileID func (p *csiProvisioner) isCallForCurrentDriver(profileID string) (string, error) { var backendDriverNameFromPlugin string url := "http://" + sodaProfileEndpoint + profileID response, err := http.Get(url) if err != nil { return backendDriverNameFromPlugin, fmt.Errorf("error in getting the Profile Details : %s", err.Error()) } else { data, _ := ioutil.ReadAll(response.Body) var customProperties *CustomPropertiesSpec json.Unmarshal(data, &customProperties) driverNameFromProfile, err := customProperties.GetDriverPreference() if err != nil { return backendDriverNameFromPlugin, err } //GetDriverName from Storage Plugin backendDriverNameFromPlugin, err = GetDriverName(p.grpcClient, operationTimeout) if err != nil { return backendDriverNameFromPlugin, err } if backendDriverNameFromPlugin != driverNameFromProfile { return backendDriverNameFromPlugin, fmt.Errorf("PVC doesnot match the current driver name : %s with expected %s", p.driverName, "profile.Name") } } return backendDriverNameFromPlugin, nil } // Call the soda-syncer for Snapshot func (p *csiProvisioner) snapShotEnable(profileID string) error { // Call the SnapshotEnable url := "http://" + sodaSnapShotEnableEndpoint + profileID response, err := http.Get(url) if err != nil { return fmt.Errorf("error in getting the Profile Details : %s", err.Error()) } else { klog.V(2).Infof("SnapshotEnabled, ", response.Body) } return nil } // prepareProvision does non-destructive parameter checking and preparations for provisioning a volume. func (p *csiProvisioner) prepareProvision(ctx context.Context, claim *v1.PersistentVolumeClaim, sc *storagev1.StorageClass, selectedNode *v1.Node) (*prepareProvisionResult, controller.ProvisioningState, error) { if sc == nil { return nil, controller.ProvisioningFinished, errors.New("storage class was nil") } var profileID string // Add Soda intelligence to pick the driver from ProfileID received in StorageClass Parameter if sc.Provisioner == "soda-csi" { for k, v := range sc.Parameters { if k != "profile" { continue } profileID = v backendDriverName, err := p.isCallForCurrentDriver(v) if err != nil { return nil, controller.ProvisioningFinished, &controller.IgnoredError{ Reason: err.Error()} } sc.Provisioner = backendDriverName } } go p.snapShotEnable(profileID) migratedVolume := false if p.supportsMigrationFromInTreePluginName != "" { // NOTE: we cannot depend on PVC.Annotations[volume.beta.kubernetes.io/storage-provisioner] to get // the in-tree provisioner name in case of CSI migration scenarios. The annotation will be // set to the CSI provisioner name by PV controller for migration scenarios // so that external provisioner can correctly pick up the PVC pointing to an in-tree plugin if sc.Provisioner == p.supportsMigrationFromInTreePluginName { klog.V(2).Infof("translating storage class for in-tree plugin %s to CSI", sc.Provisioner) storageClass, err := p.translator.TranslateInTreeStorageClassToCSI(p.supportsMigrationFromInTreePluginName, sc) if err != nil { return nil, controller.ProvisioningFinished, fmt.Errorf("failed to translate storage class: %v", err) } sc = storageClass migratedVolume = true } else { klog.V(4).Infof("skip translation of storage class for plugin: %s", sc.Provisioner) } } // Make sure the plugin is capable of fulfilling the requested options rc := &requiredCapabilities{} if claim.Spec.DataSource != nil { // PVC.Spec.DataSource.Name is the name of the VolumeSnapshot API object if claim.Spec.DataSource.Name == "" { return nil, controller.ProvisioningFinished, fmt.Errorf("the PVC source not found for PVC %s", claim.Name) } switch claim.Spec.DataSource.Kind { case snapshotKind: if *(claim.Spec.DataSource.APIGroup) != snapshotAPIGroup { return nil, controller.ProvisioningFinished, fmt.Errorf("the PVC source does not belong to the right APIGroup. Expected %s, Got %s", snapshotAPIGroup, *(claim.Spec.DataSource.APIGroup)) } rc.snapshot = true case pvcKind: rc.clone = true default: // DataSource is not VolumeSnapshot and PVC // Assume external data populator to create the volume, and there is no more work for us to do p.eventRecorder.Event(claim, v1.EventTypeNormal, "Provisioning", fmt.Sprintf("Assuming an external populator will provision the volume")) return nil, controller.ProvisioningFinished, &controller.IgnoredError{ Reason: fmt.Sprintf("data source (%s) is not handled by the provisioner, assuming an external populator will provision it", claim.Spec.DataSource.Kind), } } } if err := p.checkDriverCapabilities(rc); err != nil { return nil, controller.ProvisioningFinished, err } if claim.Spec.Selector != nil { return nil, controller.ProvisioningFinished, fmt.Errorf("claim Selector is not supported") } pvName, err := makeVolumeName(p.volumeNamePrefix, fmt.Sprintf("%s", claim.ObjectMeta.UID), p.volumeNameUUIDLength) if err != nil { return nil, controller.ProvisioningFinished, err } fsTypesFound := 0 fsType := "" for k, v := range sc.Parameters { if strings.ToLower(k) == "fstype" || k == prefixedFsTypeKey { fsType = v fsTypesFound++ } if strings.ToLower(k) == "fstype" { klog.Warningf(deprecationWarning("fstype", prefixedFsTypeKey, "")) } } if fsTypesFound > 1 { return nil, controller.ProvisioningFinished, fmt.Errorf("fstype specified in parameters with both \"fstype\" and \"%s\" keys", prefixedFsTypeKey) } if fsType == "" && p.defaultFSType != "" { fsType = p.defaultFSType } capacity := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] volSizeBytes := capacity.Value() // Get access mode volumeCaps := make([]*csi.VolumeCapability, 0) for _, pvcAccessMode := range claim.Spec.AccessModes { volumeCaps = append(volumeCaps, getVolumeCapability(claim, sc, pvcAccessMode, fsType)) } // Create a CSI CreateVolumeRequest and Response req := csi.CreateVolumeRequest{ Name: pvName, Parameters: sc.Parameters, VolumeCapabilities: volumeCaps, CapacityRange: &csi.CapacityRange{ RequiredBytes: int64(volSizeBytes), }, } if claim.Spec.DataSource != nil && (rc.clone || rc.snapshot) { volumeContentSource, err := p.getVolumeContentSource(ctx, claim, sc) if err != nil { return nil, controller.ProvisioningNoChange, fmt.Errorf("error getting handle for DataSource Type %s by Name %s: %v", claim.Spec.DataSource.Kind, claim.Spec.DataSource.Name, err) } req.VolumeContentSource = volumeContentSource } if claim.Spec.DataSource != nil && rc.clone { err = p.setCloneFinalizer(ctx, claim) if err != nil { return nil, controller.ProvisioningNoChange, err } } if p.supportsTopology() { requirements, err := GenerateAccessibilityRequirements( p.client, p.driverName, claim.Name, sc.AllowedTopologies, selectedNode, p.strictTopology, p.immediateTopology, p.csiNodeLister, p.nodeLister) if err != nil { return nil, controller.ProvisioningNoChange, fmt.Errorf("error generating accessibility requirements: %v", err) } req.AccessibilityRequirements = requirements } // Resolve provision secret credentials. provisionerSecretRef, err := getSecretReference(provisionerSecretParams, sc.Parameters, pvName, &v1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: claim.Name, Namespace: claim.Namespace, }, }) if err != nil { return nil, controller.ProvisioningNoChange, err } provisionerCredentials, err := getCredentials(ctx, p.client, provisionerSecretRef) if err != nil { return nil, controller.ProvisioningNoChange, err } req.Secrets = provisionerCredentials // Resolve controller publish, node stage, node publish secret references controllerPublishSecretRef, err := getSecretReference(controllerPublishSecretParams, sc.Parameters, pvName, claim) if err != nil { return nil, controller.ProvisioningNoChange, err } nodeStageSecretRef, err := getSecretReference(nodeStageSecretParams, sc.Parameters, pvName, claim) if err != nil { return nil, controller.ProvisioningNoChange, err } nodePublishSecretRef, err := getSecretReference(nodePublishSecretParams, sc.Parameters, pvName, claim) if err != nil { return nil, controller.ProvisioningNoChange, err } controllerExpandSecretRef, err := getSecretReference(controllerExpandSecretParams, sc.Parameters, pvName, claim) if err != nil { return nil, controller.ProvisioningNoChange, err } csiPVSource := &v1.CSIPersistentVolumeSource{ Driver: sc.Provisioner, // VolumeHandle and VolumeAttributes will be added after provisioning. ControllerPublishSecretRef: controllerPublishSecretRef, NodeStageSecretRef: nodeStageSecretRef, NodePublishSecretRef: nodePublishSecretRef, ControllerExpandSecretRef: controllerExpandSecretRef, } req.Parameters, err = removePrefixedParameters(sc.Parameters) if err != nil { return nil, controller.ProvisioningFinished, fmt.Errorf("failed to strip CSI Parameters of prefixed keys: %v", err) } if p.extraCreateMetadata { // add pvc and pv metadata to request for use by the plugin req.Parameters[pvcNameKey] = claim.GetName() req.Parameters[pvcNamespaceKey] = claim.GetNamespace() req.Parameters[pvNameKey] = pvName } return &prepareProvisionResult{ fsType: fsType, migratedVolume: migratedVolume, req: &req, csiPVSource: csiPVSource, }, controller.ProvisioningNoChange, nil } func (p *csiProvisioner) Provision(ctx context.Context, options controller.ProvisionOptions) (*v1.PersistentVolume, controller.ProvisioningState, error) { claim := options.PVC if claim.Annotations[annStorageProvisioner] != p.driverName && claim.Annotations[annMigratedTo] != p.driverName { // The storage provisioner annotation may not equal driver name but the // PVC could have annotation "migrated-to" which is the new way to // signal a PVC is migrated (k8s v1.17+) return nil, controller.ProvisioningFinished, &controller.IgnoredError{ Reason: fmt.Sprintf("PVC annotated with external-provisioner name %s does not match provisioner driver name %s. This could mean the PVC is not migrated", claim.Annotations[annStorageProvisioner], p.driverName), } } // The same check already ran in ShouldProvision, but perhaps // it couldn't complete due to some unexpected error. owned, err := p.checkNode(ctx, claim, options.StorageClass, "provision") if err != nil { return nil, controller.ProvisioningNoChange, fmt.Errorf("node check failed: %v", err) } if !owned { return nil, controller.ProvisioningNoChange, &controller.IgnoredError{ Reason: fmt.Sprintf("not responsible for provisioning of PVC %s/%s because it is not assigned to node %q", claim.Namespace, claim.Name, p.nodeDeployment.NodeName), } } result, state, err := p.prepareProvision(ctx, claim, options.StorageClass, options.SelectedNode) if result == nil { return nil, state, err } req := result.req volSizeBytes := req.CapacityRange.RequiredBytes pvName := req.Name provisionerCredentials := req.Secrets createCtx, cancel := context.WithTimeout(ctx, p.timeout) defer cancel() klog.V(5).Infof("CreateVolumeRequest %+v", req) rep, err := p.csiClient.CreateVolume(createCtx, req) if err != nil { // Giving up after an error and telling the pod scheduler to retry with a different node // only makes sense if: // - The CSI driver supports topology: without that, the next CreateVolume call after // rescheduling will be exactly the same. // - We are working on a volume with late binding: only in that case will // provisioning be retried if we give up for now. // - The error is one where rescheduling is // a) allowed (i.e. we don't have to keep calling CreateVolume because the operation might be running) and // b) it makes sense (typically local resource exhausted). // isFinalError is going to check this. // // We do this regardless whether the driver has asked for strict topology because // even drivers which did not ask for it explicitly might still only look at the first // topology entry and thus succeed after rescheduling. mayReschedule := p.supportsTopology() && options.SelectedNode != nil state := checkError(err, mayReschedule) klog.V(5).Infof("CreateVolume failed, supports topology = %v, node selected %v => may reschedule = %v => state = %v: %v", p.supportsTopology(), options.SelectedNode != nil, mayReschedule, state, err) return nil, state, err } if rep.Volume != nil { klog.V(3).Infof("create volume rep: %+v", *rep.Volume) } volumeAttributes := map[string]string{provisionerIDKey: p.identity} for k, v := range rep.Volume.VolumeContext { volumeAttributes[k] = v } respCap := rep.GetVolume().GetCapacityBytes() //According to CSI spec CreateVolume should be able to return capacity = 0, which means it is unknown. for example NFS/FTP if respCap == 0 { respCap = volSizeBytes klog.V(3).Infof("csiClient response volume with size 0, which is not supported by apiServer, will use claim size:%d", respCap) } else if respCap < volSizeBytes { capErr := fmt.Errorf("created volume capacity %v less than requested capacity %v", respCap, volSizeBytes) delReq := &csi.DeleteVolumeRequest{ VolumeId: rep.GetVolume().GetVolumeId(), } err = cleanupVolume(ctx, p, delReq, provisionerCredentials) if err != nil { capErr = fmt.Errorf("%v. Cleanup of volume %s failed, volume is orphaned: %v", capErr, pvName, err) } // use InBackground to retry the call, hoping the volume is deleted correctly next time. return nil, controller.ProvisioningInBackground, capErr } if options.PVC.Spec.DataSource != nil { contentSource := rep.GetVolume().ContentSource if contentSource == nil { sourceErr := fmt.Errorf("volume content source missing") delReq := &csi.DeleteVolumeRequest{ VolumeId: rep.GetVolume().GetVolumeId(), } err = cleanupVolume(ctx, p, delReq, provisionerCredentials) if err != nil { sourceErr = fmt.Errorf("%v. cleanup of volume %s failed, volume is orphaned: %v", sourceErr, pvName, err) } return nil, controller.ProvisioningInBackground, sourceErr } } result.csiPVSource.VolumeHandle = p.volumeIdToHandle(rep.Volume.VolumeId) result.csiPVSource.VolumeAttributes = volumeAttributes pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: pvName, }, Spec: v1.PersistentVolumeSpec{ AccessModes: options.PVC.Spec.AccessModes, MountOptions: options.StorageClass.MountOptions, Capacity: v1.ResourceList{ v1.ResourceName(v1.ResourceStorage): bytesToQuantity(respCap), }, // TODO wait for CSI VolumeSource API PersistentVolumeSource: v1.PersistentVolumeSource{ CSI: result.csiPVSource, }, }, } if options.StorageClass.ReclaimPolicy != nil { pv.Spec.PersistentVolumeReclaimPolicy = *options.StorageClass.ReclaimPolicy } if p.supportsTopology() { pv.Spec.NodeAffinity = GenerateVolumeNodeAffinity(rep.Volume.AccessibleTopology) } // Set VolumeMode to PV if it is passed via PVC spec when Block feature is enabled if options.PVC.Spec.VolumeMode != nil { pv.Spec.VolumeMode = options.PVC.Spec.VolumeMode } // Set FSType if PV is not Block Volume if !util.CheckPersistentVolumeClaimModeBlock(options.PVC) { pv.Spec.PersistentVolumeSource.CSI.FSType = result.fsType } klog.V(2).Infof("successfully created PV %v for PVC %v and csi volume name %v", pv.Name, options.PVC.Name, pv.Spec.CSI.VolumeHandle) if result.migratedVolume { pv, err = p.translator.TranslateCSIPVToInTree(pv) if err != nil { klog.Warningf("failed to translate CSI PV to in-tree due to: %v. Deleting provisioned PV", err) deleteErr := p.Delete(ctx, pv) if deleteErr != nil { klog.Warningf("failed to delete partly provisioned PV: %v", deleteErr) // Retry the call again to clean up the orphan return nil, controller.ProvisioningInBackground, err } return nil, controller.ProvisioningFinished, err } } klog.V(5).Infof("successfully created PV %+v", pv.Spec.PersistentVolumeSource) return pv, controller.ProvisioningFinished, nil } func (p *csiProvisioner) setCloneFinalizer(ctx context.Context, pvc *v1.PersistentVolumeClaim) error { claim, err := p.claimLister.PersistentVolumeClaims(pvc.Namespace).Get(pvc.Spec.DataSource.Name) if err != nil { return err } if !checkFinalizer(claim, pvcCloneFinalizer) { claim.Finalizers = append(claim.Finalizers, pvcCloneFinalizer) _, err := p.client.CoreV1().PersistentVolumeClaims(claim.Namespace).Update(ctx, claim, metav1.UpdateOptions{}) return err } return nil } func (p *csiProvisioner) supportsTopology() bool { return SupportsTopology(p.pluginCapabilities) } func removePrefixedParameters(param map[string]string) (map[string]string, error) { newParam := map[string]string{} for k, v := range param { if strings.HasPrefix(k, csiParameterPrefix) { // Check if its well known switch k { case prefixedFsTypeKey: case prefixedProvisionerSecretNameKey: case prefixedProvisionerSecretNamespaceKey: case prefixedControllerPublishSecretNameKey: case prefixedControllerPublishSecretNamespaceKey: case prefixedNodeStageSecretNameKey: case prefixedNodeStageSecretNamespaceKey: case prefixedNodePublishSecretNameKey: case prefixedNodePublishSecretNamespaceKey: case prefixedControllerExpandSecretNameKey: case prefixedControllerExpandSecretNamespaceKey: case prefixedDefaultSecretNameKey: case prefixedDefaultSecretNamespaceKey: default: return map[string]string{}, fmt.Errorf("found unknown parameter key \"%s\" with reserved namespace %s", k, csiParameterPrefix) } } else { // Don't strip, add this key-value to new map // Deprecated parameters prefixed with "csi" are not stripped to preserve backwards compatibility newParam[k] = v } } return newParam, nil } // getVolumeContentSource is a helper function to process provisioning requests that include a DataSource // currently we provide Snapshot and PVC, the default case allows the provisioner to still create a volume // so that an external controller can act upon it. Additional DataSource types can be added here with // an appropriate implementation function func (p *csiProvisioner) getVolumeContentSource(ctx context.Context, claim *v1.PersistentVolumeClaim, sc *storagev1.StorageClass) (*csi.VolumeContentSource, error) { switch claim.Spec.DataSource.Kind { case snapshotKind: return p.getSnapshotSource(ctx, claim, sc) case pvcKind: return p.getPVCSource(ctx, claim, sc) default: // For now we shouldn't pass other things to this function, but treat it as a noop and extend as needed return nil, nil } } // getPVCSource verifies DataSource.Kind of type PersistentVolumeClaim, making sure that the requested PVC is available/ready // returns the VolumeContentSource for the requested PVC func (p *csiProvisioner) getPVCSource(ctx context.Context, claim *v1.PersistentVolumeClaim, sc *storagev1.StorageClass) (*csi.VolumeContentSource, error) { sourcePVC, err := p.claimLister.PersistentVolumeClaims(claim.Namespace).Get(claim.Spec.DataSource.Name) if err != nil { return nil, fmt.Errorf("error getting PVC %s (namespace %q) from api server: %v", claim.Spec.DataSource.Name, claim.Namespace, err) } if string(sourcePVC.Status.Phase) != "Bound" { return nil, fmt.Errorf("the PVC DataSource %s must have a status of Bound. Got %v", claim.Spec.DataSource.Name, sourcePVC.Status) } if sourcePVC.ObjectMeta.DeletionTimestamp != nil { return nil, fmt.Errorf("the PVC DataSource %s is currently being deleted", claim.Spec.DataSource.Name) } if sourcePVC.Spec.StorageClassName == nil { return nil, fmt.Errorf("the source PVC (%s) storageclass cannot be empty", sourcePVC.Name) } if claim.Spec.StorageClassName == nil { return nil, fmt.Errorf("the requested PVC (%s) storageclass cannot be empty", claim.Name) } if *sourcePVC.Spec.StorageClassName != *claim.Spec.StorageClassName { return nil, fmt.Errorf("the source PVC and destination PVCs must be in the same storage class for cloning. Source is in %v, but new PVC is in %v", *sourcePVC.Spec.StorageClassName, *claim.Spec.StorageClassName) } capacity := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] requestedSize := capacity.Value() srcCapacity := sourcePVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] srcPVCSize := srcCapacity.Value() if requestedSize < srcPVCSize { return nil, fmt.Errorf("error, new PVC request must be greater than or equal in size to the specified PVC data source, requested %v but source is %v", requestedSize, srcPVCSize) } if sourcePVC.Spec.VolumeName == "" { return nil, fmt.Errorf("volume name is empty in source PVC %s", sourcePVC.Name) } sourcePV, err := p.client.CoreV1().PersistentVolumes().Get(ctx, sourcePVC.Spec.VolumeName, metav1.GetOptions{}) if err != nil { klog.Warningf("error getting volume %s for PVC %s/%s: %s", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name, err) return nil, fmt.Errorf("claim in dataSource not bound or invalid") } if sourcePV.Spec.CSI == nil { klog.Warningf("error getting volume source from %s for PVC %s/%s", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name) return nil, fmt.Errorf("claim in dataSource not bound or invalid") } if sourcePV.Spec.CSI.Driver != sc.Provisioner { klog.Warningf("the source volume %s for PVC %s/%s is handled by a different CSI driver than requested by StorageClass %s", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name, *claim.Spec.StorageClassName) return nil, fmt.Errorf("claim in dataSource not bound or invalid") } if sourcePV.Spec.ClaimRef == nil { klog.Warningf("the source volume %s for PVC %s/%s is not bound", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name) return nil, fmt.Errorf("claim in dataSource not bound or invalid") } if sourcePV.Spec.ClaimRef.UID != sourcePVC.UID || sourcePV.Spec.ClaimRef.Namespace != sourcePVC.Namespace || sourcePV.Spec.ClaimRef.Name != sourcePVC.Name { klog.Warningf("the source volume %s for PVC %s/%s is bound to a different PVC than requested", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name) return nil, fmt.Errorf("claim in dataSource not bound or invalid") } if sourcePV.Status.Phase != v1.VolumeBound { klog.Warningf("the source volume %s for PVC %s/%s status is \"%s\", should instead be \"%s\"", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name, sourcePV.Status.Phase, v1.VolumeBound) return nil, fmt.Errorf("claim in dataSource not bound or invalid") } if claim.Spec.VolumeMode == nil || *claim.Spec.VolumeMode == v1.PersistentVolumeFilesystem { if sourcePV.Spec.VolumeMode != nil && *sourcePV.Spec.VolumeMode != v1.PersistentVolumeFilesystem { return nil, fmt.Errorf("the source PVC and destination PVCs must have the same volume mode for cloning. Source is Block, but new PVC requested Filesystem") } } if claim.Spec.VolumeMode != nil && *claim.Spec.VolumeMode == v1.PersistentVolumeBlock { if sourcePV.Spec.VolumeMode == nil || *sourcePV.Spec.VolumeMode != v1.PersistentVolumeBlock { return nil, fmt.Errorf("the source PVC and destination PVCs must have the same volume mode for cloning. Source is Filesystem, but new PVC requested Block") } } volumeSource := csi.VolumeContentSource_Volume{ Volume: &csi.VolumeContentSource_VolumeSource{ VolumeId: sourcePV.Spec.CSI.VolumeHandle, }, } klog.V(5).Infof("VolumeContentSource_Volume %+v", volumeSource) volumeContentSource := &csi.VolumeContentSource{ Type: &volumeSource, } return volumeContentSource, nil } // getSnapshotSource verifies DataSource.Kind of type VolumeSnapshot, making sure that the requested Snapshot is available/ready // returns the VolumeContentSource for the requested snapshot func (p *csiProvisioner) getSnapshotSource(ctx context.Context, claim *v1.PersistentVolumeClaim, sc *storagev1.StorageClass) (*csi.VolumeContentSource, error) { snapshotObj, err := p.snapshotClient.SnapshotV1beta1().VolumeSnapshots(claim.Namespace).Get(ctx, claim.Spec.DataSource.Name, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("error getting snapshot %s from api server: %v", claim.Spec.DataSource.Name, err) } if snapshotObj.ObjectMeta.DeletionTimestamp != nil { return nil, fmt.Errorf("snapshot %s is currently being deleted", claim.Spec.DataSource.Name) } klog.V(5).Infof("VolumeSnapshot %+v", snapshotObj) if snapshotObj.Status == nil || snapshotObj.Status.BoundVolumeSnapshotContentName == nil { return nil, fmt.Errorf(snapshotNotBound, claim.Spec.DataSource.Name) } snapContentObj, err := p.snapshotClient.SnapshotV1beta1().VolumeSnapshotContents().Get(ctx, *snapshotObj.Status.BoundVolumeSnapshotContentName, metav1.GetOptions{}) if err != nil { klog.Warningf("error getting snapshotcontent %s for snapshot %s/%s from api server: %s", *snapshotObj.Status.BoundVolumeSnapshotContentName, snapshotObj.Namespace, snapshotObj.Name, err) return nil, fmt.Errorf(snapshotNotBound, claim.Spec.DataSource.Name) } if snapContentObj.Spec.VolumeSnapshotRef.UID != snapshotObj.UID || snapContentObj.Spec.VolumeSnapshotRef.Namespace != snapshotObj.Namespace || snapContentObj.Spec.VolumeSnapshotRef.Name != snapshotObj.Name { klog.Warningf("snapshotcontent %s for snapshot %s/%s is bound to a different snapshot", *snapshotObj.Status.BoundVolumeSnapshotContentName, snapshotObj.Namespace, snapshotObj.Name) return nil, fmt.Errorf(snapshotNotBound, claim.Spec.DataSource.Name) } if snapContentObj.Spec.Driver != sc.Provisioner { klog.Warningf("snapshotcontent %s for snapshot %s/%s is handled by a different CSI driver than requested by StorageClass %s", *snapshotObj.Status.BoundVolumeSnapshotContentName, snapshotObj.Namespace, snapshotObj.Name, sc.Name) return nil, fmt.Errorf(snapshotNotBound, claim.Spec.DataSource.Name) } if snapshotObj.Status.ReadyToUse == nil || *snapshotObj.Status.ReadyToUse == false { return nil, fmt.Errorf("snapshot %s is not Ready", claim.Spec.DataSource.Name) } klog.V(5).Infof("VolumeSnapshotContent %+v", snapContentObj) if snapContentObj.Status == nil || snapContentObj.Status.SnapshotHandle == nil { return nil, fmt.Errorf("snapshot handle %s is not available", claim.Spec.DataSource.Name) } snapshotSource := csi.VolumeContentSource_Snapshot{ Snapshot: &csi.VolumeContentSource_SnapshotSource{ SnapshotId: *snapContentObj.Status.SnapshotHandle, }, } klog.V(5).Infof("VolumeContentSource_Snapshot %+v", snapshotSource) if snapshotObj.Status.RestoreSize != nil { capacity, exists := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] if !exists { return nil, fmt.Errorf("error getting capacity for PVC %s when creating snapshot %s", claim.Name, snapshotObj.Name) } volSizeBytes := capacity.Value() klog.V(5).Infof("Requested volume size is %d and snapshot size is %d for the source snapshot %s", int64(volSizeBytes), int64(snapshotObj.Status.RestoreSize.Value()), snapshotObj.Name) // When restoring volume from a snapshot, the volume size should // be equal to or larger than its snapshot size. if int64(volSizeBytes) < int64(snapshotObj.Status.RestoreSize.Value()) { return nil, fmt.Errorf("requested volume size %d is less than the size %d for the source snapshot %s", int64(volSizeBytes), int64(snapshotObj.Status.RestoreSize.Value()), snapshotObj.Name) } if int64(volSizeBytes) > int64(snapshotObj.Status.RestoreSize.Value()) { klog.Warningf("requested volume size %d is greater than the size %d for the source snapshot %s. Volume plugin needs to handle volume expansion.", int64(volSizeBytes), int64(snapshotObj.Status.RestoreSize.Value()), snapshotObj.Name) } } volumeContentSource := &csi.VolumeContentSource{ Type: &snapshotSource, } return volumeContentSource, nil } func (p *csiProvisioner) Delete(ctx context.Context, volume *v1.PersistentVolume) error { if volume == nil { return fmt.Errorf("invalid CSI PV") } var err error if p.translator.IsPVMigratable(volume) { // we end up here only if CSI migration is enabled in-tree (both overall // and for the specific plugin that is migratable) causing in-tree PV // controller to yield deletion of PVs with in-tree source to external provisioner // based on AnnDynamicallyProvisioned annotation. volume, err = p.translator.TranslateInTreePVToCSI(volume) if err != nil { return err } } if volume.Spec.CSI == nil { return fmt.Errorf("invalid CSI PV") } // If we run on a single node, then we shouldn't delete volumes // that we didn't create. In practice, that means that the volume // is accessible (only!) on this node. if p.nodeDeployment != nil { accessible, err := VolumeIsAccessible(volume.Spec.NodeAffinity, p.nodeDeployment.NodeInfo.AccessibleTopology) if err != nil { return fmt.Errorf("checking volume affinity failed: %v", err) } if !accessible { return &controller.IgnoredError{ Reason: "PV was not provisioned on this node", } } } volumeId := p.volumeHandleToId(volume.Spec.CSI.VolumeHandle) rc := &requiredCapabilities{} if err := p.checkDriverCapabilities(rc); err != nil { return err } req := csi.DeleteVolumeRequest{ VolumeId: volumeId, } // get secrets if StorageClass specifies it storageClassName := util.GetPersistentVolumeClass(volume) if len(storageClassName) != 0 { if storageClass, err := p.scLister.Get(storageClassName); err == nil { // Resolve provision secret credentials. provisionerSecretRef, err := getSecretReference(provisionerSecretParams, storageClass.Parameters, volume.Name, &v1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: volume.Spec.ClaimRef.Name, Namespace: volume.Spec.ClaimRef.Namespace, }, }) if err != nil { return fmt.Errorf("failed to get secretreference for volume %s: %v", volume.Name, err) } credentials, err := getCredentials(ctx, p.client, provisionerSecretRef) if err != nil { // Continue with deletion, as the secret may have already been deleted. klog.Errorf("Failed to get credentials for volume %s: %s", volume.Name, err.Error()) } req.Secrets = credentials } else { klog.Warningf("failed to get storageclass: %s, proceeding to delete without secrets. %v", storageClassName, err) } } deleteCtx, cancel := context.WithTimeout(ctx, p.timeout) defer cancel() if err := p.canDeleteVolume(volume); err != nil { return err } _, err = p.csiClient.DeleteVolume(deleteCtx, &req) return err } func (p *csiProvisioner) canDeleteVolume(volume *v1.PersistentVolume) error { if p.vaLister == nil { // Nothing to check. return nil } // Verify if volume is attached to a node before proceeding with deletion vaList, err := p.vaLister.List(labels.Everything()) if err != nil { return fmt.Errorf("failed to list volumeattachments: %v", err) } for _, va := range vaList { if va.Spec.Source.PersistentVolumeName != nil && *va.Spec.Source.PersistentVolumeName == volume.Name { return fmt.Errorf("persistentvolume %s is still attached to node %s", volume.Name, va.Spec.NodeName) } } return nil } func (p *csiProvisioner) SupportsBlock(ctx context.Context) bool { // SupportsBlock always return true, because current CSI spec doesn't allow checking // drivers' capability of block volume before creating volume. // Drivers that don't support block volume should return error for CreateVolume called // by Provision if block AccessType is specified. return true } func (p *csiProvisioner) ShouldProvision(ctx context.Context, claim *v1.PersistentVolumeClaim) bool { provisioner := claim.Annotations[annStorageProvisioner] migratedTo := claim.Annotations[annMigratedTo] if provisioner != p.driverName && migratedTo != p.driverName { // Non-migrated in-tree volume is requested. return false } // Either CSI volume is requested or in-tree volume is migrated to CSI in PV controller // and therefore PVC has CSI annotation. // // But before we start provisioning, check that we are (or can // become) the owner if there are multiple provisioner instances. // That we do this here is crucial because if we return false here, // the claim will be ignored without logging an event for it. // We don't want each provisioner instance to log events for the same // claim unless they really need to do some work for it. owned, err := p.checkNode(ctx, claim, nil, "should provision") if err == nil { if !owned { return false } } else { // This is unexpected. Here we can only log it and let // a provisioning attempt start. If that still fails, // a proper event will be created. klog.V(2).Infof("trying to become an owner of PVC %s/%s in advance failed, will try again during provisioning: %s", claim.Namespace, claim.Name, err) } // Start provisioning. return true } //TODO use a unique volume handle from and to Id func (p *csiProvisioner) volumeIdToHandle(id string) string { return id } func (p *csiProvisioner) volumeHandleToId(handle string) string { return handle } // checkNode optionally checks whether the PVC is assigned to the current node. // If the PVC uses immediate binding, it will try to take the PVC for provisioning // on the current node. Returns true if provisioning can proceed, an error // in case of a failure that prevented checking. func (p *csiProvisioner) checkNode(ctx context.Context, claim *v1.PersistentVolumeClaim, sc *storagev1.StorageClass, caller string) (provision bool, err error) { if p.nodeDeployment == nil { return true, nil } var selectedNode string if claim.Annotations != nil { selectedNode = claim.Annotations[annSelectedNode] } switch selectedNode { case "": logger := klog.V(5) if logger.Enabled() { logger.Infof("%s: checking node for PVC %s/%s with resource version %s", caller, claim.Namespace, claim.Name, claim.ResourceVersion) defer func() { logger.Infof("%s: done checking node for PVC %s/%s with resource version %s: provision %v, err %v", caller, claim.Namespace, claim.Name, claim.ResourceVersion, provision, err) }() } if sc == nil { var err error sc, err = p.scLister.Get(*claim.Spec.StorageClassName) if err != nil { return false, err } } if sc.VolumeBindingMode == nil || *sc.VolumeBindingMode != storagev1.VolumeBindingImmediate || !p.nodeDeployment.ImmediateBinding { return false, nil } // Try to select the current node if there is a chance of it // being created there, i.e. there is currently enough free space (checked in becomeOwner). // // If later volume provisioning fails on this node, the annotation will be unset and node // selection will happen again. If no other node picks up the volume, then the PVC remains // in the queue and this check will be repeated from time to time. // // A lot of different external-provisioner instances will try to do this at the same time. // To avoid the thundering herd problem, we sleep in becomeOwner for a short random amount of time // (for new PVCs) or exponentially increasing time (for PVCs were we already had a conflict). if err := p.nodeDeployment.becomeOwner(ctx, p, claim); err != nil { return false, fmt.Errorf("PVC %s/%s: %v", claim.Namespace, claim.Name, err) } // We are now either the owner or someone else is. We'll check when the updated PVC // enters the workqueue and gets processed by sig-storage-lib-external-provisioner. return false, nil case p.nodeDeployment.NodeName: // Our node is selected. return true, nil default: // Some other node is selected, ignore it. return false, nil } } func (p *csiProvisioner) checkCapacity(ctx context.Context, claim *v1.PersistentVolumeClaim, selectedNodeName string) (bool, error) { capacity := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] volSizeBytes := capacity.Value() if volSizeBytes == 0 { // Nothing to check. return true, nil } if claim.Spec.StorageClassName == nil { return false, errors.New("empty storage class name") } sc, err := p.scLister.Get(*claim.Spec.StorageClassName) if err != nil { return false, err } node, err := p.nodeLister.Get(selectedNodeName) if err != nil { return false, err } result, _, err := p.prepareProvision(ctx, claim, sc, node) if err != nil { return false, err } // In practice, we expect exactly one entry here once a node // has been selected. But we have to be prepared for more than // one (=> check all, success if there is at least one) and // none (no node selected => check once without topology). topologies := []*csi.Topology{nil} if result.req.AccessibilityRequirements != nil && len(result.req.AccessibilityRequirements.Requisite) > 0 { topologies = result.req.AccessibilityRequirements.Requisite } for _, topology := range topologies { req := &csi.GetCapacityRequest{ VolumeCapabilities: result.req.VolumeCapabilities, Parameters: result.req.Parameters, AccessibleTopology: topology, } klog.V(5).Infof("GetCapacityRequest %+v", req) resp, err := p.csiClient.GetCapacity(ctx, req) if err != nil { return false, fmt.Errorf("GetCapacity: %v", err) } if volSizeBytes <= resp.AvailableCapacity { // Enough capacity at the moment. return true, nil } } // Currently not enough capacity anywhere. return false, nil } // becomeOwner updates the PVC with the current node as selected node. // Returns an error if something unexpectedly failed, otherwise an updated PVC with // the current node selected or nil if not the owner. func (nc *internalNodeDeployment) becomeOwner(ctx context.Context, p *csiProvisioner, claim *v1.PersistentVolumeClaim) error { requeues := nc.rateLimiter.NumRequeues(claim.UID) delay := nc.rateLimiter.When(claim.UID) klog.V(5).Infof("will try to become owner of PVC %s/%s with resource version %s in %s (attempt #%d)", claim.Namespace, claim.Name, claim.ResourceVersion, delay, requeues) sleep, cancel := context.WithTimeout(ctx, delay) defer cancel() // When the base delay is high we also should check less often. // With multiple provisioners running in parallel, it becomes more // likely that one of them became the owner quickly, so we don't // want to check too slowly either. pollInterval := nc.BaseDelay / 100 if pollInterval < 10*time.Millisecond { pollInterval = 10 * time.Millisecond } ticker := time.NewTicker(pollInterval) defer ticker.Stop() check := func() (bool, *v1.PersistentVolumeClaim, error) { current, err := nc.ClaimInformer.Lister().PersistentVolumeClaims(claim.Namespace).Get(claim.Name) if err != nil { return false, nil, fmt.Errorf("PVC not found: %v", err) } if claim.UID != current.UID { return false, nil, errors.New("PVC was replaced") } if current.Annotations != nil && current.Annotations[annSelectedNode] != "" && current.Annotations[annSelectedNode] != nc.NodeName { return true, current, nil } return false, current, nil } var stop bool var current *v1.PersistentVolumeClaim var err error loop: for { select { case <-ctx.Done(): return errors.New("timed out waiting to become PVC owner") case <-sleep.Done(): stop, current, err = check() break loop case <-ticker.C: // Abort the waiting early if we know that someone else is the owner. stop, current, err = check() if err != nil || stop { break loop } } } if err != nil { return err } if stop { // Some other instance was faster and we don't need to provision for // this PVC. If the PVC needs to be rescheduled, we start the delay from scratch. nc.rateLimiter.Forget(claim.UID) klog.V(5).Infof("did not become owner of PVC %s/%s with resource revision %s, now owned by %s with resource revision %s", claim.Namespace, claim.Name, claim.ResourceVersion, current.Annotations[annSelectedNode], current.ResourceVersion) return nil } // Check capacity as late as possible before trying to become the owner, because that is a // relatively expensive operation. // // The exact same parameters are computed here as if we were provisioning. If a precondition // is violated, like "storage class does not exist", then we have two options: // - silently ignore the problem, but if all instances do that, the problem is not surfaced // to the user // - try to become the owner and let provisioning start, which then will probably // fail the same way, but then has a chance to inform the user via events // // We do the latter. hasCapacity, err := p.checkCapacity(ctx, claim, p.nodeDeployment.NodeName) if err != nil { klog.V(3).Infof("proceeding with becoming owner although the capacity check failed: %v", err) } else if !hasCapacity { // Don't try to provision. klog.V(5).Infof("not enough capacity for PVC %s/%s with resource revision %s", claim.Namespace, claim.Name, claim.ResourceVersion) return nil } // Update PVC with our node as selected node if necessary. current = current.DeepCopy() if current.Annotations == nil { current.Annotations = map[string]string{} } if current.Annotations[annSelectedNode] == nc.NodeName { // A mere sanity check. Should not happen. klog.V(5).Infof("already owner of PVC %s/%s with updated resource version %s", current.Namespace, current.Name, current.ResourceVersion) return nil } current.Annotations[annSelectedNode] = nc.NodeName klog.V(5).Infof("trying to become owner of PVC %s/%s with resource version %s now", current.Namespace, current.Name, current.ResourceVersion) current, err = p.client.CoreV1().PersistentVolumeClaims(current.Namespace).Update(ctx, current, metav1.UpdateOptions{}) if err != nil { // Next attempt will use a longer delay and most likely // stop quickly once we see who owns the PVC now. if apierrors.IsConflict(err) { // Lost the race or some other concurrent modification. Repeat the attempt. klog.V(3).Infof("conflict during PVC %s/%s update, will try again", claim.Namespace, claim.Name) return nc.becomeOwner(ctx, p, claim) } // Some unexpected error. Report it. return fmt.Errorf("selecting node %q for PVC failed: %v", nc.NodeName, err) } // Successfully became owner. Future delays will be smaller again. nc.rateLimiter.Forget(claim.UID) klog.V(5).Infof("became owner of PVC %s/%s with updated resource version %s", current.Namespace, current.Name, current.ResourceVersion) return nil } // verifyAndGetSecretNameAndNamespaceTemplate gets the values (templates) associated // with the parameters specified in "secret" and verifies that they are specified correctly. func verifyAndGetSecretNameAndNamespaceTemplate(secret secretParamsMap, storageClassParams map[string]string) (nameTemplate, namespaceTemplate string, err error) { numName := 0 numNamespace := 0 if t, ok := storageClassParams[secret.deprecatedSecretNameKey]; ok { nameTemplate = t numName++ klog.Warning(deprecationWarning(secret.deprecatedSecretNameKey, secret.secretNameKey, "")) } if t, ok := storageClassParams[secret.deprecatedSecretNamespaceKey]; ok { namespaceTemplate = t numNamespace++ klog.Warning(deprecationWarning(secret.deprecatedSecretNamespaceKey, secret.secretNamespaceKey, "")) } if t, ok := storageClassParams[secret.secretNameKey]; ok { nameTemplate = t numName++ } if t, ok := storageClassParams[secret.secretNamespaceKey]; ok { namespaceTemplate = t numNamespace++ } if numName > 1 || numNamespace > 1 { // Double specified error return "", "", fmt.Errorf("%s secrets specified in parameters with both \"csi\" and \"%s\" keys", secret.name, csiParameterPrefix) } else if numName != numNamespace { // Not both 0 or both 1 return "", "", fmt.Errorf("either name and namespace for %s secrets specified, Both must be specified", secret.name) } else if numName == 1 { // Case where we've found a name and a namespace template if nameTemplate == "" || namespaceTemplate == "" { return "", "", fmt.Errorf("%s secrets specified in parameters but value of either namespace or name is empty", secret.name) } return nameTemplate, namespaceTemplate, nil } else if numName == 0 { // No secrets specified return "", "", nil } else { // THIS IS NOT A VALID CASE return "", "", fmt.Errorf("unknown error with getting secret name and namespace templates") } } // getSecretReference returns a reference to the secret specified in the given nameTemplate // and namespaceTemplate, or an error if the templates are not specified correctly. // no lookup of the referenced secret is performed, and the secret may or may not exist. // // supported tokens for name resolution: // - ${pv.name} // - ${pvc.namespace} // - ${pvc.name} // - ${pvc.annotations['ANNOTATION_KEY']} (e.g. ${pvc.annotations['example.com/node-publish-secret-name']}) // // supported tokens for namespace resolution: // - ${pv.name} // - ${pvc.namespace} // // an error is returned in the following situations: // - the nameTemplate or namespaceTemplate contains a token that cannot be resolved // - the resolved name is not a valid secret name // - the resolved namespace is not a valid namespace name func getSecretReference(secretParams secretParamsMap, storageClassParams map[string]string, pvName string, pvc *v1.PersistentVolumeClaim) (*v1.SecretReference, error) { nameTemplate, namespaceTemplate, err := verifyAndGetSecretNameAndNamespaceTemplate(secretParams, storageClassParams) if err != nil { return nil, fmt.Errorf("failed to get name and namespace template from params: %v", err) } // if didn't find secrets for specific call, try to check default values if nameTemplate == "" && namespaceTemplate == "" { nameTemplate, namespaceTemplate, err = verifyAndGetSecretNameAndNamespaceTemplate(defaultSecretParams, storageClassParams) if err != nil { return nil, fmt.Errorf("failed to get default name and namespace template from params: %v", err) } } if nameTemplate == "" && namespaceTemplate == "" { return nil, nil } ref := &v1.SecretReference{} { // Secret namespace template can make use of the PV name or the PVC namespace. // Note that neither of those things are under the control of the PVC user. namespaceParams := map[string]string{tokenPVNameKey: pvName} if pvc != nil { namespaceParams[tokenPVCNameSpaceKey] = pvc.Namespace } resolvedNamespace, err := resolveTemplate(namespaceTemplate, namespaceParams) if err != nil { return nil, fmt.Errorf("error resolving value %q: %v", namespaceTemplate, err) } if len(validation.IsDNS1123Label(resolvedNamespace)) > 0 { if namespaceTemplate != resolvedNamespace { return nil, fmt.Errorf("%q resolved to %q which is not a valid namespace name", namespaceTemplate, resolvedNamespace) } return nil, fmt.Errorf("%q is not a valid namespace name", namespaceTemplate) } ref.Namespace = resolvedNamespace } { // Secret name template can make use of the PV name, PVC name or namespace, or a PVC annotation. // Note that PVC name and annotations are under the PVC user's control. nameParams := map[string]string{tokenPVNameKey: pvName} if pvc != nil { nameParams[tokenPVCNameKey] = pvc.Name nameParams[tokenPVCNameSpaceKey] = pvc.Namespace for k, v := range pvc.Annotations { nameParams["pvc.annotations['"+k+"']"] = v } } resolvedName, err := resolveTemplate(nameTemplate, nameParams) if err != nil { return nil, fmt.Errorf("error resolving value %q: %v", nameTemplate, err) } if len(validation.IsDNS1123Subdomain(resolvedName)) > 0 { if nameTemplate != resolvedName { return nil, fmt.Errorf("%q resolved to %q which is not a valid secret name", nameTemplate, resolvedName) } return nil, fmt.Errorf("%q is not a valid secret name", nameTemplate) } ref.Name = resolvedName } return ref, nil } func resolveTemplate(template string, params map[string]string) (string, error) { missingParams := sets.NewString() resolved := os.Expand(template, func(k string) string { v, ok := params[k] if !ok { missingParams.Insert(k) } return v }) if missingParams.Len() > 0 { return "", fmt.Errorf("invalid tokens: %q", missingParams.List()) } return resolved, nil } func getCredentials(ctx context.Context, k8s kubernetes.Interface, ref *v1.SecretReference) (map[string]string, error) { if ref == nil { return nil, nil } secret, err := k8s.CoreV1().Secrets(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("error getting secret %s in namespace %s: %v", ref.Name, ref.Namespace, err) } credentials := map[string]string{} for key, value := range secret.Data { credentials[key] = string(value) } return credentials, nil } func bytesToQuantity(bytes int64) resource.Quantity { quantity := resource.NewQuantity(bytes, resource.BinarySI) return *quantity } func deprecationWarning(deprecatedParam, newParam, removalVersion string) string { if removalVersion == "" { removalVersion = "a future release" } newParamPhrase := "" if len(newParam) != 0 { newParamPhrase = fmt.Sprintf(", please use \"%s\" instead", newParam) } return fmt.Sprintf("\"%s\" is deprecated and will be removed in %s%s", deprecatedParam, removalVersion, newParamPhrase) } func checkError(err error, mayReschedule bool) controller.ProvisioningState { // Sources: // https://github.com/grpc/grpc/blob/master/doc/statuscodes.md // https://github.com/container-storage-interface/spec/blob/master/spec.md st, ok := status.FromError(err) if !ok { // This is not gRPC error. The operation must have failed before gRPC // method was called, otherwise we would get gRPC error. // We don't know if any previous CreateVolume is in progress, be on the safe side. return controller.ProvisioningInBackground } switch st.Code() { case codes.ResourceExhausted: // CSI: operation not pending, "Unable to provision in `accessible_topology`" // However, it also could be from the transport layer for "message size exceeded". // Cannot be decided properly here and needs to be resolved in the spec // https://github.com/container-storage-interface/spec/issues/419. // What we assume here for now is that message size limits are large enough that // the error really comes from the CSI driver. if mayReschedule { // may succeed elsewhere -> give up for now return controller.ProvisioningReschedule } // may still succeed at a later time -> continue return controller.ProvisioningInBackground case codes.Canceled, // gRPC: Client Application cancelled the request codes.DeadlineExceeded, // gRPC: Timeout codes.Unavailable, // gRPC: Server shutting down, TCP connection broken - previous CreateVolume() may be still in progress. codes.Aborted: // CSI: Operation pending for volume return controller.ProvisioningInBackground } // All other errors mean that provisioning either did not // even start or failed. It is for sure not in progress. return controller.ProvisioningFinished } func cleanupVolume(ctx context.Context, p *csiProvisioner, delReq *csi.DeleteVolumeRequest, provisionerCredentials map[string]string) error { var err error delReq.Secrets = provisionerCredentials deleteCtx, cancel := context.WithTimeout(ctx, p.timeout) defer cancel() for i := 0; i < deleteVolumeRetryCount; i++ { _, err = p.csiClient.DeleteVolume(deleteCtx, delReq) if err == nil { break } } return err } func checkFinalizer(obj metav1.Object, finalizer string) bool { for _, f := range obj.GetFinalizers() { if f == finalizer { return true } } return false }
{ "content_hash": "9d241615733f3d58b796d80665b78a0c", "timestamp": "", "source": "github", "line_count": 1791, "max_line_length": 234, "avg_line_length": 40.103294249022895, "alnum_prop": 0.7374591019839889, "repo_name": "opensds/nbp", "id": "cacdf16c04db614bd84bfe8d62dee53766efdfd3", "size": "72394", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "csi-plug-n-play/sidecars/soda-csi-provisioner/external-provisioner/pkg/controller/controller.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4126" }, { "name": "CSS", "bytes": "25925" }, { "name": "Dockerfile", "bytes": "2945" }, { "name": "Go", "bytes": "374655" }, { "name": "HTML", "bytes": "366245" }, { "name": "Java", "bytes": "623998" }, { "name": "JavaScript", "bytes": "198363" }, { "name": "Makefile", "bytes": "5163" }, { "name": "Shell", "bytes": "7246" } ], "symlink_target": "" }
package cloud.tools.mysql.jpa.entity; import javax.persistence.*; @Entity @Table(name = "COLUMNS") public class Columns { @Id private int id; private String TABLE_CATALOG; private String TABLE_SCHEMA; private String TABLE_NAME; private String COLUMN_NAME; private long ORDINAL_POSITION; private String COLUMN_DEFAULT; private String IS_NULLABLE; private String DATA_TYPE; private long CHARACTER_MAXIMUM_LENGTH; private long CHARACTER_OCTET_LENGTH; private long NUMERIC_PRECISION; private long NUMERIC_SCALE; private long DATETIME_PRECISION; private String CHARACTER_SET_NAME; private String COLLATION_NAME; private String COLUMN_TYPE; private String COLUMN_KEY; private String EXTRA; private String PRIVILEGES; private String COLUMN_COMMENT; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTABLE_CATALOG() { return TABLE_CATALOG; } public void setTABLE_CATALOG(String tABLE_CATALOG) { TABLE_CATALOG = tABLE_CATALOG; } public String getTABLE_SCHEMA() { return TABLE_SCHEMA; } public void setTABLE_SCHEMA(String tABLE_SCHEMA) { TABLE_SCHEMA = tABLE_SCHEMA; } public String getTABLE_NAME() { return TABLE_NAME; } public void setTABLE_NAME(String tABLE_NAME) { TABLE_NAME = tABLE_NAME; } public String getCOLUMN_NAME() { return COLUMN_NAME; } public void setCOLUMN_NAME(String cOLUMN_NAME) { COLUMN_NAME = cOLUMN_NAME; } public long getORDINAL_POSITION() { return ORDINAL_POSITION; } public void setORDINAL_POSITION(long oRDINAL_POSITION) { ORDINAL_POSITION = oRDINAL_POSITION; } public String getCOLUMN_DEFAULT() { return COLUMN_DEFAULT; } public void setCOLUMN_DEFAULT(String cOLUMN_DEFAULT) { COLUMN_DEFAULT = cOLUMN_DEFAULT; } public String getIS_NULLABLE() { return IS_NULLABLE; } public void setIS_NULLABLE(String iS_NULLABLE) { IS_NULLABLE = iS_NULLABLE; } public String getDATA_TYPE() { return DATA_TYPE; } public void setDATA_TYPE(String dATA_TYPE) { DATA_TYPE = dATA_TYPE; } public long getCHARACTER_MAXIMUM_LENGTH() { return CHARACTER_MAXIMUM_LENGTH; } public void setCHARACTER_MAXIMUM_LENGTH(long cHARACTER_MAXIMUM_LENGTH) { CHARACTER_MAXIMUM_LENGTH = cHARACTER_MAXIMUM_LENGTH; } public long getCHARACTER_OCTET_LENGTH() { return CHARACTER_OCTET_LENGTH; } public void setCHARACTER_OCTET_LENGTH(long cHARACTER_OCTET_LENGTH) { CHARACTER_OCTET_LENGTH = cHARACTER_OCTET_LENGTH; } public long getNUMERIC_PRECISION() { return NUMERIC_PRECISION; } public void setNUMERIC_PRECISION(long nUMERIC_PRECISION) { NUMERIC_PRECISION = nUMERIC_PRECISION; } public long getNUMERIC_SCALE() { return NUMERIC_SCALE; } public void setNUMERIC_SCALE(long nUMERIC_SCALE) { NUMERIC_SCALE = nUMERIC_SCALE; } public long getDATETIME_PRECISION() { return DATETIME_PRECISION; } public void setDATETIME_PRECISION(long dATETIME_PRECISION) { DATETIME_PRECISION = dATETIME_PRECISION; } public String getCHARACTER_SET_NAME() { return CHARACTER_SET_NAME; } public void setCHARACTER_SET_NAME(String cHARACTER_SET_NAME) { CHARACTER_SET_NAME = cHARACTER_SET_NAME; } public String getCOLLATION_NAME() { return COLLATION_NAME; } public void setCOLLATION_NAME(String cOLLATION_NAME) { COLLATION_NAME = cOLLATION_NAME; } public String getCOLUMN_TYPE() { return COLUMN_TYPE; } public void setCOLUMN_TYPE(String cOLUMN_TYPE) { COLUMN_TYPE = cOLUMN_TYPE; } public String getCOLUMN_KEY() { return COLUMN_KEY; } public void setCOLUMN_KEY(String cOLUMN_KEY) { COLUMN_KEY = cOLUMN_KEY; } public String getEXTRA() { return EXTRA; } public void setEXTRA(String eXTRA) { EXTRA = eXTRA; } public String getPRIVILEGES() { return PRIVILEGES; } public void setPRIVILEGES(String pRIVILEGES) { PRIVILEGES = pRIVILEGES; } public String getCOLUMN_COMMENT() { return COLUMN_COMMENT; } public void setCOLUMN_COMMENT(String cOLUMN_COMMENT) { COLUMN_COMMENT = cOLUMN_COMMENT; } }
{ "content_hash": "20b3afeff94c3d3d35a3c21485e41e0b", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 73, "avg_line_length": 19.935323383084576, "alnum_prop": 0.7332168704766658, "repo_name": "hardimplistic/myflow", "id": "b9bbd2bf9166581d716dcb55c3214149a59c4da5", "size": "4007", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "myflow-tools-mysql/src/main/java/cloud/tools/mysql/jpa/entity/Columns.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "29763" }, { "name": "HTML", "bytes": "17374" }, { "name": "Java", "bytes": "109083" }, { "name": "JavaScript", "bytes": "21972" } ], "symlink_target": "" }
package nl.javadude.scannit.metadata; import javassist.bytecode.ClassFile; import javassist.bytecode.Descriptor; import javassist.bytecode.FieldInfo; import javassist.bytecode.MethodInfo; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; /** * Helper that converts Java Classes, Fields and Methods to/from a String representation. */ public class DescriptorHelper { private static String[] primitiveNames = new String[]{"boolean", "byte", "char", "short", "int", "long", "float", "double"}; private static String[] primitiveDescriptors = new String[]{"Z", "B", "C", "S", "I", "J", "F", "D"}; @SuppressWarnings({"unchecked"}) private static Class<?>[] primitiveClasses = new Class[]{boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class}; /** * Convert the Javassist ClassFile to a String representation. * * @param file a Javassist ClassFile * @return a String representing the full class name */ public static String toTypeDescriptor(ClassFile file) { return file.getName(); } /** * Convert a Javassist ClassFile and MethodInfo to a String representation. * * @param file a Javassist ClassFile * @param method a Javassist MethodInfo * @return a String representing the full class name followed by the method and its signature */ public static String toMethodDescriptor(ClassFile file, MethodInfo method) { return new StringBuilder(toTypeDescriptor(file)).append(".").append(method.getName()).append(parameters(method)).toString(); } private static String parameters(MethodInfo method) { return Descriptor.toString(method.getDescriptor()); } /** * Convert a Javassist ClassFile and FieldInfo to a String representation. * * @param file a Javassist ClassFile * @param field a Javassist FieldInfo * @return a String representing the full class name followed by the field name. */ public static String tofieldDescriptor(ClassFile file, FieldInfo field) { return new StringBuilder(toTypeDescriptor(file)).append(".").append(field.getName()).toString(); } /** * Convert a String representation of the class to a Java class * * @param descriptor the full class name * @return a Java class */ public static Class<?> fromTypeDescriptor(String descriptor) { try { return Class.forName(descriptor, false, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Class not found for: " + descriptor, e); } } /** * Convert a String representation of the method to a Java Reflect Method * * @param methodDescriptor the full string representation of the method (including class name and parameters) * @return a Java Reflect Method */ public static Method fromMethodDescriptor(String methodDescriptor) { int startParameterList = methodDescriptor.indexOf('('); int endParameterList = methodDescriptor.indexOf(')'); String classAndMethodName = methodDescriptor.substring(0, startParameterList); int classMethodSep = classAndMethodName.lastIndexOf('.'); Class<?> aClass = fromTypeDescriptor(classAndMethodName.substring(0, classMethodSep)); String methodName = classAndMethodName.substring(classMethodSep + 1, startParameterList); Class<?>[] parameters = parameters(methodDescriptor.substring(startParameterList + 1, endParameterList)); try { return aClass.getMethod(methodName, parameters); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Method " + methodName + " with parameters: " + Arrays.toString(parameters) + " could not be located.", e); } } private static int findInPrimitiveNames(String n) { for (int i = 0; i < primitiveNames.length; i++) { String primitiveName = primitiveNames[i]; if (primitiveName.equals(n)) { return i; } } return -1; } private static Class<?>[] parameters(String parameters) { if (parameters == null || parameters.isEmpty()) return new Class[0]; String[] paramDescriptors = parameters.split(", *"); Class<?>[] clazzes = new Class<?>[paramDescriptors.length]; for (int i = 0; i < paramDescriptors.length; i++) { String paramDescriptor = paramDescriptors[i]; if (isPrimitive(paramDescriptor)) { clazzes[i] = primitiveClasses[findInPrimitiveNames(paramDescriptor)]; } else { String type = paramDescriptor; if (isArray(paramDescriptor)) { String arrayType = paramDescriptor.substring(0, paramDescriptor.indexOf('[')); if (isPrimitive(arrayType)) { type = "[" + primitiveDescriptors[findInPrimitiveNames(arrayType)]; } else { type = "[L" + arrayType + ";"; } } try { clazzes[i] = Class.forName(type, false, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not load class: " + paramDescriptor, e); } } } return clazzes; } private static boolean isArray(String paramDescriptor) { return paramDescriptor.indexOf('[') != -1; } private static boolean isPrimitive(String paramDescriptor) { return findInPrimitiveNames(paramDescriptor) != -1; } /** * Convert a string representation of a field to a Java Reflect Field. * * @param fieldDescriptor a String representation of a Field (including the class name) * @return a Java Reflect Field */ public static Field fromFieldDescriptor(String fieldDescriptor) { int lastDot = fieldDescriptor.lastIndexOf('.'); String className = fieldDescriptor.substring(0, lastDot); String fieldName = fieldDescriptor.substring(lastDot + 1); Class<?> aClass = fromTypeDescriptor(className); try { return aClass.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { throw new IllegalArgumentException("Field " + fieldName + " not found on class " + className, e); } } }
{ "content_hash": "0d9ae8c0f34447201fbd02f3b10d1cbe", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 163, "avg_line_length": 41.33125, "alnum_prop": 0.6428247391501588, "repo_name": "hierynomus/scannit", "id": "a49cefd4e40425825653c78916142ec926a34d05", "size": "7307", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/nl/javadude/scannit/metadata/DescriptorHelper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "77299" } ], "symlink_target": "" }
package io.georocket.output.geojson; import org.apache.commons.lang3.tuple.Pair; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import io.georocket.storage.ChunkReadStream; import io.georocket.storage.GeoJsonChunkMeta; import io.georocket.util.io.BufferWriteStream; import io.georocket.util.io.DelegateChunkReadStream; import io.vertx.core.buffer.Buffer; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import rx.Observable; /** * Test {@link GeoJsonMerger} * @author Michel Kraemer */ @RunWith(VertxUnitRunner.class) public class GeoJsonMergerTest { /** * Run the test on a Vert.x test context */ @Rule public RunTestOnContext rule = new RunTestOnContext(); private void doMerge(TestContext context, Observable<Buffer> chunks, Observable<GeoJsonChunkMeta> metas, String jsonContents) { GeoJsonMerger m = new GeoJsonMerger(); BufferWriteStream bws = new BufferWriteStream(); Async async = context.async(); metas .flatMap(meta -> m.init(meta).map(v -> meta)) .toList() .flatMap(l -> chunks.map(DelegateChunkReadStream::new) .<GeoJsonChunkMeta, Pair<ChunkReadStream, GeoJsonChunkMeta>>zipWith(l, Pair::of)) .flatMap(p -> m.merge(p.getLeft(), p.getRight(), bws)) .last() .subscribe(v -> { m.finish(bws); context.assertEquals(jsonContents, bws.getBuffer().toString("utf-8")); async.complete(); }, err -> { context.fail(err); }); } /** * Test if one geometry is rendered directly * @param context the Vert.x test context */ @Test public void oneGeometry(TestContext context) { String strChunk1 = "{\"type\":\"Polygon\"}"; Buffer chunk1 = Buffer.buffer(strChunk1); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Polygon", "geometries", 0, chunk1.length()); doMerge(context, Observable.just(chunk1), Observable.just(cm1), strChunk1); } /** * Test if one feature is rendered directly * @param context the Vert.x test context */ @Test public void oneFeature(TestContext context) { String strChunk1 = "{\"type\":\"Feature\"}"; Buffer chunk1 = Buffer.buffer(strChunk1); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Feature", "features", 0, chunk1.length()); doMerge(context, Observable.just(chunk1), Observable.just(cm1), strChunk1); } /** * Test if two geometries can be merged to a geometry collection * @param context the Vert.x test context */ @Test public void twoGeometries(TestContext context) { String strChunk1 = "{\"type\":\"Polygon\"}"; String strChunk2 = "{\"type\":\"Point\"}"; Buffer chunk1 = Buffer.buffer(strChunk1); Buffer chunk2 = Buffer.buffer(strChunk2); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Polygon", "geometries", 0, chunk1.length()); GeoJsonChunkMeta cm2 = new GeoJsonChunkMeta("Point", "geometries", 0, chunk2.length()); doMerge(context, Observable.just(chunk1, chunk2), Observable.just(cm1, cm2), "{\"type\":\"GeometryCollection\",\"geometries\":[" + strChunk1 + "," + strChunk2 + "]}"); } /** * Test if three geometries can be merged to a geometry collection * @param context the Vert.x test context */ @Test public void threeGeometries(TestContext context) { String strChunk1 = "{\"type\":\"Polygon\"}"; String strChunk2 = "{\"type\":\"Point\"}"; String strChunk3 = "{\"type\":\"MultiPoint\"}"; Buffer chunk1 = Buffer.buffer(strChunk1); Buffer chunk2 = Buffer.buffer(strChunk2); Buffer chunk3 = Buffer.buffer(strChunk3); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Polygon", "geometries", 0, chunk1.length()); GeoJsonChunkMeta cm2 = new GeoJsonChunkMeta("Point", "geometries", 0, chunk2.length()); GeoJsonChunkMeta cm3 = new GeoJsonChunkMeta("MultiPoint", "geometries", 0, chunk3.length()); doMerge(context, Observable.just(chunk1, chunk2, chunk3), Observable.just(cm1, cm2, cm3), "{\"type\":\"GeometryCollection\",\"geometries\":[" + strChunk1 + "," + strChunk2 + "," + strChunk3 + "]}"); } /** * Test if two features can be merged to a feature collection * @param context the Vert.x test context */ @Test public void twoFeatures(TestContext context) { String strChunk1 = "{\"type\":\"Feature\"}"; String strChunk2 = "{\"type\":\"Feature\",\"properties\":{}}"; Buffer chunk1 = Buffer.buffer(strChunk1); Buffer chunk2 = Buffer.buffer(strChunk2); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Feature", "features", 0, chunk1.length()); GeoJsonChunkMeta cm2 = new GeoJsonChunkMeta("Feature", "features", 0, chunk2.length()); doMerge(context, Observable.just(chunk1, chunk2), Observable.just(cm1, cm2), "{\"type\":\"FeatureCollection\",\"features\":[" + strChunk1 + "," + strChunk2 + "]}"); } /** * Test if three features can be merged to a feature collection * @param context the Vert.x test context */ @Test public void threeFeatures(TestContext context) { String strChunk1 = "{\"type\":\"Feature\"}"; String strChunk2 = "{\"type\":\"Feature\",\"properties\":{}}"; String strChunk3 = "{\"type\":\"Feature\",\"geometry\":[]}"; Buffer chunk1 = Buffer.buffer(strChunk1); Buffer chunk2 = Buffer.buffer(strChunk2); Buffer chunk3 = Buffer.buffer(strChunk3); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Feature", "features", 0, chunk1.length()); GeoJsonChunkMeta cm2 = new GeoJsonChunkMeta("Feature", "features", 0, chunk2.length()); GeoJsonChunkMeta cm3 = new GeoJsonChunkMeta("Feature", "features", 0, chunk3.length()); doMerge(context, Observable.just(chunk1, chunk2, chunk3), Observable.just(cm1, cm2, cm3), "{\"type\":\"FeatureCollection\",\"features\":[" + strChunk1 + "," + strChunk2 + "," + strChunk3 + "]}"); } /** * Test if two geometries and a feature can be merged to a feature collection * @param context the Vert.x test context */ @Test public void geometryAndFeature(TestContext context) { String strChunk1 = "{\"type\":\"Polygon\"}"; String strChunk2 = "{\"type\":\"Feature\"}"; Buffer chunk1 = Buffer.buffer(strChunk1); Buffer chunk2 = Buffer.buffer(strChunk2); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Polygon", "geometries", 0, chunk1.length()); GeoJsonChunkMeta cm2 = new GeoJsonChunkMeta("Feature", "features", 0, chunk2.length()); doMerge(context, Observable.just(chunk1, chunk2), Observable.just(cm1, cm2), "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":" + strChunk1 + "}," + strChunk2 + "]}"); } /** * Test if two geometries and a feature can be merged to a feature collection * @param context the Vert.x test context */ @Test public void featureAndGeometry(TestContext context) { String strChunk1 = "{\"type\":\"Feature\"}"; String strChunk2 = "{\"type\":\"Polygon\"}"; Buffer chunk1 = Buffer.buffer(strChunk1); Buffer chunk2 = Buffer.buffer(strChunk2); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Feature", "features", 0, chunk1.length()); GeoJsonChunkMeta cm2 = new GeoJsonChunkMeta("Polygon", "geometries", 0, chunk2.length()); doMerge(context, Observable.just(chunk1, chunk2), Observable.just(cm1, cm2), "{\"type\":\"FeatureCollection\",\"features\":[" + strChunk1 + ",{\"type\":\"Feature\",\"geometry\":" + strChunk2 + "}]}"); } /** * Test if two geometries and a feature can be merged to a feature collection * @param context the Vert.x test context */ @Test public void twoGeometriesAndAFeature(TestContext context) { String strChunk1 = "{\"type\":\"Polygon\"}"; String strChunk2 = "{\"type\":\"Point\"}"; String strChunk3 = "{\"type\":\"Feature\"}"; Buffer chunk1 = Buffer.buffer(strChunk1); Buffer chunk2 = Buffer.buffer(strChunk2); Buffer chunk3 = Buffer.buffer(strChunk3); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Polygon", "geometries", 0, chunk1.length()); GeoJsonChunkMeta cm2 = new GeoJsonChunkMeta("Point", "geometries", 0, chunk2.length()); GeoJsonChunkMeta cm3 = new GeoJsonChunkMeta("Feature", "features", 0, chunk3.length()); doMerge(context, Observable.just(chunk1, chunk2, chunk3), Observable.just(cm1, cm2, cm3), "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":" + strChunk1 + "}," + "{\"type\":\"Feature\",\"geometry\":" + strChunk2 + "}," + strChunk3 + "]}"); } /** * Test if two geometries and a feature can be merged to a feature collection * @param context the Vert.x test context */ @Test public void twoFeaturesAndAGeometry(TestContext context) { String strChunk1 = "{\"type\":\"Feature\"}"; String strChunk2 = "{\"type\":\"Feature\",\"properties\":{}}"; String strChunk3 = "{\"type\":\"Point\"}"; Buffer chunk1 = Buffer.buffer(strChunk1); Buffer chunk2 = Buffer.buffer(strChunk2); Buffer chunk3 = Buffer.buffer(strChunk3); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Feature", "features", 0, chunk1.length()); GeoJsonChunkMeta cm2 = new GeoJsonChunkMeta("Feature", "features", 0, chunk2.length()); GeoJsonChunkMeta cm3 = new GeoJsonChunkMeta("Point", "geometries", 0, chunk3.length()); doMerge(context, Observable.just(chunk1, chunk2, chunk3), Observable.just(cm1, cm2, cm3), "{\"type\":\"FeatureCollection\",\"features\":[" + strChunk1 + "," + strChunk2 + ",{\"type\":\"Feature\",\"geometry\":" + strChunk3 + "}]}"); } /** * Test if the merger fails if {@link GeoJsonMerger#init(GeoJsonChunkMeta)} has * not been called often enough * @param context the Vert.x test context */ @Test public void notEnoughInits(TestContext context) { String strChunk1 = "{\"type\":\"Feature\"}"; String strChunk2 = "{\"type\":\"Feature\",\"properties\":{}}"; Buffer chunk1 = Buffer.buffer(strChunk1); Buffer chunk2 = Buffer.buffer(strChunk2); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Feature", "features", 0, chunk1.length()); GeoJsonChunkMeta cm2 = new GeoJsonChunkMeta("Feature", "features", 0, chunk2.length()); GeoJsonMerger m = new GeoJsonMerger(); BufferWriteStream bws = new BufferWriteStream(); Async async = context.async(); m.init(cm1) .flatMap(v -> m.merge(new DelegateChunkReadStream(chunk1), cm1, bws)) .flatMap(v -> m.merge(new DelegateChunkReadStream(chunk2), cm2, bws)) .last() .subscribe(v -> { context.fail(); }, err -> { context.assertTrue(err instanceof IllegalStateException); async.complete(); }); } /** * Test if the merger succeeds if {@link GeoJsonMerger#init(GeoJsonChunkMeta)} has * not been called just often enough * @param context the Vert.x test context */ @Test public void enoughInits(TestContext context) { String strChunk1 = "{\"type\":\"Feature\"}"; String strChunk2 = "{\"type\":\"Feature\",\"properties\":{}}"; String strChunk3 = "{\"type\":\"Polygon\"}"; Buffer chunk1 = Buffer.buffer(strChunk1); Buffer chunk2 = Buffer.buffer(strChunk2); Buffer chunk3 = Buffer.buffer(strChunk3); GeoJsonChunkMeta cm1 = new GeoJsonChunkMeta("Feature", "features", 0, chunk1.length()); GeoJsonChunkMeta cm2 = new GeoJsonChunkMeta("Feature", "features", 0, chunk2.length()); GeoJsonChunkMeta cm3 = new GeoJsonChunkMeta("Polygon", "geometries", 0, chunk2.length()); String jsonContents = "{\"type\":\"FeatureCollection\",\"features\":[" + strChunk1 + "," + strChunk2 + ",{\"type\":\"Feature\",\"geometry\":" + strChunk3 + "}]}"; GeoJsonMerger m = new GeoJsonMerger(); BufferWriteStream bws = new BufferWriteStream(); Async async = context.async(); m.init(cm1) .flatMap(v -> m.init(cm2)) .flatMap(v -> m.merge(new DelegateChunkReadStream(chunk1), cm1, bws)) .flatMap(v -> m.merge(new DelegateChunkReadStream(chunk2), cm2, bws)) .flatMap(v -> m.merge(new DelegateChunkReadStream(chunk3), cm3, bws)) .last() .subscribe(v -> { m.finish(bws); context.assertEquals(jsonContents, bws.getBuffer().toString("utf-8")); async.complete(); }, context::fail); } }
{ "content_hash": "d2273f4ededaa712e7dc49ab7b05544f", "timestamp": "", "source": "github", "line_count": 288, "max_line_length": 110, "avg_line_length": 43.03819444444444, "alnum_prop": 0.6560709963695038, "repo_name": "andrej-sajenko/georocket", "id": "d9884580ecce963b14d5efa8e7e04a81952039ef", "size": "12395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "georocket-server/src/test/java/io/georocket/output/geojson/GeoJsonMergerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "940" }, { "name": "Groovy", "bytes": "30082" }, { "name": "Java", "bytes": "746331" }, { "name": "Shell", "bytes": "2555" } ], "symlink_target": "" }
<!doctype html> <html> <title>prune</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="./style.css"> <body> <div id="wrapper"> <h1><a href="../api/prune.html">prune</a></h1> <p>Remove extraneous packages</p> <h2 id="SYNOPSIS">SYNOPSIS</h2> <pre><code>npm.commands.prune([packages,] callback)</code></pre> <h2 id="DESCRIPTION">DESCRIPTION</h2> <p>This command removes "extraneous" packages.</p> <p>The first parameter is optional, and it specifies packages to be removed.</p> <p>No packages are specified, then all packages will be checked.</p> <p>Extraneous packages are packages that are not listed on the parent package's dependencies list.</p> </div> <p id="footer">prune &mdash; npm@1.1.16</p> <script> ;(function () { var wrapper = document.getElementById("wrapper") var els = Array.prototype.slice.call(wrapper.getElementsByTagName("*"), 0) .filter(function (el) { return el.parentNode === wrapper && el.tagName.match(/H[1-6]/) && el.id }) var l = 2 , toc = document.createElement("ul") toc.innerHTML = els.map(function (el) { var i = el.tagName.charAt(1) , out = "" while (i > l) { out += "<ul>" l ++ } while (i < l) { out += "</ul>" l -- } out += "<li><a href='#" + el.id + "'>" + ( el.innerText || el.text || el.innerHTML) + "</a>" return out }).join("\n") toc.id = "toc" document.body.appendChild(toc) })() </script> </body></html>
{ "content_hash": "6cca5352e582270a75b661fe86a75457", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 80, "avg_line_length": 25.67241379310345, "alnum_prop": 0.6212222968435192, "repo_name": "carlosbeatortega/sociedades", "id": "c178d521668740a8e2cf6fd5187f09e0fca87f11", "size": "1489", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/node/node_modules/npm/html/api/prune.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "358899" }, { "name": "JavaScript", "bytes": "485611" }, { "name": "PHP", "bytes": "550901" }, { "name": "Shell", "bytes": "633" } ], "symlink_target": "" }
#include <common.h> #include <malloc.h> #include <errno.h> #include <dfu.h> int dfu_tftp_write(char *dfu_entity_name, unsigned int addr, unsigned int len, char *interface, char *devstring) { char *s, *sb; int alt_setting_num, ret; struct dfu_entity *dfu; debug("%s: name: %s addr: 0x%x len: %d device: %s:%s\n", __func__, dfu_entity_name, addr, len, interface, devstring); ret = dfu_init_env_entities(interface, devstring); if (ret) goto done; /* * We need to copy name pointed by *dfu_entity_name since this text * is the integral part of the FDT image. * Any implicit modification (i.e. done by strsep()) will corrupt * the FDT image and prevent other images to be stored. */ s = strdup(dfu_entity_name); sb = s; if (!s) { ret = -ENOMEM; goto done; } strsep(&s, "@"); debug("%s: image name: %s strlen: %d\n", __func__, sb, strlen(sb)); alt_setting_num = dfu_get_alt(sb); free(sb); if (alt_setting_num < 0) { pr_err("Alt setting [%d] to write not found!", alt_setting_num); ret = -ENODEV; goto done; } dfu = dfu_get_entity(alt_setting_num); if (!dfu) { pr_err("DFU entity for alt: %d not found!", alt_setting_num); ret = -ENODEV; goto done; } ret = dfu_write_from_mem_addr(dfu, (void *)addr, len); done: dfu_free_entities(); return ret; }
{ "content_hash": "ba59294cfaddbfa253c6441e7b150720", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 78, "avg_line_length": 22.05, "alnum_prop": 0.6273620559334845, "repo_name": "guileschool/beagleboard", "id": "62bf797dac9f11d26f5c325b457e03ce96565a8f", "size": "1433", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "u-boot/drivers/dfu/dfu_tftp.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "960094" }, { "name": "Awk", "bytes": "269" }, { "name": "Batchfile", "bytes": "3451" }, { "name": "C", "bytes": "62720528" }, { "name": "C++", "bytes": "5261365" }, { "name": "CSS", "bytes": "8362" }, { "name": "GDB", "bytes": "3642" }, { "name": "HTML", "bytes": "237884" }, { "name": "Lex", "bytes": "13917" }, { "name": "Makefile", "bytes": "429363" }, { "name": "Objective-C", "bytes": "370078" }, { "name": "Perl", "bytes": "358570" }, { "name": "Python", "bytes": "884691" }, { "name": "Roff", "bytes": "9384" }, { "name": "Shell", "bytes": "96042" }, { "name": "Tcl", "bytes": "967" }, { "name": "XSLT", "bytes": "445" }, { "name": "Yacc", "bytes": "26163" } ], "symlink_target": "" }
namespace ppapi { namespace thunk { namespace { typedef EnterResource<PPB_Graphics3D_API> EnterGraphics3D; PP_Graphics3DTrustedState GetErrorState() { PP_Graphics3DTrustedState error_state = { 0 }; error_state.error = PPB_GRAPHICS3D_TRUSTED_ERROR_GENERICERROR; return error_state; } PP_Resource CreateRaw(PP_Instance instance, PP_Resource share_context, const int32_t* attrib_list) { EnterFunction<ResourceCreationAPI> enter(instance, true); if (enter.failed()) return 0; return enter.functions()->CreateGraphics3DRaw( instance, share_context, attrib_list); } PP_Bool InitCommandBuffer(PP_Resource context) { EnterGraphics3D enter(context, true); if (enter.failed()) return PP_FALSE; return enter.object()->InitCommandBuffer(); } PP_Bool SetGetBuffer(PP_Resource context, int32_t transfer_buffer_id) { EnterGraphics3D enter(context, true); if (enter.failed()) return PP_FALSE; return enter.object()->SetGetBuffer(transfer_buffer_id); } PP_Graphics3DTrustedState GetState(PP_Resource context) { EnterGraphics3D enter(context, true); if (enter.failed()) return GetErrorState(); return enter.object()->GetState(); } int32_t CreateTransferBuffer(PP_Resource context, uint32_t size) { EnterGraphics3D enter(context, true); if (enter.failed()) return PP_FALSE; return enter.object()->CreateTransferBuffer(size); } PP_Bool DestroyTransferBuffer(PP_Resource context, int32_t id) { EnterGraphics3D enter(context, true); if (enter.failed()) return PP_FALSE; return enter.object()->DestroyTransferBuffer(id); } PP_Bool GetTransferBuffer(PP_Resource context, int32_t id, int* shm_handle, uint32_t* shm_size) { EnterGraphics3D enter(context, true); if (enter.failed()) return PP_FALSE; return enter.object()->GetTransferBuffer(id, shm_handle, shm_size); } PP_Bool Flush(PP_Resource context, int32_t put_offset) { EnterGraphics3D enter(context, true); if (enter.failed()) return PP_FALSE; return enter.object()->Flush(put_offset); } PP_Graphics3DTrustedState FlushSync(PP_Resource context, int32_t put_offset) { EnterGraphics3D enter(context, true); if (enter.failed()) return GetErrorState(); return enter.object()->FlushSync(put_offset); } PP_Graphics3DTrustedState FlushSyncFast(PP_Resource context, int32_t put_offset, int32_t last_known_get) { EnterGraphics3D enter(context, true); if (enter.failed()) return GetErrorState(); return enter.object()->FlushSyncFast(put_offset, last_known_get); } const PPB_Graphics3DTrusted g_ppb_graphics_3d_trusted_thunk = { &CreateRaw, &InitCommandBuffer, &SetGetBuffer, &GetState, &CreateTransferBuffer, &DestroyTransferBuffer, &GetTransferBuffer, &Flush, &FlushSync, &FlushSyncFast, }; } // namespace const PPB_Graphics3DTrusted_1_0* GetPPB_Graphics3DTrusted_1_0_Thunk() { return &g_ppb_graphics_3d_trusted_thunk; } } // namespace thunk } // namespace ppapi
{ "content_hash": "a6b1464310887f27a8cc0c92fa2bb0ba", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 78, "avg_line_length": 28.044642857142858, "alnum_prop": 0.6876790830945558, "repo_name": "paul99/clank", "id": "8933d12e2c10705640b1534e08ea3ac40fe2b481", "size": "3466", "binary": false, "copies": "4", "ref": "refs/heads/chrome-18.0.1025.469", "path": "ppapi/thunk/ppb_graphics_3d_trusted_thunk.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "56689" }, { "name": "C", "bytes": "8707669" }, { "name": "C++", "bytes": "89569069" }, { "name": "Go", "bytes": "10440" }, { "name": "Java", "bytes": "1201391" }, { "name": "JavaScript", "bytes": "5587454" }, { "name": "Lua", "bytes": "13641" }, { "name": "Objective-C", "bytes": "4568468" }, { "name": "PHP", "bytes": "11278" }, { "name": "Perl", "bytes": "51521" }, { "name": "Python", "bytes": "2615443" }, { "name": "R", "bytes": "262" }, { "name": "Ruby", "bytes": "107" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "588836" } ], "symlink_target": "" }
package fr.hmil.roshttp.body import java.nio.ByteBuffer import fr.hmil.roshttp.CrossPlatformUtils /** An urlencoded HTTP body. * * <b>Usage:</b> urlencoded bodies are best suited for simple key/value maps of strings. For more * structured data, use [[JSONBody]]. For binary data, use [[ByteBufferBody]] or [[MultiPartBody]]. * * URLEncoded bodies are associated with the mime type "application/x-www-form-urlencoded" * and look like query string parameters (eg. key=value&key2=value2 ). * * @param values A map of key/value pairs to send with the request. */ class URLEncodedBody private(values: Map[String, String]) extends BulkBodyPart { override def contentType: String = s"application/x-www-form-urlencoded" override def contentData: ByteBuffer = ByteBuffer.wrap( values.map({case (name, part) => CrossPlatformUtils.encodeURIComponent(name) + "=" + CrossPlatformUtils.encodeURIComponent(part) }).mkString("&").getBytes("utf-8") ) } object URLEncodedBody { def apply(values: (String, String)*): URLEncodedBody = new URLEncodedBody(Map(values: _*)) }
{ "content_hash": "c0a0701aaa469e78b2539ed097eac3e4", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 100, "avg_line_length": 34.71875, "alnum_prop": 0.7191719171917191, "repo_name": "hmil/RosHTTP", "id": "b5d950bdb80545fda38f9ae39a8469b1a88e598d", "size": "1111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shared/src/main/scala/fr/hmil/roshttp/body/URLEncodedBody.scala", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "6066" }, { "name": "Scala", "bytes": "125541" }, { "name": "Shell", "bytes": "1816" } ], "symlink_target": "" }
package Maximus::Role::Form::Account::Username; use HTML::FormHandler::Moose::Role; has_field 'username' => ( type => '+Maximus::FormField::AlNum', label => 'Username', required => 1, required_message => 'You must enter a username', minlength => 3, maxlength => 25, css_class => 'required validate-alphanum minLength:3 maxLength:25', ); no HTML::FormHandler::Moose::Role; =head1 NAME Maximus::Role::Form::Account::Username - Username field =head1 DESCRIPTION This module provides a default Username field for a L<HTML::FormHandler> account form. =head1 AUTHOR Christiaan Kras =head1 LICENSE Copyright (c) 2010-2013 Christiaan Kras Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =cut 1;
{ "content_hash": "83f9002c5816e96eae6337c64dec057f", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 78, "avg_line_length": 33.113207547169814, "alnum_prop": 0.7407407407407407, "repo_name": "maximos/maximus-web", "id": "f216065de7e2b57783bc9a282b32bd75941bcb00", "size": "1755", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lib/Maximus/Role/Form/Account/Username.pm", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "56" }, { "name": "BlitzMax", "bytes": "941" }, { "name": "CSS", "bytes": "15842" }, { "name": "CoffeeScript", "bytes": "4347" }, { "name": "JavaScript", "bytes": "1065" }, { "name": "Perl", "bytes": "298889" }, { "name": "Puppet", "bytes": "5380" }, { "name": "Shell", "bytes": "1217" } ], "symlink_target": "" }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Statistics; using System; using System.Collections.Generic; using osu.Framework.Development; using osu.Framework.Graphics.OpenGL; using osu.Framework.Platform; using osuTK; using osuTK.Graphics; namespace osu.Framework.Threading { public class DrawThread : GameThread { private readonly GameHost host; public DrawThread(Action onNewFrame, GameHost host) : base(onNewFrame, "Draw") { this.host = host; } public override bool IsCurrent => ThreadSafety.IsDrawThread; protected sealed override void OnInitialize() { var window = host.Window; if (window != null) { window.MakeCurrent(); GLWrapper.Initialize(host); GLWrapper.Reset(new Vector2(window.ClientSize.Width, window.ClientSize.Height)); } } internal sealed override void MakeCurrent() { base.MakeCurrent(); ThreadSafety.IsDrawThread = true; // Seems to be required on some drivers as the context is lost from the draw thread. host.Window?.MakeCurrent(); } protected sealed override void Cleanup() { base.Cleanup(); // specifically for mobile platforms so SDL does not need to be considered yet if (GraphicsContext.CurrentContext != null) GraphicsContext.CurrentContext.MakeCurrent(null); } internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[] { StatisticsCounterType.VBufBinds, StatisticsCounterType.VBufOverflow, StatisticsCounterType.TextureBinds, StatisticsCounterType.FBORedraw, StatisticsCounterType.DrawCalls, StatisticsCounterType.ShaderBinds, StatisticsCounterType.VerticesDraw, StatisticsCounterType.VerticesUpl, StatisticsCounterType.Pixels, }; } }
{ "content_hash": "7c501a989f53791db2fb10af3610ecea", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 96, "avg_line_length": 30.555555555555557, "alnum_prop": 0.6281818181818182, "repo_name": "EVAST9919/osu-framework", "id": "0f3bd9afe49fbdb72c1ef736ff91746a94557443", "size": "2202", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "osu.Framework/Threading/DrawThread.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6094" }, { "name": "C#", "bytes": "4855469" }, { "name": "C++", "bytes": "1770" }, { "name": "GLSL", "bytes": "5397" }, { "name": "PowerShell", "bytes": "924" }, { "name": "Shell", "bytes": "406" } ], "symlink_target": "" }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _class, _temp; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _rcTooltip = require('rc-tooltip'); var _rcTooltip2 = _interopRequireDefault(_rcTooltip); var _placements = require('../popover/placements'); var _placements2 = _interopRequireDefault(_placements); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } var Tooltip = (_temp = _class = function (_React$Component) { _inherits(Tooltip, _React$Component); function Tooltip(props) { _classCallCheck(this, Tooltip); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this.onVisibleChange = function (visible) { _this.setState({ visible: visible }); _this.props.onVisibleChange(visible); }; _this.onPopupAlign = function (domNode, align) { var placements = _this.getPlacements(); // 当前返回的位置 var placement = Object.keys(placements).filter(function (key) { return placements[key].points[0] === align.points[0] && placements[key].points[1] === align.points[1]; })[0]; if (!placement) { return; } // 根据当前坐标设置动画点 var rect = domNode.getBoundingClientRect(); var transformOrigin = { top: '50%', left: '50%' }; if (placement.indexOf('top') >= 0 || placement.indexOf('Bottom') >= 0) { transformOrigin.top = rect.height - align.offset[1] + 'px'; } else if (placement.indexOf('Top') >= 0 || placement.indexOf('bottom') >= 0) { transformOrigin.top = -align.offset[1] + 'px'; } if (placement.indexOf('left') >= 0 || placement.indexOf('Right') >= 0) { transformOrigin.left = rect.width - align.offset[0] + 'px'; } else if (placement.indexOf('right') >= 0 || placement.indexOf('Left') >= 0) { transformOrigin.left = -align.offset[0] + 'px'; } domNode.style.transformOrigin = transformOrigin.left + ' ' + transformOrigin.top; }; _this.state = { visible: false }; return _this; } Tooltip.prototype.getPopupDomNode = function getPopupDomNode() { return this.refs.tooltip.getPopupDomNode(); }; Tooltip.prototype.getPlacements = function getPlacements() { var _props = this.props, builtinPlacements = _props.builtinPlacements, arrowPointAtCenter = _props.arrowPointAtCenter; return builtinPlacements || (0, _placements2["default"])({ arrowPointAtCenter: arrowPointAtCenter, verticalArrowShift: 8 }); }; // 动态设置动画点 Tooltip.prototype.render = function render() { var _props2 = this.props, prefixCls = _props2.prefixCls, title = _props2.title, overlay = _props2.overlay, children = _props2.children; // Hide tooltip when there is no title var visible = this.state.visible; if (!title && !overlay) { visible = false; } if ('visible' in this.props) { visible = this.props.visible; } var openClassName = this.props.openClassName || prefixCls + '-open'; var childrenCls = children && children.props && children.props.className ? children.props.className + ' ' + openClassName : openClassName; return _react2["default"].createElement( _rcTooltip2["default"], _extends({ overlay: title, visible: visible, onPopupAlign: this.onPopupAlign, ref: 'tooltip' }, this.props, { builtinPlacements: this.getPlacements(), onVisibleChange: this.onVisibleChange }), visible ? (0, _react.cloneElement)(children, { className: childrenCls }) : children ); }; return Tooltip; }(_react2["default"].Component), _class.defaultProps = { prefixCls: 'ant-tooltip', placement: 'top', transitionName: 'zoom-big', mouseEnterDelay: 0.1, mouseLeaveDelay: 0.1, onVisibleChange: function onVisibleChange() {}, arrowPointAtCenter: false }, _temp); exports["default"] = Tooltip; module.exports = exports['default'];
{ "content_hash": "8a4e7af66222ab68d09788f0b5e26e18", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 494, "avg_line_length": 38.895833333333336, "alnum_prop": 0.654168898410998, "repo_name": "geng890518/editor-ui", "id": "b98fac46e568b9652a95bd90ac15d580e40d3787", "size": "5651", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/antd/lib/tooltip/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "127022" }, { "name": "JavaScript", "bytes": "260497" } ], "symlink_target": "" }
/* eslint-disable no-console */ "use strict" import { StoreUsingServer } from "./StoreUsingServer.js" import { HashUtils } from "./HashUtils.js" import { FileUtils } from "./FileUtils.js" // defines m import "./vendor/mithril.js" let streamName = "{\"chatRoom\": \"test\"}" let userID = localStorage.getItem("userID") || "anonymous" let newMessageJSONText = "" const messages = [] // filterText is split into tags by spaces and used to filter by a logical "and" to include displayed items let filterText = "" // hideText is split into tags by spaces and used to filter by a logical "OR" to hide displayed items let hideText = "" let messagesDiv = null let showEntryArea = false function startup() { streamName = HashUtils.getHashParams()["stream"] || streamName window.onhashchange = () => updateStreamNameFromHash() updateHashForStreamName() } function updateTitleForStreamName() { document.title = streamName.replace(/[{}":]/g, "") + " -- Twirlip7 Monitor" } function updateStreamNameFromHash() { const hashParams = HashUtils.getHashParams() console.log("updateStreamNameFromHash", hashParams) const newStreamName = hashParams["stream"] if (newStreamName !== streamName) { streamName = newStreamName resetMessagesForStreamNameChange() updateTitleForStreamName() if (!isTextValidJSON(newStreamName)) { console.log("invalid JSON stream name in hash", newStreamName) return } backend.configure(JSON.parse(streamName)) } } function updateHashForStreamName() { const hashParams = HashUtils.getHashParams() hashParams["stream"] = streamName HashUtils.setHashParams(hashParams) updateTitleForStreamName() } function streamNameChange(event) { resetMessagesForStreamNameChange() streamName = event.target.value updateHashForStreamName() if (!isTextValidJSON(streamName)) { console.log("invalid JSON stream name in hash", streamName) return } backend.configure(JSON.parse(streamName)) } function resetMessagesForStreamNameChange() { messages.splice(0) } function userIDChange(event) { userID = event.target.value backend.configure(undefined, userID) localStorage.setItem("userID", userID) } function newMessageJSONTextChange(event) { newMessageJSONText = event.target.value } function sendStreamMessage() { const newMessage = JSON.parse(newMessageJSONText) sendMessage(newMessage) // newMessageJSONText = "" if (!hasFilterText(newMessage)) { setTimeout(() => alert("The message you just added is currently\nnot displayed due to show/hide filtering.")) /* filterText = "" hideText = " */ } setTimeout(() => { // Scroll to bottom always when sending -- but defer it just in case was filtering if (messagesDiv) { messagesDiv.scrollTop = messagesDiv.scrollHeight } }, 0) } function sendMessage(message) { // Call addItem after a delay to give socket.io a chance to reconnect // as socket.io will timeout if a prompt (or alert?) is up for very long setTimeout(() => backend.addItem(message), 10) } function sendIfCtrlEnter(event, text, callbackToSendMessage) { if (isTextValidJSONObject(newMessageJSONText) && text.trim() && event.key === "Enter" && event.ctrlKey ) { callbackToSendMessage() return false } event.redraw = false return true } function textAreaKeyDown(event) { return sendIfCtrlEnter(event, newMessageJSONText, sendStreamMessage) } function hasFilterText(message) { const messageText = JSON.stringify(message) if ((filterText || hideText)) { let lowerCaseText = messageText if (filterText) { const tags = filterText.split(" ") for (let tag of tags) { if (tag && !lowerCaseText.includes(tag.toLowerCase())) return false } } if (hideText) { const tags = hideText.split(" ") for (let tag of tags) { if (tag && lowerCaseText.includes(tag.toLowerCase())) return false } } } return true } function isTextValidJSON(text) { if (!text) return false try { JSON.parse(text) return true } catch(e) { return false } } function isTextValidJSONObject(text) { if (text[0] !== "{") return false return isTextValidJSON(text) } function exportStreamAsJSONClicked() { const messagesToExport = [] messages.forEach(function (message, index) { if (!hasFilterText(message)) return messagesToExport.push(message) }) FileUtils.saveToFile(streamName + " " + new Date().toISOString(), JSON.stringify(messagesToExport, null, 4), ".json") } function importStreamFromJSONClicked() { FileUtils.loadFromFile(false, (filename, contents, bytes) => { console.log("JSON filename, contents", filename, bytes, contents) for (let transaction of JSON.parse(contents)) { sendMessage(transaction) } }) } const TwirlipMonitor = { view: function () { return m("div.pa2.overflow-hidden.flex.flex-column.h-100.w-100", [ // m("h4.tc", "Twirlip Monitor"), m("div.mb3", m("span.dib.tr", "Stream:"), m("input.ml2" + (!isTextValidJSON(streamName) ? ".orange" : ""), {style: "width: 30rem", value: streamName, onchange: streamNameChange}), m("span.dib.tr.ml2", "User:"), m("input.w4.ml2", {value: userID, onchange: userIDChange, title: "Your user id or handle"}), m("div.dib", m("span.ml2" + (filterText ? ".green" : ""), "Show:"), m("input.ml2" + (filterText ? ".green" : ""), {value: filterText, oninput: (event) => { filterText = event.target.value; scrollToBottomLater() }, title: "Only display messages with all entered words"}), m("span.ml2" + (hideText ? ".orange" : ""), "Hide:"), m("input.ml2" + (hideText ? ".orange" : ""), {value: hideText, oninput: (event) => { hideText = event.target.value; scrollToBottomLater() }, title: "Hide messages with any entered words"}), ), ), m("div.overflow-auto.flex-auto", { oncreate: (vnode) => { messagesDiv = (vnode.dom) }, }, messages.map(function (message, index) { if (!hasFilterText(message)) return [] return m("div", [ m("hr.b--light-gray"), m("div", "#" + index), m("pre", JSON.stringify(message, null, 4)) ]) }) ), m("div", m("span.ml2", { title: "Show entry area" }, m("input[type=checkbox].ma1", { checked: showEntryArea, onchange: (event) => showEntryArea = event.target.checked }), "entry area" ), showEntryArea && m("div.dib", m("button.ml2.mt2", {onclick: sendStreamMessage, disabled: !isTextValidJSONObject(newMessageJSONText)}, "Send (ctrl-enter)"), m("span.ml2", "Enter a valid JSON object {...} below:"), m("button.ml2.mt2", {onclick: exportStreamAsJSONClicked, title: "Export stream as JSON"}, "Export JSON..."), m("button.ml2.mt2", {onclick: importStreamFromJSONClicked, title: "Import stream from JSON"}, "Import JSON..."), ) ), showEntryArea && m("div.pb1.f4", m("textarea.h4.w-80.ma1.ml3", {value: newMessageJSONText, oninput: newMessageJSONTextChange, onkeydown: textAreaKeyDown}), ) ]) } } let isLoaded = false function scrollToBottomLater() { setTimeout(() => { // Scroll to bottom when loaded everything if (messagesDiv) messagesDiv.scrollTop = messagesDiv.scrollHeight + 10000 }, 0) } const streamNameResponder = { onLoaded: () => { isLoaded = true console.log("onLoaded") scrollToBottomLater() }, onAddItem: (item) => { // console.log("onAddItem", item) messages.push(item) const itemIsNotFiltered = hasFilterText(item) if (isLoaded) { // Only scroll if scroll is already near bottom and not filtering to avoid messing up browsing previous items if (itemIsNotFiltered && messagesDiv && (item.userID === userID || messagesDiv.scrollTop >= (messagesDiv.scrollHeight - messagesDiv.clientHeight - 300))) { setTimeout(() => { // Add some because height may not include new item messagesDiv.scrollTop = messagesDiv.scrollHeight + 10000 }, 100) } } } } startup() let initialObject = {} try { initialObject = JSON.parse(streamName) } catch (e) { console.log("not valid JSON for hash", streamName) } const backend = StoreUsingServer(m.redraw, initialObject, userID) backend.connect(streamNameResponder) try { backend.setup() } catch(e) { alert("This Monitor app requires a backend server supporting socket.io (i.e. won't work correctly on rawgit)") } m.mount(document.body, TwirlipMonitor)
{ "content_hash": "0fdf441f7b1884e5adfe407841257fc7", "timestamp": "", "source": "github", "line_count": 281, "max_line_length": 222, "avg_line_length": 33.76512455516014, "alnum_prop": 0.6011804384485666, "repo_name": "pdfernhout/Twirlip7", "id": "e242708a303570f1b65fc2f473655a1014f162bf", "size": "9488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ui/monitor.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "12045" }, { "name": "JavaScript", "bytes": "466648" }, { "name": "Shell", "bytes": "1559" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- Meta, title, CSS, favicons, etc. --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>DataTables | Inventory</title> <!-- Bootstrap --> <link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet"> <!-- NProgress --> <link href="../vendors/nprogress/nprogress.css" rel="stylesheet"> <!-- iCheck --> <link href="../vendors/iCheck/skins/flat/green.css" rel="stylesheet"> <!-- Datatables --> <link href="../vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet"> <link href="../vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" rel="stylesheet"> <link href="../vendors/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css" rel="stylesheet"> <link href="../vendors/datatables.net-responsive-bs/css/responsive.bootstrap.min.css" rel="stylesheet"> <link href="../vendors/datatables.net-scroller-bs/css/scroller.bootstrap.min.css" rel="stylesheet"> <!-- Custom Theme Style --> <link href="../build/css/custom.min.css" rel="stylesheet"> </head> <body class="nav-md"> <div class="container body"> <div class="main_container"> <div class="col-md-3 left_col"> <div class="left_col scroll-view"> <div class="navbar nav_title" style="border: 0;"> <a href="index.html" class="site_title"><i class="fa fa-paw"></i> <span>Data Inventory!</span></a> </div> <div class="clearfix"></div> <!-- menu profile quick info --> <div class="profile clearfix"> <div class="profile_pic"> <img src="images/img.jpg" alt="..." class="img-circle profile_img"> </div> <div class="profile_info"> <span>Welcome,</span> <h2>John Doe</h2> </div> </div> <!-- /menu profile quick info --> <br /> <!-- sidebar menu --> <div id="sidebar-menu" class="main_menu_side hidden-print main_menu"> <div class="menu_section"> <h3>General</h3> <ul class="nav side-menu"> <li><a href="tables_dynamic.html"><i class="fa fa-table"></i> NMS </a> <li><a href="tables_dynamic2.html"><i class="fa fa-table"></i> Perangkat </a></li> </li> </ul> </div> </div> <!-- /sidebar menu --> <!-- /menu footer buttons --> <div class="sidebar-footer hidden-small"> <a data-toggle="tooltip" data-placement="top" title="Settings"> <span class="glyphicon glyphicon-cog" aria-hidden="true"></span> </a> <a data-toggle="tooltip" data-placement="top" title="FullScreen"> <span class="glyphicon glyphicon-fullscreen" aria-hidden="true"></span> </a> <a data-toggle="tooltip" data-placement="top" title="Lock"> <span class="glyphicon glyphicon-eye-close" aria-hidden="true"></span> </a> <a data-toggle="tooltip" data-placement="top" title="Logout"> <span class="glyphicon glyphicon-off" aria-hidden="true"></span> </a> </div> <!-- /menu footer buttons --> </div> </div> <!-- top navigation --> <div class="top_nav"> <div class="nav_menu"> <nav> <div class="nav toggle"> <a id="menu_toggle"><i class="fa fa-bars"></i></a> </div> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <img src="images/img.jpg" alt="">John Doe <span class=" fa fa-angle-down"></span> </a> <ul class="dropdown-menu dropdown-usermenu pull-right"> <li><a href="javascript:;"> Profile</a></li> <li> <a href="javascript:;"> <span class="badge bg-red pull-right">50%</span> <span>Settings</span> </a> </li> <li><a href="javascript:;">Help</a></li> <li><a href="login.html"><i class="fa fa-sign-out pull-right"></i> Log Out</a></li> </ul> </li> <li role="presentation" class="dropdown"> <a href="javascript:;" class="dropdown-toggle info-number" data-toggle="dropdown" aria-expanded="false"> <i class="fa fa-envelope-o"></i> <span class="badge bg-green">6</span> </a> <ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu"> <li> <a> <span class="image"><img src="images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <div class="text-center"> <a> <strong>See All Alerts</strong> <i class="fa fa-angle-right"></i> </a> </div> </li> </ul> </li> </ul> </nav> </div> </div> <!-- /top navigation --> <!-- page content --> <div class="right_col" role="main"> <div class=""> <div class="page-title"> <div class="title_left"> <h3>Users <small>Some examples to get you started</small></h3> </div> <div class="title_right"> <div class="col-md-5 col-sm-5 col-xs-12 form-group pull-right top_search"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search for..."> <span class="input-group-btn"> <button class="btn btn-default" type="button">Go!</button> </span> </div> </div> </div> </div> <div class="clearfix"></div> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="x_panel"> <div class="x_title"> <h2>Data Invetory NNCC ! <small>Users</small></h2> <ul class="nav navbar-right panel_toolbox"> <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a> </li> </ul> <div class="clearfix"></div> </div> <div class="x_content"> <p class="text-muted font-13 m-b-30"> The Buttons extension for DataTables provides a common set of options, API methods and styling to display buttons on a page that will interact with a DataTable. The core library provides the based framework upon which plug-ins can built. </p> <table id="datatable-buttons" class="table table-striped table-bordered"> <thead> <tr> <th>Node-A</th> <th>Node-B</th> <th>Kap</th> <th>Node-A</th> <th>Node-B</th> <th>Sistra</th> <th>Edit Data</th> </tr> </thead> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$320,800</td> <td> <a href="#" class="btn btn-info btn-xs"><i class="fa fa-pencil"></i> Edit </a> <a href="#" class="btn btn-danger btn-xs"><i class="fa fa-trash-o"></i> Delete </a> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> <td> <a href="#" class="btn btn-info btn-xs"><i class="fa fa-pencil"></i> Edit </a> <a href="#" class="btn btn-danger btn-xs"><i class="fa fa-trash-o"></i> Delete </a> </td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>66</td> <td>2009/01/12</td> <td>$86,000</td> <td> <a href="#" class="btn btn-info btn-xs"><i class="fa fa-pencil"></i> Edit </a> <a href="#" class="btn btn-danger btn-xs"><i class="fa fa-trash-o"></i> Delete </a> </td> </tr> </tbody> </table> </div> <td> <a href="form_validation2.html"><button type="submit" class="btn btn-primary">Insert Single Data</button></a> </td> <td> <a href="form_upload2.html"><button type="submit" class="btn btn-success">Insert Multiple Data</button></a> </td> </div> </div> <!-- /page content --> <!-- footer content --> <footer> <div class="pull-right"> Gentelella - Bootstrap Admin Template by <a href="https://colorlib.com">Colorlib</a> </div> <div class="clearfix"></div> </footer> <!-- /footer content --> </div> </div> <!-- jQuery --> <script src="../vendors/jquery/dist/jquery.min.js"></script> <!-- Bootstrap --> <script src="../vendors/bootstrap/dist/js/bootstrap.min.js"></script> <!-- FastClick --> <script src="../vendors/fastclick/lib/fastclick.js"></script> <!-- NProgress --> <script src="../vendors/nprogress/nprogress.js"></script> <!-- iCheck --> <script src="../vendors/iCheck/icheck.min.js"></script> <!-- Datatables --> <script src="../vendors/datatables.net/js/jquery.dataTables.min.js"></script> <script src="../vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script> <script src="../vendors/datatables.net-buttons/js/dataTables.buttons.min.js"></script> <script src="../vendors/datatables.net-buttons-bs/js/buttons.bootstrap.min.js"></script> <script src="../vendors/datatables.net-buttons/js/buttons.flash.min.js"></script> <script src="../vendors/datatables.net-buttons/js/buttons.html5.min.js"></script> <script src="../vendors/datatables.net-buttons/js/buttons.print.min.js"></script> <script src="../vendors/datatables.net-fixedheader/js/dataTables.fixedHeader.min.js"></script> <script src="../vendors/datatables.net-keytable/js/dataTables.keyTable.min.js"></script> <script src="../vendors/datatables.net-responsive/js/dataTables.responsive.min.js"></script> <script src="../vendors/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script> <script src="../vendors/datatables.net-scroller/js/datatables.scroller.min.js"></script> <script src="../vendors/jszip/dist/jszip.min.js"></script> <script src="../vendors/pdfmake/build/pdfmake.min.js"></script> <script src="../vendors/pdfmake/build/vfs_fonts.js"></script> <!-- Custom Theme Scripts --> <script src="../build/js/custom.min.js"></script> <!-- Datatables --> <script> $(document).ready(function() { var handleDataTableButtons = function() { if ($("#datatable-buttons").length) { $("#datatable-buttons").DataTable({ dom: "Bfrtip", buttons: [ { extend: "copy", className: "btn-sm" }, { extend: "csv", className: "btn-sm" }, { extend: "excel", className: "btn-sm" }, { extend: "pdfHtml5", className: "btn-sm" }, { extend: "print", className: "btn-sm" }, ], responsive: true }); } }; TableManageButtons = function() { "use strict"; return { init: function() { handleDataTableButtons(); } }; }(); $('#datatable').dataTable(); $('#datatable-keytable').DataTable({ keys: true }); $('#datatable-responsive').DataTable(); $('#datatable-scroller').DataTable({ ajax: "js/datatables/json/scroller-demo.json", deferRender: true, scrollY: 380, scrollCollapse: true, scroller: true }); $('#datatable-fixed-header').DataTable({ fixedHeader: true }); var $datatable = $('#datatable-checkbox'); $datatable.dataTable({ 'order': [[ 1, 'asc' ]], 'columnDefs': [ { orderable: false, targets: [0] } ] }); $datatable.on('draw.dt', function() { $('input').iCheck({ checkboxClass: 'icheckbox_flat-green' }); }); TableManageButtons.init(); }); </script> <!-- /Datatables --> </body> </html>
{ "content_hash": "e8667dd3325b4df0426fac28d475241a", "timestamp": "", "source": "github", "line_count": 410, "max_line_length": 259, "avg_line_length": 41.12682926829268, "alnum_prop": 0.44170323805005335, "repo_name": "cicilestaris/PLA_project", "id": "41f9b5f918d07a86a2c5d7fb50f8e1963d274b4b", "size": "16862", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/admin/html/tables_dynamic2.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "317159" }, { "name": "HTML", "bytes": "11427641" }, { "name": "JavaScript", "bytes": "183508" }, { "name": "PHP", "bytes": "2225799" } ], "symlink_target": "" }
layout: post title: "April 11, 2017 dplyr Pre-Class" data: "04/11/2017" tags: [R, dplyr] --- ## Reading For your Reading: - [The Split Apply Combine Method](https://www.jstatsoft.org/article/view/v040i01) - [Tidy Data](http://statseducation.com/Introduction-to-R/modules/tidy%20data/tidy-data/) ## Videos 1. Complete the DataCamp assignment you have received. 2. Make sure you have read the [Tidy Data Tutorial](http://statseducation.com/Introduction-to-R/modules/tidy%20data/tidy-data/) ## Make Up Classes - The snow day really affected our class schedule. - On top of this I have been called to a meeting in Boston on April 25, 2017 - I am asking you to sign up for 2 extra classes - This will cover the snow day we missed as well as missing class on April 25. - This means that the first week of May we will ahve 2 classes. [Please Fill In One class In the last week for April and 1st Week of May](https://docs.google.com/spreadsheets/d/1x-IDRAGtXW4XN1B4EtZiiWFSV3ff8IBKyery_A3zGjE/edit#gid=0)
{ "content_hash": "68ae3d105e0154cf208cb4776f498ade", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 169, "avg_line_length": 31.84375, "alnum_prop": 0.7428851815505397, "repo_name": "php2560/preclass", "id": "f1f0d41b4b092840d1f7f0082c53779184e80e01", "size": "1023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2017-04-11-pre-class.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "24235" }, { "name": "HTML", "bytes": "746294" }, { "name": "JavaScript", "bytes": "4356" } ], "symlink_target": "" }
(function() { 'use strict'; angular .module('webHipsterApp') .directive('hasAuthority', hasAuthority); hasAuthority.$inject = ['Principal']; function hasAuthority(Principal) { var directive = { restrict: 'A', link: linkFunc }; return directive; function linkFunc(scope, element, attrs) { var authority = attrs.hasAuthority.replace(/\s+/g, ''); var setVisible = function () { element.removeClass('hidden'); }, setHidden = function () { element.addClass('hidden'); }, defineVisibility = function (reset) { if (reset) { setVisible(); } Principal.hasAuthority(authority) .then(function (result) { if (result) { setVisible(); } else { setHidden(); } }); }; if (authority.length > 0) { defineVisibility(true); scope.$watch(function() { return Principal.isAuthenticated(); }, function() { defineVisibility(true); }); } } } })();
{ "content_hash": "ca879e8ce8d912b453a669722ebb3778", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 67, "avg_line_length": 27.48148148148148, "alnum_prop": 0.3861185983827493, "repo_name": "rafaelmss/WebHipster", "id": "9ab9835a4966d7cd58a8e637c05dd066e19b72aa", "size": "1484", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/webapp/app/services/auth/has-authority.directive.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "9760" }, { "name": "HTML", "bytes": "175415" }, { "name": "Java", "bytes": "357100" }, { "name": "JavaScript", "bytes": "242593" }, { "name": "Scala", "bytes": "13675" }, { "name": "Shell", "bytes": "7058" } ], "symlink_target": "" }
package renderer.scene.actors; import renderer.infrastructure.math.Vector3; import renderer.infrastructure.pipeline.model.BuilderInterface; /** * A data structure to store WaveFront .mtl file data. This class is not an original work, but is instead a * derivative work from a parser written by * <a href="https://github.com/seanrowens/oObjLoader">Sean R. Owens</a>. * @author Sean R. Owens * */ public class Material { public String name; public Vector3 ka = Vector3.ZERO; public Vector3 kd = Vector3.ZERO; public Vector3 ks = Vector3.ZERO; public Vector3 tf = Vector3.ZERO; public int illumModel = 0; public boolean dHalo = false; public double dFactor = 0.0; public double nsExponent = 0.0; public double sharpnessValue = 0.0; public double niOpticalDensity = 0.0; public String mapKaFilename = null; public String mapKdFilename = null; public String mapKsFilename = null; public String mapNsFilename = null; public String mapDFilename = null; public String decalFilename = null; public String dispFilename = null; public String bumpFilename = null; public int reflType = BuilderInterface.MTL_REFL_TYPE_UNKNOWN; public String reflFilename = null; public Material(String name) { this.name = name; } }
{ "content_hash": "9e677895448ee0ecc7e9c639b39276ce", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 107, "avg_line_length": 30.26829268292683, "alnum_prop": 0.7518130539887188, "repo_name": "DonIsaac/Accelerated-Raytracer", "id": "aad2c5e11bb5f9cd7eb64fcaa1f90676e6d31897", "size": "1241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/renderer/scene/actors/Material.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "408" }, { "name": "Java", "bytes": "111095" } ], "symlink_target": "" }
// Copyright 2020 The Outline Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Directly import @sentry/electron main process code. // See: https://docs.sentry.io/platforms/javascript/guides/electron/#webpack-configuration import * as sentry from '@sentry/electron/main'; import {app, BrowserWindow, ipcMain, Menu, MenuItemConstructorOptions, nativeImage, shell, Tray} from 'electron'; import {autoUpdater} from 'electron-updater'; import * as os from 'os'; import * as path from 'path'; import * as process from 'process'; import * as url from 'url'; import autoLaunch = require('auto-launch'); // tslint:disable-line import * as connectivity from './connectivity'; import * as errors from '../www/model/errors'; import {ShadowsocksSessionConfig} from '../www/app/tunnel'; import {TunnelStatus} from '../www/app/tunnel'; import {GoVpnTunnel} from './go_vpn_tunnel'; import {installRoutingServices, RoutingDaemon} from './routing_service'; import {TunnelStore, SerializableTunnel} from './tunnel_store'; import {VpnTunnel} from './vpn_tunnel'; // TODO: can we define these macros in other .d.ts files with default values? // Build-time macros injected by webpack's DefinePlugin: // - SENTRY_DSN is either undefined or a url string // - APP_VERSION should always be a string declare const SENTRY_DSN: string | undefined; declare const APP_VERSION: string; // Run-time environment variables: const debugMode = process.env.OUTLINE_DEBUG === 'true'; const isLinux = os.platform() === 'linux'; // Used for the auto-connect feature. There will be a tunnel in store // if the user was connected at shutdown. const tunnelStore = new TunnelStore(app.getPath('userData')); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow: Electron.BrowserWindow | null; let tray: Tray; let isAppQuitting = false; // Default to English strings in case we fail to retrieve them from the renderer process. let localizedStrings: {[key: string]: string} = { 'tray-open-window': 'Open', 'connected-server-state': 'Connected', 'disconnected-server-state': 'Disconnected', quit: 'Quit', }; const TRAY_ICON_IMAGES = { connected: createTrayIconImage('connected.png'), disconnected: createTrayIconImage('disconnected.png'), }; const enum Options { AUTOSTART = '--autostart', } const REACHABILITY_TIMEOUT_MS = 10000; let currentTunnel: VpnTunnel | undefined; /** * Sentry must be initialized before electron app is ready: * - https://github.com/getsentry/sentry-electron/blob/3.0.7/src/main/ipc.ts#L70 */ function setupSentry(): void { // Use 'typeof(v)' instead of '!!v' here to prevent ReferenceError if (typeof SENTRY_DSN !== 'undefined' && typeof APP_VERSION !== 'undefined') { // This config makes console (log/info/warn/error - no debug!) output go to breadcrumbs. sentry.init({dsn: SENTRY_DSN, release: APP_VERSION, maxBreadcrumbs: 100}); } } function setupMenu(): void { if (debugMode) { Menu.setApplicationMenu( Menu.buildFromTemplate([ { label: 'Developer', submenu: Menu.buildFromTemplate([{role: 'reload'}, {role: 'forceReload'}, {role: 'toggleDevTools'}]), }, ]) ); } else { // Hide standard menu. Menu.setApplicationMenu(null); } } function setupTray(): void { tray = new Tray(TRAY_ICON_IMAGES.disconnected); // On Linux, the click event is never fired: https://github.com/electron/electron/issues/14941 tray.on('click', () => { mainWindow?.show(); }); tray.setToolTip('Outline'); updateTray(TunnelStatus.DISCONNECTED); } function setupWindow(): void { // Create the browser window. mainWindow = new BrowserWindow({ width: 360, height: 640, resizable: false, webPreferences: { nodeIntegration: false, contextIsolation: true, preload: path.join(__dirname, 'preload.js'), }, }); // Icon is not shown in Ubuntu Dock. It is a recurrent issue happened in Linux: // - https://github.com/electron-userland/electron-builder/issues/2269 // A workaround is to forcibly set the icon of the main window. // // This is a workaround because the icon is fixed to 64x64, which might look blurry // on higher dpi (>= 200%) settings. Setting it to a higher resolution icon (e.g., 128x128) // does not work either because Ubuntu's image resize algorithm is pretty bad, the icon // looks too sharp in a regular dpi (100%) setting. // // The ideal solution would be: either electron-builder supports the app icon; or we add // dpi-aware features to this app. if (isLinux) { mainWindow.setIcon(path.join(app.getAppPath(), 'build', 'icons', 'png', '64x64.png')); } const pathToIndexHtml = path.join(app.getAppPath(), 'www', 'index_electron.html'); const webAppUrl = new url.URL(`file://${pathToIndexHtml}`); // Debug mode, etc. const queryParams = new url.URLSearchParams(); if (debugMode) { queryParams.set('debug', 'true'); } queryParams.set('appName', app.getName()); webAppUrl.search = queryParams.toString(); const webAppUrlAsString = webAppUrl.toString(); console.info(`loading web app from ${webAppUrlAsString}`); mainWindow.loadURL(webAppUrlAsString); mainWindow.on('close', (event: Event) => { if (isAppQuitting) { // Actually close the window if we are quitting. return; } // Hide instead of close so we don't need to create a new one. event.preventDefault(); mainWindow.hide(); }); if (os.platform() === 'win32') { // On Windows we hide the app from the taskbar. mainWindow.on('minimize', (event: Event) => { event.preventDefault(); mainWindow.hide(); }); } // TODO: is this the most appropriate event? mainWindow.webContents.on('did-finish-load', () => { // TODO: refactor channel name and namespace to a constant mainWindow.webContents.send('outline-ipc-localization-request', Object.keys(localizedStrings)); interceptShadowsocksLink(process.argv); }); // The client is a single page app - loading any other page means the // user clicked on one of the Privacy, Terms, etc., links. These should // open in the user's browser. mainWindow.webContents.on('will-navigate', (event: Event, url: string) => { try { const parsed: URL = new URL(url); if (parsed.protocol === 'http:' || parsed.protocol === 'https:') { shell.openExternal(url); } else { console.warn(`Refusing to open URL with protocol "${parsed.protocol}"`); } } catch (e) { console.warn('Could not parse URL: ' + url); } event.preventDefault(); }); } function updateTray(status: TunnelStatus) { const isConnected = status === TunnelStatus.CONNECTED; tray.setImage(isConnected ? TRAY_ICON_IMAGES.connected : TRAY_ICON_IMAGES.disconnected); // Retrieve localized strings, falling back to the pre-populated English default. const statusString = isConnected ? localizedStrings['connected-server-state'] : localizedStrings['disconnected-server-state']; let menuTemplate = [ {label: statusString, enabled: false}, {type: 'separator'} as MenuItemConstructorOptions, {label: localizedStrings['quit'], click: quitApp}, ]; if (isLinux) { // Because the click event is never fired on Linux, we need an explicit open option. menuTemplate = [{label: localizedStrings['tray-open-window'], click: () => mainWindow.show()}, ...menuTemplate]; } tray.setContextMenu(Menu.buildFromTemplate(menuTemplate)); } function createTrayIconImage(imageName: string) { const image = nativeImage.createFromPath(path.join(app.getAppPath(), 'resources', 'tray', imageName)); if (image.isEmpty()) { throw new Error(`cannot find ${imageName} tray icon image`); } return image; } // Signals that the app is quitting and quits the app. This is necessary because we override the // window 'close' event to support minimizing to the system tray. async function quitApp() { isAppQuitting = true; await stopVpn(); app.quit(); } function interceptShadowsocksLink(argv: string[]) { if (argv.length > 1) { const protocols = ['ss://', 'ssconf://']; let url = argv[1]; for (const protocol of protocols) { if (url.startsWith(protocol)) { if (mainWindow) { // The system adds a trailing slash to the intercepted URL (before the fragment). // Remove it before sending to the UI. url = `${protocol}${url.substr(protocol.length).replace(/\//g, '')}`; // TODO: refactor channel name and namespace to a constant mainWindow.webContents.send('outline-ipc-add-server', url); } else { console.error('called with URL but mainWindow not open'); } } } } } // Set the app to launch at startup to connect automatically in case of a shutdown while // proxying. async function setupAutoLaunch(args: SerializableTunnel): Promise<void> { try { await tunnelStore.save(args); if (isLinux) { if (process.env.APPIMAGE) { const outlineAutoLauncher = new autoLaunch({ name: 'OutlineClient', path: process.env.APPIMAGE, }); outlineAutoLauncher.enable(); } } else { app.setLoginItemSettings({openAtLogin: true, args: [Options.AUTOSTART]}); } } catch (e) { console.error(`Failed to set up auto-launch: ${e.message}`); } } async function tearDownAutoLaunch() { try { if (isLinux) { const outlineAutoLauncher = new autoLaunch({ name: 'OutlineClient', }); outlineAutoLauncher.disable(); } else { app.setLoginItemSettings({openAtLogin: false}); } await tunnelStore.clear(); } catch (e) { console.error(`Failed to tear down auto-launch: ${e.message}`); } } // Factory function to create a VPNTunnel instance backed by a network statck // specified at build time. function createVpnTunnel(config: ShadowsocksSessionConfig, isAutoConnect: boolean): VpnTunnel { const routing = new RoutingDaemon(config.host || '', isAutoConnect); const tunnel = new GoVpnTunnel(routing, config); routing.onNetworkChange = tunnel.networkChanged.bind(tunnel); return tunnel; } // Invoked by both the start-proxying event handler and auto-connect. async function startVpn(config: ShadowsocksSessionConfig, id: string, isAutoConnect = false) { if (currentTunnel) { throw new Error('already connected'); } currentTunnel = createVpnTunnel(config, isAutoConnect); if (debugMode) { currentTunnel.enableDebugMode(); } currentTunnel.onceDisconnected.then(() => { console.log(`disconnected from ${id}`); currentTunnel = undefined; setUiTunnelStatus(TunnelStatus.DISCONNECTED, id); }); currentTunnel.onReconnecting(() => { console.log(`reconnecting to ${id}`); setUiTunnelStatus(TunnelStatus.RECONNECTING, id); }); currentTunnel.onReconnected(() => { console.log(`reconnected to ${id}`); setUiTunnelStatus(TunnelStatus.CONNECTED, id); }); // Don't check connectivity on boot: if the key was revoked or network connectivity is not ready, // we want the system to stay "connected" so that traffic doesn't leak. await currentTunnel.connect(!isAutoConnect); setUiTunnelStatus(TunnelStatus.CONNECTED, id); } // Invoked by both the stop-proxying event and quit handler. async function stopVpn() { if (!currentTunnel) { return; } currentTunnel.disconnect(); await tearDownAutoLaunch(); await currentTunnel.onceDisconnected; } function setUiTunnelStatus(status: TunnelStatus, tunnelId: string) { let statusString; switch (status) { case TunnelStatus.CONNECTED: statusString = 'connected'; break; case TunnelStatus.DISCONNECTED: statusString = 'disconnected'; break; case TunnelStatus.RECONNECTING: statusString = 'reconnecting'; break; default: console.error(`Cannot send unknown proxy status: ${status}`); return; } // TODO: refactor channel name and namespace to a constant const event = `outline-ipc-proxy-${statusString}-${tunnelId}`; if (mainWindow) { mainWindow.webContents.send(event); } else { console.warn(`received ${event} event but no mainWindow to notify`); } updateTray(status); } function checkForUpdates() { try { autoUpdater.checkForUpdates(); } catch (e) { console.error(`Failed to check for updates`, e); } } function main() { setupSentry(); if (!app.requestSingleInstanceLock()) { console.log('another instance is running - exiting'); app.quit(); } app.setAsDefaultProtocolClient('ss'); app.setAsDefaultProtocolClient('ssconf'); // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', async () => { // To clearly identify app restarts in Sentry. console.info('Outline is starting'); setupMenu(); setupTray(); // TODO(fortuna): Start the app with the window hidden on auto-start? setupWindow(); let tunnelAtShutdown: SerializableTunnel; try { tunnelAtShutdown = await tunnelStore.load(); } catch (e) { // No tunnel at shutdown, or failure - either way, no need to start. // TODO: Instead of quitting, how about creating the system tray icon? console.warn(`Could not load active tunnel: `, e); await tunnelStore.clear(); } if (tunnelAtShutdown) { console.info(`was connected at shutdown, reconnecting to ${tunnelAtShutdown.id}`); setUiTunnelStatus(TunnelStatus.RECONNECTING, tunnelAtShutdown.id); try { await startVpn(tunnelAtShutdown.config, tunnelAtShutdown.id, true); console.log(`reconnected to ${tunnelAtShutdown.id}`); } catch (e) { console.error(`could not reconnect: ${e.name} (${e.message})`); } } if (!debugMode) { checkForUpdates(); // Check every six hours setInterval(checkForUpdates, 6 * 60 * 60 * 1000); } }); app.on('second-instance', (event: Event, argv: string[]) => { interceptShadowsocksLink(argv); // Someone tried to run a second instance, we should focus our window. mainWindow?.show(); }); app.on('activate', () => { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. mainWindow?.show(); }); // This event fires whenever the app's window receives focus. app.on('browser-window-focus', () => { // TODO: refactor channel name and namespace to a constant mainWindow?.webContents.send('outline-ipc-push-clipboard'); }); // TODO: refactor channel name and namespace to a constant ipcMain.handle('outline-ipc-is-server-reachable', async (_, args: {hostname: string; port: number}) => { try { await connectivity.isServerReachable(args.hostname || '', args.port || 0, REACHABILITY_TIMEOUT_MS); return true; } catch { return false; } }); // Connects to the specified server, if that server is reachable and the credentials are valid. // TODO: refactor channel name and namespace to a constant ipcMain.handle( 'outline-ipc-start-proxying', async (_, args: {config: ShadowsocksSessionConfig; id: string}): Promise<errors.ErrorCode> => { // TODO: Rather than first disconnecting, implement a more efficient switchover (as well as // being faster, this would help prevent traffic leaks - the Cordova clients already do // this). if (currentTunnel) { console.log('disconnecting from current server...'); currentTunnel.disconnect(); await currentTunnel.onceDisconnected; } console.log(`connecting to ${args.id}...`); try { // Rather than repeadedly resolving a hostname in what may be a fingerprint-able way, // resolve it just once, upfront. args.config.host = await connectivity.lookupIp(args.config.host || ''); await connectivity.isServerReachable(args.config.host || '', args.config.port || 0, REACHABILITY_TIMEOUT_MS); await startVpn(args.config, args.id); console.log(`connected to ${args.id}`); await setupAutoLaunch(args); // Auto-connect requires IPs; the hostname in here has already been resolved (see above). tunnelStore.save(args).catch(() => { console.error('Failed to store tunnel.'); }); return errors.ErrorCode.NO_ERROR; } catch (e) { console.error(`could not connect: ${e.name} (${e.message})`); // clean up the state, no need to await because stopVpn might throw another error which can be ignored stopVpn(); return errors.toErrorCode(e); } } ); // Disconnects from the current server, if any. // TODO: refactor channel name and namespace to a constant ipcMain.handle('outline-ipc-stop-proxying', stopVpn); // Install backend services and return the error code // TODO: refactor channel name and namespace to a constant ipcMain.handle('outline-ipc-install-outline-services', async () => { // catch custom errors (even simple as numbers) does not work for ipcRenderer: // https://github.com/electron/electron/issues/24427 try { await installRoutingServices(); return errors.ErrorCode.NO_ERROR; } catch (e) { if (typeof e === 'number') { return e; } return errors.ErrorCode.UNEXPECTED; } }); // TODO: refactor channel name and namespace to a constant ipcMain.on('outline-ipc-quit-app', quitApp); // TODO: refactor channel name and namespace to a constant ipcMain.on('outline-ipc-localization-response', (_, localizationResult: {[key: string]: string}) => { if (localizationResult) { localizedStrings = localizationResult; } updateTray(TunnelStatus.DISCONNECTED); }); // Notify the UI of updates. autoUpdater.on('update-downloaded', () => { // TODO: refactor channel name and namespace to a constant mainWindow?.webContents.send('outline-ipc-update-downloaded'); }); } main();
{ "content_hash": "cb787f7361f5f3a385e44a4d55ec9213", "timestamp": "", "source": "github", "line_count": 539, "max_line_length": 117, "avg_line_length": 34.79777365491651, "alnum_prop": 0.6780763489016848, "repo_name": "Jigsaw-Code/outline-client", "id": "1c9af56af12a0140f8626cc542e3f1e63f8c9434", "size": "18756", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/electron/index.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "3975" }, { "name": "Batchfile", "bytes": "10768" }, { "name": "C#", "bytes": "50160" }, { "name": "C++", "bytes": "80767" }, { "name": "CMake", "bytes": "1960" }, { "name": "CSS", "bytes": "2741" }, { "name": "Dockerfile", "bytes": "2752" }, { "name": "Go", "bytes": "5972" }, { "name": "HTML", "bytes": "2529" }, { "name": "Java", "bytes": "61985" }, { "name": "JavaScript", "bytes": "130455" }, { "name": "NSIS", "bytes": "6840" }, { "name": "Objective-C", "bytes": "35023" }, { "name": "Python", "bytes": "5342" }, { "name": "Shell", "bytes": "12024" }, { "name": "Swift", "bytes": "49451" }, { "name": "TypeScript", "bytes": "213901" } ], "symlink_target": "" }
<html> <head> <title>User agent detail - Mozilla/5.0 (Linux; U; Android 2.2.1; Es-es; Bq Darwin Build/MASTER) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Linux; U; Android 2.2.1; Es-es; Bq Darwin Build/MASTER) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>ua-parser/uap-core<br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td> </td><td> </td><td style="border-left: 1px solid #555">bq</td><td>Darwin</td><td></td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a> <!-- Modal Structure --> <div id="modal-test" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Testsuite result detail</h4> <p><pre><code class="php">Array ( [user_agent_string] => Mozilla/5.0 (Linux; U; Android 2.2.1; Es-es; Bq Darwin Build/MASTER) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 [family] => Bq Darwin [brand] => bq [model] => Darwin ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Android 4.0</td><td>WebKit </td><td>Android 2.2</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.02</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-215ac98d-ccf8-4615-916e-5a819d6a59c9">Detail</a> <!-- Modal Structure --> <div id="modal-215ac98d-ccf8-4615-916e-5a819d6a59c9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.2\.2.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android?2.2* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => 2.2 [platform_description] => Android OS [platform_bits] => 32 [platform_maker] => Google Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => 1 [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [cssversion] => 3 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>Android Browser 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661">Detail</a> <!-- Modal Structure --> <div id="modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Android [browser] => Android Browser [version] => 4.0 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 2.2.1</td><td style="border-left: 1px solid #555">Generic</td><td>Android 2.2</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.30203</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc">Detail</a> <!-- Modal Structure --> <div id="modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 480 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => Generic [mobile_model] => Android 2.2 [version] => 4.0 [is_android] => 1 [browser_name] => Android Webkit [operating_system_family] => Android [operating_system_version] => 2.2.1 [is_ios] => [producer] => Google Inc. [operating_system] => Android 2.2.x Froyo [mobile_screen_width] => 320 [mobile_browser] => Android Webkit ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.2</small></td><td>Android Browser </td><td>WebKit </td><td>Android 2.2</td><td style="border-left: 1px solid #555">bq</td><td>Darwin</td><td>tablet</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.003</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-21638055-738d-46ba-a1b1-f5114bc26475">Detail</a> <!-- Modal Structure --> <div id="modal-21638055-738d-46ba-a1b1-f5114bc26475" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [operatingSystem] => Array ( [name] => Android [short_name] => AND [version] => 2.2 [platform] => ) [device] => Array ( [brand] => BX [brandName] => bq [model] => Darwin [device] => 2 [deviceName] => tablet ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => [isTablet] => 1 [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td><td>Navigator 4.0</td><td><i class="material-icons">close</i></td><td>Android 2.2.1</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c">Detail</a> <!-- Modal Structure --> <div id="modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 2.2.1; Es-es; Bq Darwin Build/MASTER) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 ) [name:Sinergi\BrowserDetector\Browser:private] => Navigator [version:Sinergi\BrowserDetector\Browser:private] => 4.0 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Android [version:Sinergi\BrowserDetector\Os:private] => 2.2.1 [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 2.2.1; Es-es; Bq Darwin Build/MASTER) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 2.2.1; Es-es; Bq Darwin Build/MASTER) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>Android 2.2.1</td><td><i class="material-icons">close</i></td><td>Android 2.2.1</td><td style="border-left: 1px solid #555">bq</td><td>Darwin</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b">Detail</a> <!-- Modal Structure --> <div id="modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 2 [minor] => 2 [patch] => 1 [family] => Android ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 2 [minor] => 2 [patch] => 1 [patchMinor] => [family] => Android ) [device] => UAParser\Result\Device Object ( [brand] => bq [model] => Darwin [family] => Bq Darwin ) [originalUserAgent] => Mozilla/5.0 (Linux; U; Android 2.2.1; Es-es; Bq Darwin Build/MASTER) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Darwin </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.08501</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4">Detail</a> <!-- Modal Structure --> <div id="modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Android Webkit Browser [agent_version] => -- [os_type] => Darwin [os_name] => Darwin [os_versionName] => [os_versionNumber] => [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => Spanish - Spain [agent_languageTag] => Es-es ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small></td><td>Android Browser 4.0</td><td>WebKit 533.1</td><td>Android 2.2.1</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.43104</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9795f66f-7271-430e-973a-a5c0e14dc35a">Detail</a> <!-- Modal Structure --> <div id="modal-9795f66f-7271-430e-973a-a5c0e14dc35a" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Android [simple_sub_description_string] => [simple_browser_string] => Android Browser 4 on Android (Froyo) [browser_version] => 4 [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => stdClass Object ( [System Build] => Master ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => android-browser [operating_system_version] => Froyo [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 533.1 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Android (Froyo) [operating_system_version_full] => 2.2.1 [operating_platform_code] => [browser_name] => Android Browser [operating_system_name_code] => android [user_agent] => Mozilla/5.0 (Linux; U; Android 2.2.1; Es-es; Bq Darwin Build/MASTER) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 [browser_version_full] => 4.0 [browser] => Android Browser 4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>2.0.10</small></td><td>Android Browser </td><td>Webkit 533.1</td><td>Android 2.2.1</td><td style="border-left: 1px solid #555">bq</td><td>Darwin</td><td>tablet</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.009</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4">Detail</a> <!-- Modal Structure --> <div id="modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Android Browser ) [engine] => Array ( [name] => Webkit [version] => 533.1 ) [os] => Array ( [name] => Android [version] => 2.2.1 ) [device] => Array ( [type] => tablet [manufacturer] => bq [model] => Darwin ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3f285ff5-314b-4db4-9948-54572e92e7b6">Detail</a> <!-- Modal Structure --> <div id="modal-3f285ff5-314b-4db4-9948-54572e92e7b6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [name] => Safari [vendor] => Apple [version] => 4.0 [category] => smartphone [os] => Android [os_version] => 2.2.1 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td> </td><td><i class="material-icons">close</i></td><td>Linux </td><td style="border-left: 1px solid #555"></td><td></td><td>Smartphone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.054</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-1a1aee36-7ce7-4111-a391-8e2c501f1532">Detail</a> <!-- Modal Structure --> <div id="modal-1a1aee36-7ce7-4111-a391-8e2c501f1532" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => true [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => false [is_mobile] => true [is_robot] => false [is_smartphone] => true [is_touchscreen] => true [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Linux [advertised_device_os_version] => [advertised_browser] => [advertised_browser_version] => [complete_device_name] => Generic Android 2.2 [form_factor] => Smartphone [is_phone] => true [is_app_webview] => false ) [all] => Array ( [brand_name] => Generic [model_name] => Android 2.2 [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => Android [mobile_browser] => Android Webkit [mobile_browser_version] => [device_os_version] => 2.2 [pointing_method] => touchscreen [release_date] => 2009_october [marketing_name] => [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => true [is_tablet] => false [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => true [xhtml_supports_css_cell_table_coloring] => true [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => true [xhtml_document_title_support] => true [xhtml_preferred_charset] => iso-8859-1 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => true [xhtml_send_sms_string] => sms: [xhtml_send_mms_string] => mms: [xhtml_file_upload] => supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => play_and_stop [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => w3c_api [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 320 [resolution_height] => 480 [columns] => 60 [max_image_width] => 320 [max_image_height] => 400 [rows] => 40 [physical_screen_width] => 34 [physical_screen_height] => 50 [dual_orientation] => true [density_class] => 1.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => false [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => true [transparent_png_index] => true [svgt_1_1] => false [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => false [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 384 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 2000000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => true [inline_support] => false [oma_support] => true [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => true [streaming_3gpp] => true [streaming_mp4] => true [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => 10 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => 2 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => 3.0 [streaming_acodec_amr] => nb [streaming_acodec_aac] => lc [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => progressive_download [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => true [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => true [mp3] => true [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => true [css_supports_width_as_percentage] => true [css_border_image] => webkit [css_rounded_corners] => webkit [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => 10 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => 0 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => 3.0 [playback_real_media] => none [playback_3gpp] => true [playback_3g2] => false [playback_mp4] => true [playback_mov] => false [playback_acodec_amr] => nb [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => true [html_preferred_dtd] => html4 [viewport_supported] => true [viewport_width] => device_width_token [viewport_userscalable] => no [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => full [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => A [is_sencha_touch_ok] => false [controlcap_is_smartphone] => default [controlcap_is_ios] => default [controlcap_is_android] => default [controlcap_is_robot] => default [controlcap_is_app] => default [controlcap_advertised_device_os] => default [controlcap_advertised_device_os_version] => default [controlcap_advertised_browser] => default [controlcap_advertised_browser_version] => default [controlcap_is_windows_phone] => default [controlcap_is_full_desktop] => default [controlcap_is_largescreen] => default [controlcap_is_mobile] => default [controlcap_is_touchscreen] => default [controlcap_is_wml_preferred] => default [controlcap_is_xhtmlmp_preferred] => default [controlcap_is_html_preferred] => default [controlcap_form_factor] => default [controlcap_complete_device_name] => default ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-02-13 13:36:14</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
{ "content_hash": "ca20d5eb79f9d73e8a81d0c1ef15cb2b", "timestamp": "", "source": "github", "line_count": 1121, "max_line_length": 743, "avg_line_length": 41.30508474576271, "alnum_prop": 0.5373949852061422, "repo_name": "ThaDafinser/UserAgentParserComparison", "id": "12e3e651d0d1cb196639abd665344ff0015492ab", "size": "46304", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "v4/user-agent-detail/9c/94/9c94f0e7-a1cb-4403-8ebc-bf54eae50971.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2060859160" } ], "symlink_target": "" }
body { padding-top: 70px; } @-moz-document url-prefix() { fieldset { display: table-cell; } }
{ "content_hash": "b18e3f94996fb9fe0530366c2a61109c", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 35, "avg_line_length": 16.166666666666668, "alnum_prop": 0.6391752577319587, "repo_name": "iMunshi/backbonejs-contact-manager", "id": "4c332999d6d8f3d90fe9b9d4c34a1205a98cfd37", "size": "97", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/css/main.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "97" }, { "name": "JavaScript", "bytes": "4684" }, { "name": "PHP", "bytes": "74734" } ], "symlink_target": "" }
import { CommonModule } from '@angular/common' import { NgModule } from '@angular/core' import { IonicModule } from 'ionic-angular' import { PipesModule } from '../../shared/pipes/pipes.module' import { SplashPageComponent } from './containers/splash-page.component' import { SplashService } from './services/splash.service' @NgModule({ imports: [ CommonModule, PipesModule, IonicModule.forRoot(SplashPageComponent) ], declarations: [SplashPageComponent], providers: [SplashService] }) export class SplashModule {}
{ "content_hash": "133eb2583270292ace3e9ef239e8f0d4", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 72, "avg_line_length": 29.833333333333332, "alnum_prop": 0.7318435754189944, "repo_name": "RADAR-CNS/RADAR-Questionnaire", "id": "1fd26e67105bc681f9fb281232ae94af2fa1c998", "size": "537", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/pages/splash/splash.module.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "20042" }, { "name": "HTML", "bytes": "19996" }, { "name": "JavaScript", "bytes": "10818" }, { "name": "Shell", "bytes": "461" }, { "name": "TypeScript", "bytes": "120495" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "051e0f5deff90e21d14026fee8909ca3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "f1f06b379fcb2c3344434a00902bfa33fe0d7e97", "size": "179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Gentianaceae/Gentiana/Gentiana nanobella/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.famaridon.maven.scoped.properties.exceptions; /** * Created by famaridon on 10/07/2014. */ public class BuildPropertiesFilesException extends Exception { public BuildPropertiesFilesException() { super(); } public BuildPropertiesFilesException(String s) { super(s); } public BuildPropertiesFilesException(String s, Throwable throwable) { super(s, throwable); } public BuildPropertiesFilesException(Throwable throwable) { super(throwable); } protected BuildPropertiesFilesException(String s, Throwable throwable, boolean b, boolean b2) { super(s, throwable, b, b2); } }
{ "content_hash": "5d5ad9b98e7dbcb55002009fb13f3786", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 96, "avg_line_length": 23.346153846153847, "alnum_prop": 0.7611202635914333, "repo_name": "famaridon/scoped-properties-maven-plugin", "id": "6930eed3916fc32075f49f5a055c2b33d94f956e", "size": "607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/famaridon/maven/scoped/properties/exceptions/BuildPropertiesFilesException.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "41446" } ], "symlink_target": "" }
class CreateUserRequests < ActiveRecord::Migration def change create_table :chat_requests do |t| t.string :type t.string :payload t.timestamps end add_reference :chat_requests, :chat end end
{ "content_hash": "531b825908e92b8d6d3a388a23d55a53", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 50, "avg_line_length": 18.916666666666668, "alnum_prop": 0.6696035242290749, "repo_name": "chyrta/TUTBYBot", "id": "101b2a45d7f4b44baddb71721c5e876103ed6ac1", "size": "227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20170521211802_create_user_requests.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "9172" } ], "symlink_target": "" }
package net.sourceforge.marathon.fxdocking; import java.util.logging.Logger; public class DockingUtilities { public static final Logger LOGGER = Logger.getLogger(DockingUtilities.class.getName()); public static TabbedDockableContainer findTabbedDockableContainer(Dockable dockable) { // TODO Auto-generated method stub IDockingContainer container = dockable.getContainer(); if (container instanceof TabDockingContainer) { return (TabbedDockableContainer) container; } return null; } }
{ "content_hash": "0e1b5757a92774de08e71ec8feaca739", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 91, "avg_line_length": 29.210526315789473, "alnum_prop": 0.7261261261261261, "repo_name": "jalian-systems/marathonv5", "id": "d0c58cb705ce06324f416b85119eb16631a68080", "size": "1318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "marathon-core/src/main/java/net/sourceforge/marathon/fxdocking/DockingUtilities.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AppleScript", "bytes": "1764" }, { "name": "Batchfile", "bytes": "6982" }, { "name": "CSS", "bytes": "1787119" }, { "name": "HTML", "bytes": "54026" }, { "name": "Java", "bytes": "9276296" }, { "name": "JavaScript", "bytes": "44347" }, { "name": "Ruby", "bytes": "877513" }, { "name": "Shell", "bytes": "580" }, { "name": "XSLT", "bytes": "12141" } ], "symlink_target": "" }
using GameFramework.Event; using GameFramework.Procedure; using UnityEngine; using UnityGameFramework.Runtime; using ProcedureOwner = GameFramework.Fsm.IFsm<GameFramework.Procedure.IProcedureManager>; namespace Game { public class ProcedureLaunch : ProcedureBase { private bool m_HasStartedInitRes = false; private bool m_InitResComplete = false; protected override void OnInit(ProcedureOwner procedureOwner) { base.OnInit(procedureOwner); } protected override void OnEnter(ProcedureOwner procedureOwner) { base.OnEnter(procedureOwner); m_HasStartedInitRes = false; m_InitResComplete = false; } protected override void OnUpdate(ProcedureOwner procedureOwner, float elapseSeconds, float realElapseSeconds) { base.OnUpdate(procedureOwner, elapseSeconds, realElapseSeconds); if (Application.isEditor && GameEntry.GetComponent<BaseComponent>().EditorResourceMode) { ChangeState<ProcedureLoadLuaScripts>(procedureOwner); return; } if (!m_HasStartedInitRes) { m_HasStartedInitRes = true; GameEntry.GetComponent<EventComponent>().Subscribe(EventId.ResourceInitComplete, OnResourceInitComplete); GameEntry.GetComponent<ResourceComponent>().InitResources(); } if (m_InitResComplete) { GameEntry.GetComponent<EventComponent>().Unsubscribe(EventId.ResourceInitComplete, OnResourceInitComplete); ChangeState<ProcedureLoadLuaScripts>(procedureOwner); } } protected override void OnLeave(ProcedureOwner procedureOwner, bool isShutdown) { base.OnLeave(procedureOwner, isShutdown); } protected override void OnDestroy(ProcedureOwner procedureOwner) { base.OnDestroy(procedureOwner); } private void OnResourceInitComplete(object sender, GameEventArgs e) { m_InitResComplete = true; } } }
{ "content_hash": "c58f11995d373e15489e9826d1c046b2", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 123, "avg_line_length": 33.38461538461539, "alnum_prop": 0.6414746543778802, "repo_name": "GarfieldJiang/UGFWithToLua", "id": "1ff8dda65966360a3cd524235ba2d42137f16d61", "size": "2172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/ProcedureLaunch.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2598406" }, { "name": "Lua", "bytes": "250125" } ], "symlink_target": "" }
require 'uri' require 'openssl' require 'time' require 'securerandom' require 'set' require 'savon' if Puppet.features.savon? module Transip SOAP_ARRAY_KEYS ||= [:item, :'@soap_enc:array_type', :'@xsi:type'].to_set.freeze refine Array do def to_soap if empty? {} else type = first.class.name.split(':').last soaped_options = map { |o| o.to_soap } { item: { content!: soaped_options, '@xsi:type': "tns:#{type}" }, '@xsi:type': "tns:ArrayOf#{type}", '@enc:arrayType': "tns:#{type}[#{soaped_options.size}]" } end end def from_soap map { |x| x.from_soap } end end refine Hash do def to_soap each_with_object({}) do |(k, v), memo| memo[k] = v.to_soap end end def single_element_soap_array? keys.to_set == SOAP_ARRAY_KEYS && self[:'@soap_enc:array_type'].end_with?('[1]') end def strip_soap_keys if single_element_soap_array? { item: [self[:item]] } # turn single element array into proper array else each_with_object({}) do |(k, v), memo| memo[k] = v unless k[0].to_s == '@' end end end def from_soap h = strip_soap_keys.each_with_object({}) do |(k, v), memo| memo[k] = v.from_soap end (h.keys == [:item] || h.keys == [:return]) ? h[keys.first] : h end end refine Object do [:to_soap, :from_soap].each do |m| define_method(m) { to_s } end end class Soap API_VERSION ||= '5.6'.freeze ENDPOINT ||= 'api.transip.nl'.freeze API_SERVICE ||= 'DomainService'.freeze WSDL ||= "https://#{ENDPOINT}/wsdl/?service=#{API_SERVICE}".freeze NAMESPACES ||= { 'xmlns:enc': 'http://schemas.xmlsoap.org/soap/encoding/' }.freeze using Transip class << self def camelize(word) parts = word.to_s.split('_') parts.first.downcase + parts[1..-1].map(&:capitalize).join end def to_indexed_hash(array) Hash[(0...array.size).zip(array)] end def urlencode(input) URI.encode_www_form_component(input.to_s).gsub('+', '%20').gsub('%7E', '~').gsub('*', '%2A') end def encode(params, prefix = nil) case params when Hash params.map { |key, value| encoded_key = prefix ? "#{prefix}[#{urlencode(key)}]" : urlencode(key) encode(value, encoded_key) }.flatten when Array h = to_indexed_hash(params) encode(h, prefix) else ["#{prefix}=#{urlencode(params)}"] end end def message_options(method, api_service, hostname, time, nonce) ["__method=#{camelize(method)}", "__service=#{api_service}", "__hostname=#{hostname}", "__timestamp=#{time}", "__nonce=#{nonce}"] end def serialize(action, api_service, hostname, time, nonce, options = {}) (encode(options.values) + message_options(action, api_service, hostname, time, nonce)).join('&') end def sign(input, private_key) digest = OpenSSL::Digest::SHA512.new signed_input = private_key.sign(digest, input) urlencode(Base64.encode64(signed_input)) end def to_cookie_array(username, mode, time, nonce, api_version, signature) ["login=#{username}", "mode=#{mode}", "timestamp=#{time}", "nonce=#{nonce}", "clientVersion=#{api_version}", "signature=#{signature}"] end def cookies(action, username, mode, api_service, api_version, hostname, private_key, options = {}) time = Time.new.to_i # strip out the -'s because transip requires the nonce to be between 6 and 32 chars nonce = SecureRandom.uuid.delete('-') serialized_input = serialize(action, api_service, hostname, time, nonce, options) signature = sign(serialized_input, private_key) to_cookie_array(username, mode, time, nonce, api_version, signature).map { |c| HTTPI::Cookie.new(c) } end end def initialize(options = {}) begin key = options[:key] || (options[:key_file] && File.read(options[:key_file])) @private_key = OpenSSL::PKey::RSA.new(key) rescue OpenSSL::PKey::RSAError raise ArgumentError, 'Invalid RSA key' end @username = options[:username] raise ArgumentError, 'The :username and :key options are required' unless @username && key @mode = options[:mode] || :readonly @client = Savon::Client.new(wsdl: WSDL, namespaces: NAMESPACES) end def request(action, options = {}) response_action = "#{action}_response".to_sym message = options.to_soap cookies = self.class.cookies(action, @username, @mode, API_SERVICE, API_VERSION, ENDPOINT, @private_key, options) response = @client.call(action, message: message, cookies: cookies) response.body[response_action].from_soap end end end
{ "content_hash": "2c3532284d9e03a95ef7f9039e4741a3", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 142, "avg_line_length": 31.928571428571427, "alnum_prop": 0.5865365059995933, "repo_name": "gerardkok/puppet-transip", "id": "b84da653f7b9f96ff5cd4cf81a111f57fbf1b2f5", "size": "4917", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/puppet_x/transip/soap.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "181" }, { "name": "Puppet", "bytes": "1289" }, { "name": "Ruby", "bytes": "36402" }, { "name": "Shell", "bytes": "329" } ], "symlink_target": "" }
import cPickle as pickle import urllib import flask import numpy as np from waitress import serve from grpc.beta import implementations import tensorflow as tf from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2 from google.protobuf.json_format import MessageToJson app = flask.Flask(__name__) @app.route('/model_prediction', methods=["GET", "POST"]) def model_prediction(): host = "localhost" port = 9000 model_name = "default" url_input = flask.request.values.get('input') model_input = pickle.loads(str(urllib.unquote(url_input))) channel = implementations.insecure_channel(host, int(port)) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) request = predict_pb2.PredictRequest() request.model_spec.name = model_name for k,v in model_input.items(): request.inputs[k].CopyFrom( tf.contrib.util.make_tensor_proto(v)) result = stub.Predict(request, 10.0) # 10 secs timeout return MessageToJson(result) if __name__ == '__main__': #slow and unreliable (dev purpouses) #app.run(host="0.0.0.0", port=5000) #using waitrsess server instead serve(app, host='0.0.0.0', port=8915)
{ "content_hash": "86f904a69cdde2889d351b2254ae3eae", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 77, "avg_line_length": 27.17391304347826, "alnum_prop": 0.7056, "repo_name": "avloss/serving", "id": "01364ea53956433451fc817c08c33005c84c4ce1", "size": "1250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow_serving/example/flask_client.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "1397437" }, { "name": "CSS", "bytes": "12464" }, { "name": "HTML", "bytes": "3225" }, { "name": "Jupyter Notebook", "bytes": "25836" }, { "name": "Protocol Buffer", "bytes": "20980" }, { "name": "Python", "bytes": "170419" }, { "name": "Shell", "bytes": "442" } ], "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 com.wrmsr.wava.core.literal; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.collect.ImmutableMap; import com.wrmsr.wava.core.type.Type; import javax.annotation.concurrent.Immutable; import java.util.Map; import java.util.Objects; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; @Immutable public abstract class Literal<Self, Value> { // FIXME: human readability @JsonValue public final Object jsonValue() { return ImmutableMap.of(getType().getName(), "0x" + Long.toString(getBits(), 16)); } @JsonCreator public static Literal jsonCreator(Map<String, String> object) { if (object == null) { return null; } checkArgument(object.size() == 1); Map.Entry<String, String> e = object.entrySet().iterator().next(); String key = requireNonNull(e.getKey()); String value = requireNonNull(e.getValue()); Type type = Type.of(key); checkArgument(value.startsWith("0x") && value.length() > 2); long bits = Long.parseLong(value.substring(2), 16); return of(type, bits); } protected final long bits; public Literal(long bits) { this.bits = bits; } public abstract <C, R> R accept(LiteralVisitor<C, R> visitor, C context); public static Literal of(Type type, long bits) { switch (type) { case I32: return new I32Literal(bits); case I64: return new I64Literal(bits); case F32: return new F32Literal(bits); case F64: return new F64Literal(bits); default: throw new UnsupportedOperationException(); } } public static I32Literal of(boolean value) { return value ? new I32Literal(1) : new I32Literal(0); } public static I32Literal of(int value) { return new I32Literal(value); } public static I64Literal of(long value) { return new I64Literal(value); } public static F32Literal of(float value) { return new F32Literal(Float.floatToRawIntBits(value)); } public static F64Literal of(double value) { return new F64Literal(Double.doubleToRawLongBits(value)); } public static Literal of(Object value) { if (value instanceof Integer) { return new I32Literal((Integer) value); } else if (value instanceof Long) { return new I64Literal((Long) value); } else if (value instanceof Float) { return new F32Literal((Float) value); } else if (value instanceof Double) { return new F64Literal((Double) value); } else { throw new IllegalArgumentException(); } } public final long getBits() { return bits; } @Override public final boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Literal<?, ?> literal = (Literal<?, ?>) o; return bits == literal.bits; } @Override public final int hashCode() { return Objects.hash(bits); } public abstract Type getType(); public abstract Value getValue(); protected abstract void innerPrint(StringBuilder sb); public F32Literal toF32() { throw new UnsupportedOperationException(); } public F64Literal toF64() { throw new UnsupportedOperationException(); } public I32Literal toI32() { throw new UnsupportedOperationException(); } public I64Literal toI64() { throw new UnsupportedOperationException(); } public int getI32() { throw new UnsupportedOperationException(); } public long getI64() { throw new UnsupportedOperationException(); } public float getF32() { throw new UnsupportedOperationException(); } public double getF64() { throw new UnsupportedOperationException(); } public long getInteger() { throw new UnsupportedOperationException(); } public double getFloat() { throw new UnsupportedOperationException(); } public I32Literal countLeadingZeroes() { throw new UnsupportedOperationException(); } public I32Literal countTrailingZeroes() { throw new UnsupportedOperationException(); } public I32Literal popCount() { throw new UnsupportedOperationException(); } public I64Literal extendToSI64() { throw new UnsupportedOperationException(); } public I64Literal extendToUI64() { throw new UnsupportedOperationException(); } public F64Literal extendToF64() { throw new UnsupportedOperationException(); } public I32Literal truncateToI32() { throw new UnsupportedOperationException(); } public F32Literal truncateToF32() { throw new UnsupportedOperationException(); } public F32Literal convertSToF32() { throw new UnsupportedOperationException(); } public F32Literal convertUToF32() { throw new UnsupportedOperationException(); } public F64Literal convertSToF64() { throw new UnsupportedOperationException(); } public F64Literal convertUToF64() { throw new UnsupportedOperationException(); } public Literal neg() { throw new UnsupportedOperationException(); } public Literal abs() { throw new UnsupportedOperationException(); } public Literal ceil() { throw new UnsupportedOperationException(); } public Literal floor() { throw new UnsupportedOperationException(); } public Literal trunc() { throw new UnsupportedOperationException(); } public Literal nearbyint() { throw new UnsupportedOperationException(); } public Literal sqrt() { throw new UnsupportedOperationException(); } public Literal add(Literal other) { throw new UnsupportedOperationException(); } public Literal sub(Literal other) { throw new UnsupportedOperationException(); } public Literal mul(Literal other) { throw new UnsupportedOperationException(); } public Literal div(Literal other) { throw new UnsupportedOperationException(); } public Literal divS(Literal other) { throw new UnsupportedOperationException(); } public Literal divU(Literal other) { throw new UnsupportedOperationException(); } public Literal remS(Literal other) { throw new UnsupportedOperationException(); } public Literal remU(Literal other) { throw new UnsupportedOperationException(); } public Literal and_(Literal other) { throw new UnsupportedOperationException(); } public Literal or_(Literal other) { throw new UnsupportedOperationException(); } public Literal xor_(Literal other) { throw new UnsupportedOperationException(); } public Literal shl(Literal other) { throw new UnsupportedOperationException(); } public Literal shrS(Literal other) { throw new UnsupportedOperationException(); } public Literal shrU(Literal other) { throw new UnsupportedOperationException(); } public Literal rotL(Literal other) { throw new UnsupportedOperationException(); } public Literal rotR(Literal other) { throw new UnsupportedOperationException(); } public Literal eq(Literal other) { throw new UnsupportedOperationException(); } public Literal ne(Literal other) { throw new UnsupportedOperationException(); } public Literal ltS(Literal other) { throw new UnsupportedOperationException(); } public Literal ltU(Literal other) { throw new UnsupportedOperationException(); } public Literal lt(Literal other) { throw new UnsupportedOperationException(); } public Literal leS(Literal other) { throw new UnsupportedOperationException(); } public Literal leU(Literal other) { throw new UnsupportedOperationException(); } public Literal le(Literal other) { throw new UnsupportedOperationException(); } public Literal gtS(Literal other) { throw new UnsupportedOperationException(); } public Literal gtU(Literal other) { throw new UnsupportedOperationException(); } public Literal gt(Literal other) { throw new UnsupportedOperationException(); } public Literal geS(Literal other) { throw new UnsupportedOperationException(); } public Literal geU(Literal other) { throw new UnsupportedOperationException(); } public Literal ge(Literal other) { throw new UnsupportedOperationException(); } public Literal min(Literal other) { throw new UnsupportedOperationException(); } public Literal max(Literal other) { throw new UnsupportedOperationException(); } public Literal copySign(Literal other) { throw new UnsupportedOperationException(); } }
{ "content_hash": "8e2255656c607a17de087fdad0293c24", "timestamp": "", "source": "github", "line_count": 464, "max_line_length": 89, "avg_line_length": 22.20689655172414, "alnum_prop": 0.624417701863354, "repo_name": "wrmsr/wava", "id": "51041b5f5c40ed9f1bf0525e2783b953eee9b1bf", "size": "10304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/wrmsr/wava/core/literal/Literal.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "3300558" }, { "name": "C", "bytes": "5042845" }, { "name": "C++", "bytes": "96366" }, { "name": "CMake", "bytes": "554" }, { "name": "Charity", "bytes": "26547" }, { "name": "Dockerfile", "bytes": "2136" }, { "name": "Java", "bytes": "14026396" }, { "name": "JavaScript", "bytes": "30232" }, { "name": "LLVM", "bytes": "6249320" }, { "name": "Makefile", "bytes": "39023" }, { "name": "Pascal", "bytes": "70" }, { "name": "Python", "bytes": "1038" }, { "name": "Shell", "bytes": "23039" }, { "name": "WebAssembly", "bytes": "36576133" } ], "symlink_target": "" }
import logging from datetime import timedelta from django.db import DEFAULT_DB_ALIAS from django.utils import timezone from django.db.models.deletion import Collector from django.core.management.base import BaseCommand from chatbot.models import ChatHistory logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Purge old chat history (default 30 days)' def add_arguments(self, parser): parser.add_argument( '--days', type=int, default=30, help='Delete task reports older than N days (default 30)') parser.add_argument( '--force', action='store_true', default=False, help='Allow delete fresher than 7 days', ) def handle(self, *args, **options): verbosity = int(options.get("verbosity", "1")) levels = (logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG) if "verbosity" in options: logging.basicConfig(format='%(message)s', level=levels[verbosity]) if options['days'] < 7 and not options['force']: logger.error('Delete less than one week not allowed, try using --force') return if options['days'] < 1: logger.error('Delete less than one day not allowed at all') return start_date = timezone.now() - timedelta(days=options['days']) collector = Collector(using=DEFAULT_DB_ALIAS) logger.info("Purge old chat records since {}".format(start_date)) for model in [ChatHistory]: qs = model.objects.filter(created__lt=start_date) logger.info("Delete {} records in {}".format(qs.count(), model._meta.db_table)) collector.collect(qs) collector.delete() logger.info("Done purging old records.")
{ "content_hash": "36437238909d86d3d188506aea67a800", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 91, "avg_line_length": 34.55769230769231, "alnum_prop": 0.6349471341124096, "repo_name": "dchaplinsky/declarations.com.ua", "id": "a7734dbb2041c88383baf6bc22d5419146cdeccf", "size": "1797", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "declarations_site/chatbot/management/commands/purgechathistory.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "3235" }, { "name": "HTML", "bytes": "3593" }, { "name": "JavaScript", "bytes": "1559768" }, { "name": "Jinja", "bytes": "591048" }, { "name": "Python", "bytes": "561374" }, { "name": "SCSS", "bytes": "546001" }, { "name": "Shell", "bytes": "1517" } ], "symlink_target": "" }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string.h> #include "base/stringprintf.h" #include "chrome/browser/extensions/api/bluetooth/bluetooth_api.h" #include "chrome/browser/extensions/bluetooth_event_router.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_out_of_band_pairing_data.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "device/bluetooth/test/mock_bluetooth_device.h" #include "testing/gmock/include/gmock/gmock.h" using device::BluetoothAdapter; using device::BluetoothDevice; using device::BluetoothOutOfBandPairingData; using device::MockBluetoothAdapter; using device::MockBluetoothDevice; using extensions::Extension; namespace utils = extension_function_test_utils; namespace api = extensions::api; namespace { static const char* kAdapterAddress = "A1:A2:A3:A4:A5:A6"; static const char* kName = "whatsinaname"; class BluetoothApiTest : public ExtensionApiTest { public: BluetoothApiTest() : empty_extension_(utils::CreateEmptyExtension()) {} virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis); } virtual void SetUpOnMainThread() OVERRIDE { // The browser will clean this up when it is torn down mock_adapter_ = new testing::StrictMock<MockBluetoothAdapter>( kAdapterAddress, kName); event_router()->SetAdapterForTest(mock_adapter_); device1_.reset(new testing::NiceMock<MockBluetoothDevice>( mock_adapter_, "d1", "11:12:13:14:15:16", true /* paired */, false /* bonded */, true /* connected */)); device2_.reset(new testing::NiceMock<MockBluetoothDevice>( mock_adapter_, "d2", "21:22:23:24:25:26", false /* paired */, true /* bonded */, false /* connected */)); } virtual void CleanUpOnMainThread() OVERRIDE { EXPECT_CALL(*mock_adapter_, RemoveObserver(testing::_)); } void expectBooleanResult(bool expected, UIThreadExtensionFunction* function) { scoped_ptr<base::Value> result( utils::RunFunctionAndReturnSingleResult(function, "[]", browser())); ASSERT_TRUE(result.get() != NULL); ASSERT_EQ(base::Value::TYPE_BOOLEAN, result->GetType()); bool boolean_value; result->GetAsBoolean(&boolean_value); EXPECT_EQ(expected, boolean_value); } void expectStringResult(const std::string& expected, UIThreadExtensionFunction* function) { scoped_ptr<base::Value> result( utils::RunFunctionAndReturnSingleResult(function, "[]", browser())); ASSERT_TRUE(result.get() != NULL); ASSERT_EQ(base::Value::TYPE_STRING, result->GetType()); std::string string_value; result->GetAsString(&string_value); EXPECT_EQ(expected, string_value); } template <class T> T* setupFunction(T* function) { function->set_extension(empty_extension_.get()); function->set_has_callback(true); return function; } protected: testing::StrictMock<MockBluetoothAdapter>* mock_adapter_; scoped_ptr<testing::NiceMock<MockBluetoothDevice> > device1_; scoped_ptr<testing::NiceMock<MockBluetoothDevice> > device2_; extensions::ExtensionBluetoothEventRouter* event_router() { return browser()->profile()->GetExtensionService()-> bluetooth_event_router(); } private: scoped_refptr<Extension> empty_extension_; }; // This is the canonical UUID for the short UUID 0010. static const char kOutOfBandPairingDataHash[] = "0123456789ABCDEh"; static const char kOutOfBandPairingDataRandomizer[] = "0123456789ABCDEr"; static BluetoothOutOfBandPairingData GetOutOfBandPairingData() { BluetoothOutOfBandPairingData data; memcpy(&(data.hash), kOutOfBandPairingDataHash, device::kBluetoothOutOfBandPairingDataSize); memcpy(&(data.randomizer), kOutOfBandPairingDataRandomizer, device::kBluetoothOutOfBandPairingDataSize); return data; } static bool CallClosure(const base::Closure& callback) { callback.Run(); return true; } static void CallOutOfBandPairingDataCallback( const BluetoothAdapter::BluetoothOutOfBandPairingDataCallback& callback, const BluetoothAdapter::ErrorCallback& error_callback) { callback.Run(GetOutOfBandPairingData()); } template <bool Value> static void CallProvidesServiceCallback( const std::string& name, const BluetoothDevice::ProvidesServiceCallback& callback) { callback.Run(Value); } } // namespace IN_PROC_BROWSER_TEST_F(BluetoothApiTest, IsAvailable) { EXPECT_CALL(*mock_adapter_, IsPresent()) .WillOnce(testing::Return(false)); scoped_refptr<api::BluetoothIsAvailableFunction> is_available; is_available = setupFunction(new api::BluetoothIsAvailableFunction); expectBooleanResult(false, is_available); testing::Mock::VerifyAndClearExpectations(mock_adapter_); EXPECT_CALL(*mock_adapter_, IsPresent()) .WillOnce(testing::Return(true)); is_available = setupFunction(new api::BluetoothIsAvailableFunction); expectBooleanResult(true, is_available); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, IsPowered) { EXPECT_CALL(*mock_adapter_, IsPowered()) .WillOnce(testing::Return(false)); scoped_refptr<api::BluetoothIsPoweredFunction> is_powered; is_powered = setupFunction(new api::BluetoothIsPoweredFunction); expectBooleanResult(false, is_powered); testing::Mock::VerifyAndClearExpectations(mock_adapter_); EXPECT_CALL(*mock_adapter_, IsPowered()) .WillOnce(testing::Return(true)); is_powered = setupFunction(new api::BluetoothIsPoweredFunction); expectBooleanResult(true, is_powered); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetAddress) { scoped_refptr<api::BluetoothGetAddressFunction> get_address; get_address = setupFunction(new api::BluetoothGetAddressFunction); expectStringResult(kAdapterAddress, get_address); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetName) { scoped_refptr<api::BluetoothGetNameFunction> get_name; get_name = setupFunction(new api::BluetoothGetNameFunction); expectStringResult(kName, get_name); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetLocalOutOfBandPairingData) { EXPECT_CALL(*mock_adapter_, ReadLocalOutOfBandPairingData(testing::_, testing::_)) .WillOnce(testing::Invoke(CallOutOfBandPairingDataCallback)); scoped_refptr<api::BluetoothGetLocalOutOfBandPairingDataFunction> get_oob_function(setupFunction( new api::BluetoothGetLocalOutOfBandPairingDataFunction)); scoped_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( get_oob_function, "[]", browser())); base::DictionaryValue* dict; EXPECT_TRUE(result->GetAsDictionary(&dict)); base::BinaryValue* binary_value; EXPECT_TRUE(dict->GetBinary("hash", &binary_value)); EXPECT_STREQ(kOutOfBandPairingDataHash, std::string(binary_value->GetBuffer(), binary_value->GetSize()).c_str()); EXPECT_TRUE(dict->GetBinary("randomizer", &binary_value)); EXPECT_STREQ(kOutOfBandPairingDataRandomizer, std::string(binary_value->GetBuffer(), binary_value->GetSize()).c_str()); // Try again with an error testing::Mock::VerifyAndClearExpectations(mock_adapter_); EXPECT_CALL(*mock_adapter_, ReadLocalOutOfBandPairingData( testing::_, testing::Truly(CallClosure))); get_oob_function = setupFunction(new api::BluetoothGetLocalOutOfBandPairingDataFunction); std::string error( utils::RunFunctionAndReturnError(get_oob_function, "[]", browser())); EXPECT_FALSE(error.empty()); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, SetOutOfBandPairingData) { std::string device_address("11:12:13:14:15:16"); EXPECT_CALL(*mock_adapter_, GetDevice(device_address)) .WillOnce(testing::Return(device1_.get())); EXPECT_CALL(*device1_, ClearOutOfBandPairingData(testing::Truly(CallClosure), testing::_)); std::string params = base::StringPrintf( "[{\"deviceAddress\":\"%s\"}]", device_address.c_str()); scoped_refptr<api::BluetoothSetOutOfBandPairingDataFunction> set_oob_function; set_oob_function = setupFunction( new api::BluetoothSetOutOfBandPairingDataFunction); // There isn't actually a result. (void)utils::RunFunctionAndReturnSingleResult( set_oob_function, params, browser()); // Try again with an error testing::Mock::VerifyAndClearExpectations(mock_adapter_); testing::Mock::VerifyAndClearExpectations(device1_.get()); EXPECT_CALL(*mock_adapter_, GetDevice(device_address)) .WillOnce(testing::Return(device1_.get())); EXPECT_CALL(*device1_, ClearOutOfBandPairingData(testing::_, testing::Truly(CallClosure))); set_oob_function = setupFunction( new api::BluetoothSetOutOfBandPairingDataFunction); std::string error( utils::RunFunctionAndReturnError(set_oob_function, params, browser())); EXPECT_FALSE(error.empty()); // TODO(bryeung): Also test setting the data when there is support for // ArrayBuffers in the arguments to the RunFunctionAnd* methods. // crbug.com/132796 } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, Discovery) { // Try with a failure to start EXPECT_CALL(*mock_adapter_, IsDiscovering()).WillOnce(testing::Return(false)); EXPECT_CALL(*mock_adapter_, SetDiscovering(true, testing::_, testing::Truly(CallClosure))); scoped_refptr<api::BluetoothStartDiscoveryFunction> start_function; start_function = setupFunction(new api::BluetoothStartDiscoveryFunction); std::string error( utils::RunFunctionAndReturnError(start_function, "[]", browser())); ASSERT_TRUE(!error.empty()); // Reset for a successful start testing::Mock::VerifyAndClearExpectations(mock_adapter_); EXPECT_CALL(*mock_adapter_, IsDiscovering()).WillOnce(testing::Return(false)); EXPECT_CALL(*mock_adapter_, SetDiscovering(true, testing::Truly(CallClosure), testing::_)); start_function = setupFunction(new api::BluetoothStartDiscoveryFunction); (void)utils::RunFunctionAndReturnError(start_function, "[]", browser()); // Reset to try stopping testing::Mock::VerifyAndClearExpectations(mock_adapter_); EXPECT_CALL(*mock_adapter_, SetDiscovering(false, testing::Truly(CallClosure), testing::_)); scoped_refptr<api::BluetoothStopDiscoveryFunction> stop_function; stop_function = setupFunction(new api::BluetoothStopDiscoveryFunction); (void)utils::RunFunctionAndReturnSingleResult(stop_function, "[]", browser()); // Reset to try stopping with an error testing::Mock::VerifyAndClearExpectations(mock_adapter_); EXPECT_CALL(*mock_adapter_, SetDiscovering(false, testing::_, testing::Truly(CallClosure))); stop_function = setupFunction(new api::BluetoothStopDiscoveryFunction); error = utils::RunFunctionAndReturnError(stop_function, "[]", browser()); ASSERT_TRUE(!error.empty()); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DiscoveryCallback) { EXPECT_CALL(*mock_adapter_, IsDiscovering()).WillOnce(testing::Return(false)); EXPECT_CALL(*mock_adapter_, SetDiscovering(true, testing::Truly(CallClosure), testing::_)); EXPECT_CALL(*mock_adapter_, SetDiscovering(false, testing::Truly(CallClosure), testing::_)); ResultCatcher catcher; catcher.RestrictToProfile(browser()->profile()); ExtensionTestMessageListener discovery_started("ready", true); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bluetooth/discovery_callback"))); EXPECT_TRUE(discovery_started.WaitUntilSatisfied()); event_router()->DeviceAdded(mock_adapter_, device1_.get()); discovery_started.Reply("go"); ExtensionTestMessageListener discovery_stopped("ready", true); EXPECT_TRUE(discovery_stopped.WaitUntilSatisfied()); event_router()->DeviceAdded(mock_adapter_, device2_.get()); discovery_stopped.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DiscoveryInProgress) { // Fake that the adapter is discovering EXPECT_CALL(*mock_adapter_, IsDiscovering()).WillOnce(testing::Return(true)); event_router()->AdapterDiscoveringChanged(mock_adapter_, true); // Cache a device before the extension starts discovering event_router()->DeviceAdded(mock_adapter_, device1_.get()); ResultCatcher catcher; catcher.RestrictToProfile(browser()->profile()); ExtensionTestMessageListener discovery_started("ready", true); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bluetooth/discovery_in_progress"))); EXPECT_TRUE(discovery_started.WaitUntilSatisfied()); // This should be received in addition to the cached device above. event_router()->DeviceAdded(mock_adapter_, device2_.get()); discovery_started.Reply("go"); ExtensionTestMessageListener discovery_stopped("ready", true); EXPECT_TRUE(discovery_stopped.WaitUntilSatisfied()); // This should never be received. event_router()->DeviceAdded(mock_adapter_, device2_.get()); discovery_stopped.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, Events) { ResultCatcher catcher; catcher.RestrictToProfile(browser()->profile()); // Load and wait for setup ExtensionTestMessageListener listener("ready", true); ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("bluetooth/events"))); EXPECT_TRUE(listener.WaitUntilSatisfied()); event_router()->AdapterPoweredChanged(mock_adapter_, true); event_router()->AdapterPoweredChanged(mock_adapter_, false); event_router()->AdapterPresentChanged(mock_adapter_, true); event_router()->AdapterPresentChanged(mock_adapter_, false); event_router()->AdapterDiscoveringChanged(mock_adapter_, true); event_router()->AdapterDiscoveringChanged(mock_adapter_, false); listener.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevices) { ResultCatcher catcher; catcher.RestrictToProfile(browser()->profile()); BluetoothAdapter::ConstDeviceList devices; devices.push_back(device1_.get()); devices.push_back(device2_.get()); EXPECT_CALL(*device1_, ProvidesServiceWithUUID(testing::_)) .WillOnce(testing::Return(false)); EXPECT_CALL(*device1_, ProvidesServiceWithName(testing::_, testing::_)) .WillOnce(testing::Invoke(CallProvidesServiceCallback<true>)); EXPECT_CALL(*device2_, ProvidesServiceWithUUID(testing::_)) .WillOnce(testing::Return(true)); EXPECT_CALL(*device2_, ProvidesServiceWithName(testing::_, testing::_)) .WillOnce(testing::Invoke(CallProvidesServiceCallback<false>)); EXPECT_CALL(*mock_adapter_, GetDevices()) .Times(3) .WillRepeatedly(testing::Return(devices)); // Load and wait for setup ExtensionTestMessageListener listener("ready", true); ASSERT_TRUE( LoadExtension(test_data_dir_.AppendASCII("bluetooth/get_devices"))); EXPECT_TRUE(listener.WaitUntilSatisfied()); listener.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevicesConcurrently) { ResultCatcher catcher; catcher.RestrictToProfile(browser()->profile()); BluetoothAdapter::ConstDeviceList devices; devices.push_back(device1_.get()); // Save the callback to delay execution so that we can force the calls to // happen concurrently. This will be called after the listener is satisfied. BluetoothDevice::ProvidesServiceCallback callback; EXPECT_CALL(*device1_, ProvidesServiceWithName(testing::_, testing::_)) .WillOnce(testing::SaveArg<1>(&callback)); EXPECT_CALL(*mock_adapter_, GetDevices()) .WillOnce(testing::Return(devices)); // Load and wait for setup ExtensionTestMessageListener listener("ready", true); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bluetooth/get_devices_concurrently"))); EXPECT_TRUE(listener.WaitUntilSatisfied()); callback.Run(false); listener.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevicesError) { ResultCatcher catcher; catcher.RestrictToProfile(browser()->profile()); // Load and wait for setup ExtensionTestMessageListener listener("ready", true); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bluetooth/get_devices_error"))); EXPECT_TRUE(listener.WaitUntilSatisfied()); listener.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); }
{ "content_hash": "5c232e7ca85b81616d7e22312045731f", "timestamp": "", "source": "github", "line_count": 460, "max_line_length": 80, "avg_line_length": 37.73478260869565, "alnum_prop": 0.7209932019817952, "repo_name": "junmin-zhu/chromium-rivertrail", "id": "50452e7a7dba92197f398d8a2cb9ab45d8109bff", "size": "17358", "binary": false, "copies": "1", "ref": "refs/heads/v8-binding", "path": "chrome/browser/extensions/api/bluetooth/bluetooth_apitest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1172794" }, { "name": "Awk", "bytes": "9519" }, { "name": "C", "bytes": "75806807" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "145161929" }, { "name": "DOT", "bytes": "1559" }, { "name": "F#", "bytes": "381" }, { "name": "Java", "bytes": "1546515" }, { "name": "JavaScript", "bytes": "18675242" }, { "name": "Logos", "bytes": "4517" }, { "name": "Matlab", "bytes": "5234" }, { "name": "Objective-C", "bytes": "6981387" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "926245" }, { "name": "Python", "bytes": "8088373" }, { "name": "R", "bytes": "262" }, { "name": "Ragel in Ruby Host", "bytes": "3239" }, { "name": "Shell", "bytes": "1513486" }, { "name": "Tcl", "bytes": "277077" }, { "name": "XML", "bytes": "13493" } ], "symlink_target": "" }
var ws = require('websocket-stream'); var stream = ws('ws://localhost:8000'); stream.end('hello\n');
{ "content_hash": "cf6aaf3a8c2bf02682390f0103f233c9", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 39, "avg_line_length": 20.6, "alnum_prop": 0.6601941747572816, "repo_name": "Gurylev/nodeschool-solutions", "id": "b46ec4884352b1a4064bfd92036d53dbab31f608", "size": "103", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stream-adventure/websockets.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "140" }, { "name": "HTML", "bytes": "1562" }, { "name": "JavaScript", "bytes": "36630" } ], "symlink_target": "" }
package zhou.demo.spannable; import android.graphics.Color; import android.text.Spannable; import android.text.style.ForegroundColorSpan; /** * Created by Administrator on 2017/2/16 0016. */ public class DemoForegroundColorSpan extends BaseSpannablePage { @Override protected String getTitle() { return "ForegroundColorSpan"; } @Override protected String getInfo() { return "ForegroundColorSpan,文字颜色\n"; } @Override protected Spannable getSpannable() { return SpannableBuilder.from("蓝色字体\n红色字体\n黄色字体") .on("蓝色字体", new ForegroundColorSpan(Color.BLUE)) .on("红色字体", new ForegroundColorSpan(Color.RED)) .textColor("黄色字体", Color.YELLOW) .build(); } }
{ "content_hash": "9d0caab275f690ec1bbc2daa281cf9d5", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 64, "avg_line_length": 25.096774193548388, "alnum_prop": 0.6503856041131105, "repo_name": "cowthan/Ayo2022", "id": "a21e06fac3d01ae2af998d1eb0e86afdeb4920fe", "size": "836", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RichText/app/src/main/java/zhou/demo/spannable/DemoForegroundColorSpan.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5114" }, { "name": "HTML", "bytes": "2365" }, { "name": "Java", "bytes": "9575777" }, { "name": "JavaScript", "bytes": "27653" }, { "name": "Makefile", "bytes": "891" } ], "symlink_target": "" }
package com.cezarykluczynski.stapi.etl.template.species.processor; import com.cezarykluczynski.stapi.etl.common.dto.EnrichablePair; import com.cezarykluczynski.stapi.etl.common.processor.ItemEnrichingProcessor; import com.cezarykluczynski.stapi.etl.common.service.EntityLookupByNameService; import com.cezarykluczynski.stapi.etl.template.species.dto.SpeciesTemplate; import com.cezarykluczynski.stapi.etl.template.species.service.SpeciesTypeDetector; import com.cezarykluczynski.stapi.sources.mediawiki.api.enums.MediaWikiSource; import com.cezarykluczynski.stapi.sources.mediawiki.dto.Page; import com.cezarykluczynski.stapi.util.constant.PageTitle; import org.springframework.stereotype.Service; @Service public class SpeciesTemplateTypeEnrichingProcessor implements ItemEnrichingProcessor<EnrichablePair<Page, SpeciesTemplate>> { private static final MediaWikiSource SOURCE = MediaWikiSource.MEMORY_ALPHA_EN; private final SpeciesTypeDetector speciesTypeDetector; private final EntityLookupByNameService entityLookupByNameService; public SpeciesTemplateTypeEnrichingProcessor(SpeciesTypeDetector speciesTypeDetector, EntityLookupByNameService entityLookupByNameService) { this.speciesTypeDetector = speciesTypeDetector; this.entityLookupByNameService = entityLookupByNameService; } @Override public void enrich(EnrichablePair<Page, SpeciesTemplate> enrichablePair) throws Exception { SpeciesTemplate speciesTemplate = enrichablePair.getOutput(); Page page = enrichablePair.getInput(); if (speciesTypeDetector.isDeltaQuadrantSpecies(page)) { speciesTemplate.setQuadrant(entityLookupByNameService.findAstronomicalObjectByName(PageTitle.DELTA_QUADRANT, SOURCE).orElse(null)); } if (speciesTypeDetector.isGammaQuadrantSpecies(page)) { speciesTemplate.setQuadrant(entityLookupByNameService.findAstronomicalObjectByName(PageTitle.GAMMA_QUADRANT, SOURCE).orElse(null)); } speciesTemplate.setWarpCapableSpecies(speciesTypeDetector.isWarpCapableSpecies(page)); speciesTemplate.setExtraGalacticSpecies(speciesTypeDetector.isExtraGalacticSpecies(page)); speciesTemplate.setHumanoidSpecies(speciesTypeDetector.isHumanoidSpecies(page)); speciesTemplate.setReptilianSpecies(speciesTypeDetector.isReptilianSpecies(page)); speciesTemplate.setNonCorporealSpecies(speciesTypeDetector.isNonCorporealSpecies(page)); speciesTemplate.setShapeshiftingSpecies(speciesTypeDetector.isShapeshiftingSpecies(page)); speciesTemplate.setSpaceborneSpecies(speciesTypeDetector.isSpaceborneSpecies(page)); speciesTemplate.setTelepathicSpecies(speciesTypeDetector.isTelepathicSpecies(page)); speciesTemplate.setTransDimensionalSpecies(speciesTypeDetector.isTransDimensionalSpecies(page)); speciesTemplate.setUnnamedSpecies(speciesTypeDetector.isUnnamedSpecies(page)); } }
{ "content_hash": "9f5a1cbce502689bf679e0ce713fa60a", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 141, "avg_line_length": 53.86538461538461, "alnum_prop": 0.8639771510174937, "repo_name": "cezarykluczynski/stapi", "id": "cf368cff769bc06f2c59b147b3f3bfce832e1c61", "size": "2801", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "etl/src/main/java/com/cezarykluczynski/stapi/etl/template/species/processor/SpeciesTemplateTypeEnrichingProcessor.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "4357719" }, { "name": "HTML", "bytes": "31512" }, { "name": "Java", "bytes": "3370461" }, { "name": "JavaScript", "bytes": "5771" }, { "name": "Sass", "bytes": "3577" }, { "name": "TypeScript", "bytes": "138102" } ], "symlink_target": "" }
package pl.hycom.pip.messanger.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext; import lombok.extern.log4j.Log4j2; import pl.hycom.pip.messanger.MessengerRecommendationsApplication; /** * Created by piotr on 15.05.2017. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = MessengerRecommendationsApplication.class) @WebAppConfiguration @ContextConfiguration @ActiveProfiles({ "dev", "testdb" }) @Log4j2 public class GreetingControllerIntegrationTest { private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; @Before public void setUp() { this.mockMvc = webAppContextSetup(webApplicationContext).build(); } @Test public void removeGreetingTest() throws Exception { String locale = "pl_PL"; this.mockMvc.perform(delete("/admin/deleteGreeting/" + locale)) .andExpect(status().isFound()) .andExpect(view().name(GreetingController.REDIRECT_ADMIN_GREETINGS)); } }
{ "content_hash": "1c945881ddc118993e2b5f370e1cb3f8", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 92, "avg_line_length": 35.56603773584906, "alnum_prop": 0.7915119363395225, "repo_name": "Hycom-PIP/pip2017", "id": "867c50fde76a37a5b33d0f7843c2059db51501a8", "size": "1885", "binary": false, "copies": "1", "ref": "refs/heads/developer", "path": "src/test/java/pl/hycom/pip/messanger/controller/GreetingControllerIntegrationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "4673" }, { "name": "HTML", "bytes": "60705" }, { "name": "Java", "bytes": "248446" }, { "name": "JavaScript", "bytes": "13757" }, { "name": "Shell", "bytes": "7058" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>CodeRay output</title> <style type="text/css"> .CodeRay .line-numbers a { text-decoration: inherit; color: inherit; } body { background-color: white; padding: 0; margin: 0; } .CodeRay { background-color: hsl(0,0%,95%); border: 1px solid silver; color: black; } .CodeRay pre { margin: 0px; } span.CodeRay { white-space: pre; border: 0px; padding: 2px; } table.CodeRay { border-collapse: collapse; width: 100%; padding: 2px; } table.CodeRay td { padding: 2px 4px; vertical-align: top; } .CodeRay .line-numbers { background-color: hsl(180,65%,90%); color: gray; text-align: right; -webkit-user-select: none; -moz-user-select: none; user-select: none; } .CodeRay .line-numbers a { background-color: hsl(180,65%,90%) !important; color: gray !important; text-decoration: none !important; } .CodeRay .line-numbers pre { word-break: normal; } .CodeRay .line-numbers a:target { color: blue !important; } .CodeRay .line-numbers .highlighted { color: red !important; } .CodeRay .line-numbers .highlighted a { color: red !important; } .CodeRay span.line-numbers { padding: 0px 4px; } .CodeRay .line { display: block; float: left; width: 100%; } .CodeRay .code { width: 100%; } .CodeRay .debug { color: white !important; background: blue !important; } .CodeRay .annotation { color:#007 } .CodeRay .attribute-name { color:#b48 } .CodeRay .attribute-value { color:#700 } .CodeRay .binary { color:#549 } .CodeRay .binary .char { color:#325 } .CodeRay .binary .delimiter { color:#325 } .CodeRay .char { color:#D20 } .CodeRay .char .content { color:#D20 } .CodeRay .char .delimiter { color:#710 } .CodeRay .class { color:#B06; font-weight:bold } .CodeRay .class-variable { color:#369 } .CodeRay .color { color:#0A0 } .CodeRay .comment { color:#777 } .CodeRay .comment .char { color:#444 } .CodeRay .comment .delimiter { color:#444 } .CodeRay .constant { color:#036; font-weight:bold } .CodeRay .decorator { color:#B0B } .CodeRay .definition { color:#099; font-weight:bold } .CodeRay .delimiter { color:black } .CodeRay .directive { color:#088; font-weight:bold } .CodeRay .docstring { color:#D42; } .CodeRay .doctype { color:#34b } .CodeRay .done { text-decoration: line-through; color: gray } .CodeRay .entity { color:#800; font-weight:bold } .CodeRay .error { color:#F00; background-color:#FAA } .CodeRay .escape { color:#666 } .CodeRay .exception { color:#C00; font-weight:bold } .CodeRay .float { color:#60E } .CodeRay .function { color:#06B; font-weight:bold } .CodeRay .function .delimiter { color:#024; font-weight:bold } .CodeRay .global-variable { color:#d70 } .CodeRay .hex { color:#02b } .CodeRay .id { color:#33D; font-weight:bold } .CodeRay .include { color:#B44; font-weight:bold } .CodeRay .inline { background-color: hsla(0,0%,0%,0.07); color: black } .CodeRay .inline-delimiter { font-weight: bold; color: #666 } .CodeRay .instance-variable { color:#33B } .CodeRay .integer { color:#00D } .CodeRay .imaginary { color:#f00 } .CodeRay .important { color:#D00 } .CodeRay .key { color: #606 } .CodeRay .key .char { color: #60f } .CodeRay .key .delimiter { color: #404 } .CodeRay .keyword { color:#080; font-weight:bold } .CodeRay .label { color:#970; font-weight:bold } .CodeRay .local-variable { color:#950 } .CodeRay .map .content { color:#808 } .CodeRay .map .delimiter { color:#40A} .CodeRay .map { background-color:hsla(200,100%,50%,0.06); } .CodeRay .namespace { color:#707; font-weight:bold } .CodeRay .octal { color:#40E } .CodeRay .operator { } .CodeRay .predefined { color:#369; font-weight:bold } .CodeRay .predefined-constant { color:#069 } .CodeRay .predefined-type { color:#0a8; font-weight:bold } .CodeRay .preprocessor { color:#579 } .CodeRay .pseudo-class { color:#00C; font-weight:bold } .CodeRay .regexp { background-color:hsla(300,100%,50%,0.06); } .CodeRay .regexp .content { color:#808 } .CodeRay .regexp .delimiter { color:#404 } .CodeRay .regexp .modifier { color:#C2C } .CodeRay .reserved { color:#080; font-weight:bold } .CodeRay .shell { background-color:hsla(120,100%,50%,0.06); } .CodeRay .shell .content { color:#2B2 } .CodeRay .shell .delimiter { color:#161 } .CodeRay .string { background-color:hsla(0,100%,50%,0.05); } .CodeRay .string .char { color: #b0b } .CodeRay .string .content { color: #D20 } .CodeRay .string .delimiter { color: #710 } .CodeRay .string .modifier { color: #E40 } .CodeRay .symbol { color:#A60 } .CodeRay .symbol .content { color:#A60 } .CodeRay .symbol .delimiter { color:#740 } .CodeRay .tag { color:#070; font-weight:bold } .CodeRay .type { color:#339; font-weight:bold } .CodeRay .value { color: #088 } .CodeRay .variable { color:#037 } .CodeRay .insert { background: hsla(120,100%,50%,0.12) } .CodeRay .delete { background: hsla(0,100%,50%,0.12) } .CodeRay .change { color: #bbf; background: #007 } .CodeRay .head { color: #f8f; background: #505 } .CodeRay .head .filename { color: white; } .CodeRay .delete .eyecatcher { background-color: hsla(0,100%,50%,0.2); border: 1px solid hsla(0,100%,45%,0.5); margin: -1px; border-bottom: none; border-top-left-radius: 5px; border-top-right-radius: 5px; } .CodeRay .insert .eyecatcher { background-color: hsla(120,100%,50%,0.2); border: 1px solid hsla(120,100%,25%,0.5); margin: -1px; border-top: none; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; } .CodeRay .insert .insert { color: #0c0; background:transparent; font-weight:bold } .CodeRay .delete .delete { color: #c00; background:transparent; font-weight:bold } .CodeRay .change .change { color: #88f } .CodeRay .head .head { color: #f4f } .CodeRay { border: none; } </style> </head> <body> <table class="CodeRay"><tr> <td class="line-numbers"><pre><a href="#n1" name="n1">1</a> <a href="#n2" name="n2">2</a> <a href="#n3" name="n3">3</a> <a href="#n4" name="n4">4</a> <a href="#n5" name="n5">5</a> <a href="#n6" name="n6">6</a> <a href="#n7" name="n7">7</a> <a href="#n8" name="n8">8</a> <a href="#n9" name="n9">9</a> <strong><a href="#n10" name="n10">10</a></strong> <a href="#n11" name="n11">11</a> <a href="#n12" name="n12">12</a> <a href="#n13" name="n13">13</a> <a href="#n14" name="n14">14</a> <a href="#n15" name="n15">15</a> <a href="#n16" name="n16">16</a> <a href="#n17" name="n17">17</a> <a href="#n18" name="n18">18</a> <a href="#n19" name="n19">19</a> <strong><a href="#n20" name="n20">20</a></strong> <a href="#n21" name="n21">21</a> <a href="#n22" name="n22">22</a> <a href="#n23" name="n23">23</a> <a href="#n24" name="n24">24</a> <a href="#n25" name="n25">25</a> <a href="#n26" name="n26">26</a> <a href="#n27" name="n27">27</a> <a href="#n28" name="n28">28</a> <a href="#n29" name="n29">29</a> <strong><a href="#n30" name="n30">30</a></strong> <a href="#n31" name="n31">31</a> <a href="#n32" name="n32">32</a> <a href="#n33" name="n33">33</a> <a href="#n34" name="n34">34</a> <a href="#n35" name="n35">35</a> <a href="#n36" name="n36">36</a> <a href="#n37" name="n37">37</a> <a href="#n38" name="n38">38</a> <a href="#n39" name="n39">39</a> <strong><a href="#n40" name="n40">40</a></strong> <a href="#n41" name="n41">41</a> <a href="#n42" name="n42">42</a> <a href="#n43" name="n43">43</a> <a href="#n44" name="n44">44</a> <a href="#n45" name="n45">45</a> <a href="#n46" name="n46">46</a> <a href="#n47" name="n47">47</a> <a href="#n48" name="n48">48</a> <a href="#n49" name="n49">49</a> <strong><a href="#n50" name="n50">50</a></strong> <a href="#n51" name="n51">51</a> <a href="#n52" name="n52">52</a> <a href="#n53" name="n53">53</a> <a href="#n54" name="n54">54</a> <a href="#n55" name="n55">55</a> <a href="#n56" name="n56">56</a> <a href="#n57" name="n57">57</a> <a href="#n58" name="n58">58</a> <a href="#n59" name="n59">59</a> <strong><a href="#n60" name="n60">60</a></strong> <a href="#n61" name="n61">61</a> <a href="#n62" name="n62">62</a> <a href="#n63" name="n63">63</a> <a href="#n64" name="n64">64</a> <a href="#n65" name="n65">65</a> <a href="#n66" name="n66">66</a> <a href="#n67" name="n67">67</a> <a href="#n68" name="n68">68</a> <a href="#n69" name="n69">69</a> <strong><a href="#n70" name="n70">70</a></strong> <a href="#n71" name="n71">71</a> <a href="#n72" name="n72">72</a> <a href="#n73" name="n73">73</a> <a href="#n74" name="n74">74</a> <a href="#n75" name="n75">75</a> <a href="#n76" name="n76">76</a> <a href="#n77" name="n77">77</a> <a href="#n78" name="n78">78</a> <a href="#n79" name="n79">79</a> <strong><a href="#n80" name="n80">80</a></strong> <a href="#n81" name="n81">81</a> <a href="#n82" name="n82">82</a> <a href="#n83" name="n83">83</a> <a href="#n84" name="n84">84</a> <a href="#n85" name="n85">85</a> <a href="#n86" name="n86">86</a> <a href="#n87" name="n87">87</a> <a href="#n88" name="n88">88</a> <a href="#n89" name="n89">89</a> <strong><a href="#n90" name="n90">90</a></strong> <a href="#n91" name="n91">91</a> <a href="#n92" name="n92">92</a> <a href="#n93" name="n93">93</a> <a href="#n94" name="n94">94</a> <a href="#n95" name="n95">95</a> <a href="#n96" name="n96">96</a> <a href="#n97" name="n97">97</a> <a href="#n98" name="n98">98</a> <a href="#n99" name="n99">99</a> <strong><a href="#n100" name="n100">100</a></strong> <a href="#n101" name="n101">101</a> <a href="#n102" name="n102">102</a> <a href="#n103" name="n103">103</a> <a href="#n104" name="n104">104</a> <a href="#n105" name="n105">105</a> <a href="#n106" name="n106">106</a> <a href="#n107" name="n107">107</a> <a href="#n108" name="n108">108</a> <a href="#n109" name="n109">109</a> <strong><a href="#n110" name="n110">110</a></strong> <a href="#n111" name="n111">111</a> <a href="#n112" name="n112">112</a> <a href="#n113" name="n113">113</a> <a href="#n114" name="n114">114</a> <a href="#n115" name="n115">115</a> <a href="#n116" name="n116">116</a> <a href="#n117" name="n117">117</a> <a href="#n118" name="n118">118</a> <a href="#n119" name="n119">119</a> <strong><a href="#n120" name="n120">120</a></strong> <a href="#n121" name="n121">121</a> <a href="#n122" name="n122">122</a> <a href="#n123" name="n123">123</a> <a href="#n124" name="n124">124</a> <a href="#n125" name="n125">125</a> <a href="#n126" name="n126">126</a> <a href="#n127" name="n127">127</a> <a href="#n128" name="n128">128</a> <a href="#n129" name="n129">129</a> <strong><a href="#n130" name="n130">130</a></strong> <a href="#n131" name="n131">131</a> <a href="#n132" name="n132">132</a> <a href="#n133" name="n133">133</a> <a href="#n134" name="n134">134</a> <a href="#n135" name="n135">135</a> <a href="#n136" name="n136">136</a> <a href="#n137" name="n137">137</a> <a href="#n138" name="n138">138</a> <a href="#n139" name="n139">139</a> <strong><a href="#n140" name="n140">140</a></strong> <a href="#n141" name="n141">141</a> <a href="#n142" name="n142">142</a> <a href="#n143" name="n143">143</a> <a href="#n144" name="n144">144</a> <a href="#n145" name="n145">145</a> <a href="#n146" name="n146">146</a> <a href="#n147" name="n147">147</a> <a href="#n148" name="n148">148</a> <a href="#n149" name="n149">149</a> <strong><a href="#n150" name="n150">150</a></strong> <a href="#n151" name="n151">151</a> <a href="#n152" name="n152">152</a> <a href="#n153" name="n153">153</a> <a href="#n154" name="n154">154</a> <a href="#n155" name="n155">155</a> <a href="#n156" name="n156">156</a> <a href="#n157" name="n157">157</a> <a href="#n158" name="n158">158</a> <a href="#n159" name="n159">159</a> <strong><a href="#n160" name="n160">160</a></strong> <a href="#n161" name="n161">161</a> <a href="#n162" name="n162">162</a> <a href="#n163" name="n163">163</a> <a href="#n164" name="n164">164</a> <a href="#n165" name="n165">165</a> <a href="#n166" name="n166">166</a> <a href="#n167" name="n167">167</a> <a href="#n168" name="n168">168</a> <a href="#n169" name="n169">169</a> <strong><a href="#n170" name="n170">170</a></strong> <a href="#n171" name="n171">171</a> <a href="#n172" name="n172">172</a> <a href="#n173" name="n173">173</a> <a href="#n174" name="n174">174</a> <a href="#n175" name="n175">175</a> <a href="#n176" name="n176">176</a> <a href="#n177" name="n177">177</a> <a href="#n178" name="n178">178</a> <a href="#n179" name="n179">179</a> <strong><a href="#n180" name="n180">180</a></strong> <a href="#n181" name="n181">181</a> <a href="#n182" name="n182">182</a> <a href="#n183" name="n183">183</a> <a href="#n184" name="n184">184</a> <a href="#n185" name="n185">185</a> <a href="#n186" name="n186">186</a> <a href="#n187" name="n187">187</a> <a href="#n188" name="n188">188</a> <a href="#n189" name="n189">189</a> <strong><a href="#n190" name="n190">190</a></strong> <a href="#n191" name="n191">191</a> <a href="#n192" name="n192">192</a> <a href="#n193" name="n193">193</a> <a href="#n194" name="n194">194</a> <a href="#n195" name="n195">195</a> <a href="#n196" name="n196">196</a> <a href="#n197" name="n197">197</a> <a href="#n198" name="n198">198</a> <a href="#n199" name="n199">199</a> <strong><a href="#n200" name="n200">200</a></strong> <a href="#n201" name="n201">201</a> <a href="#n202" name="n202">202</a> <a href="#n203" name="n203">203</a> <a href="#n204" name="n204">204</a> <a href="#n205" name="n205">205</a> <a href="#n206" name="n206">206</a> <a href="#n207" name="n207">207</a> <a href="#n208" name="n208">208</a> <a href="#n209" name="n209">209</a> <strong><a href="#n210" name="n210">210</a></strong> <a href="#n211" name="n211">211</a> <a href="#n212" name="n212">212</a> <a href="#n213" name="n213">213</a> <a href="#n214" name="n214">214</a> <a href="#n215" name="n215">215</a> <a href="#n216" name="n216">216</a> <a href="#n217" name="n217">217</a> <a href="#n218" name="n218">218</a> <a href="#n219" name="n219">219</a> <strong><a href="#n220" name="n220">220</a></strong> <a href="#n221" name="n221">221</a> <a href="#n222" name="n222">222</a> <a href="#n223" name="n223">223</a> <a href="#n224" name="n224">224</a> <a href="#n225" name="n225">225</a> <a href="#n226" name="n226">226</a> <a href="#n227" name="n227">227</a> <a href="#n228" name="n228">228</a> <a href="#n229" name="n229">229</a> <strong><a href="#n230" name="n230">230</a></strong> <a href="#n231" name="n231">231</a> <a href="#n232" name="n232">232</a> <a href="#n233" name="n233">233</a> <a href="#n234" name="n234">234</a> <a href="#n235" name="n235">235</a> </pre></td> <td class="code"><pre><span class="comment">&lt;!-- Copyright 2015-2016 Teem2 LLC. Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); 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 &quot;AS IS&quot; 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. --&gt;</span> <span class="comment">&lt;!--/** * @class dr.alignlayout {Layout} * @extends dr.variablelayout * A variablelayout that aligns each view vertically or horizontally * relative to all the other views. * * If updateparent is true the parent will be sized to fit the * aligned views such that the view with the greatest extent will have * a position of 0. If instead updateparent is false the views will * be aligned within the inner extent of the parent view. * * @example * &lt;alignlayout align=&quot;middle&quot; updateparent=&quot;true&quot;&gt;&lt;/alignlayout&gt; * * &lt;view x=&quot;0&quot; width=&quot;50&quot; height=&quot;35&quot; bgcolor=&quot;plum&quot;&gt;&lt;/view&gt; * &lt;view x=&quot;55&quot; width=&quot;50&quot; height=&quot;25&quot; bgcolor=&quot;lightpink&quot;&gt;&lt;/view&gt; * &lt;view x=&quot;110&quot; width=&quot;50&quot; height=&quot;15&quot; bgcolor=&quot;lightblue&quot;&gt;&lt;/view&gt; */--&gt;</span> <span class="tag">&lt;class</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">alignlayout</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">extends</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">variablelayout</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">coffee</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> <span class="comment">&lt;!--/** * @attribute {String} [axis=''] * The orientation of the layout. Supported values are 'x' and 'y' and ''. * A value of 'x' will restrict align values to 'left', 'center' and 'right'. * A value of 'y' will restrict align values to 'top', 'middle' and 'bottom'. * An empty/null value will not restrict the align values. */--&gt;</span> <span class="tag">&lt;attribute</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">axis</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">string</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span><span class="tag">&lt;/attribute&gt;</span> <span class="tag">&lt;setter</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">axis</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">axis</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> @setActual('axis', axis, 'string', '') @setAttribute('align', @align) <span class="tag">&lt;/setter&gt;</span> <span class="comment">&lt;!--/** * @attribute {String} [align='middle'] * Determines which way the views are aligned. Supported values are * 'left', 'center', 'right' for horizontal alignment and 'top', 'middle' * and 'bottom' for vertical alignment. */--&gt;</span> <span class="tag">&lt;attribute</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">align</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">string</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">middle</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span><span class="tag">&lt;/attribute&gt;</span> <span class="tag">&lt;setter</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">align</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">align</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> if @align isnt align # Stop monitoring since we may end up changing the axis. This needs to # be done before the new align value is set since stopMonitoringSubview # needs to know the old values. @stopMonitoringAllSubviews() switch @axis when 'x' if align is 'top' then align = 'left' else if align is 'middle' then align = 'center' else if align is 'bottom' then align = 'right' when 'y' if align is 'left' then align = 'top' else if align is 'center' then align = 'middle' else if align is 'right' then align = 'bottom' # Setup private attributes based on axis switch align when 'left', 'center', 'right' # The layout is oriented horizontally @__parentAttrName = 'width' # The attr to update on the parent if updateparent is true @__innerAttrName = 'innerwidth' # The attr used to get available space @__measureAttrName = 'boundswidth' # The attr to measure the size needed for a subview @__diffAttrName = 'boundsxdiff' # The attr used to offset the position of a transformed subview so it will appear to be aligned @__setterAttrName = 'x' # The attr to set on a subview to position it @__alignattr = 'isaligned' # The attr on a subview to determine if it is aligning itself and should thus be ignored. when 'top', 'middle', 'bottom' # The layout is oriented vertically @__parentAttrName = 'height' @__innerAttrName = 'innerheight' @__measureAttrName = 'boundsheight' @__diffAttrName = 'boundsydiff' @__setterAttrName = 'y' @__alignattr = 'isvaligned' @setActual('align', align, 'string') if @inited # Start monitoring again and update since we have new alignment. This needs # to be done after the new align value is set since startMonitoringSubview # needs to use the new values. @startMonitoringAllSubviews() @update() else @__redoMonitoring = true <span class="tag">&lt;/setter&gt;</span> <span class="comment">&lt;!--/** * @attribute {boolean} [inset=0] * Determines if the parent will be sized to fit the aligned views such * that the view with the greatest extent will have a position of 0. If * instead updateparent is false the views will be aligned within the * inner extent of the parent view. */--&gt;</span> <span class="tag">&lt;setter</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">updateparent</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">updateparent</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> if @updateparent isnt updateparent # Stop monitoring since we will have different updateparent behavior @stopMonitoringAllSubviews() @setActual('updateparent', updateparent, 'boolean') if @inited # Start monitoring again and update since we have new updateparent # behavior @startMonitoringAllSubviews() else @__redoMonitoring = true <span class="tag">&lt;/setter&gt;</span> <span class="tag">&lt;handler</span> <span class="attribute-name">event</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">oninit</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> if @__redoMonitoring @stopMonitoringAllSubviews() @startMonitoringAllSubviews() <span class="tag">&lt;/handler&gt;</span> <span class="tag">&lt;method</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">stopMonitoringAllSubviews</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">view</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> @super() # When not collapsing we were monitoring the parent's inner measure # Also verify that __innerAttrName exists, otherwise stopListening will # clear all the listeners. if not @updateparent and @__innerAttrName? then @stopListening(@parent, 'on' + @__innerAttrName, @update) <span class="tag">&lt;/method&gt;</span> <span class="tag">&lt;method</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">startMonitoringAllSubviews</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">view</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> @super() # When not collapsing we need to monitor the parent's inner measure if not @updateparent then @listenTo(@parent, 'on' + @__innerAttrName, @update) <span class="tag">&lt;/method&gt;</span> <span class="tag">&lt;method</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">startMonitoringSubview</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">view</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> @super() # Monitor each subview's measure, bounds offset and self alignment state @listenTo(view, 'on' + @__measureAttrName, @update) @listenTo(view, 'on' + @__diffAttrName, @update) @listenTo(view, 'on' + @__alignattr, @update) <span class="tag">&lt;/method&gt;</span> <span class="tag">&lt;method</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">stopMonitoringSubview</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">view</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> @super() # No longer monitor each subview's measure, bounds offset and self # alignment state @stopListening(view, 'on' + @__measureAttrName, @update) @stopListening(view, 'on' + @__diffAttrName, @update) @stopListening(view, 'on' + @__alignattr, @update) <span class="tag">&lt;/method&gt;</span> <span class="tag">&lt;method</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">skipSubview</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">view</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> # Don't position subviews that are handling their own alignment if view[@__alignattr] then return true # Use visibility as well return @super() <span class="tag">&lt;/method&gt;</span> <span class="comment">&lt;!--/** * @method doBeforeUpdate * Determine the maximum subview width/height according to the alignment. * This is only necessary if updateparent is true since we will need to * know what size to make the parent as well as what size to align the * subviews within. */--&gt;</span> <span class="tag">&lt;method</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">doBeforeUpdate</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> if @updateparent # Walk all the subviews to determine the largest size needed to fit # them all. measureAttrName = @__measureAttrName svs = @subviews i = svs.length value = 0 while i sv = svs[--i] if @skipSubview(sv) then continue value = Math.max(value, sv[measureAttrName]) # Convert invalid values into a size of 0 if isNaN(value) or 0 <span class="error">&gt;</span>= value then value = 0 # Store the value to use for alignment @setAttribute('value', value) <span class="tag">&lt;/method&gt;</span> <span class="tag">&lt;method</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">updateSubview</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">count, view, attribute, value</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> switch @align when 'center','middle' if @updateparent actualVal = (value - view[@__measureAttrName]) / 2 else actualVal = (@parent[@__innerAttrName] - view[@__measureAttrName]) / 2 when 'right','bottom' if @updateparent actualVal = value - view[@__measureAttrName] else actualVal = @parent[@__innerAttrName] - view[@__measureAttrName] else actualVal = 0 @__positionView(view, @__setterAttrName, view[@__diffAttrName] + actualVal) return value <span class="tag">&lt;/method&gt;</span> <span class="tag">&lt;method</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">updateParent</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">attribute, value, count</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> # Resize the parent and allow for the difference between innersize and size # due to border and padding. parent = @parent @__positionView(parent, @__parentAttrName, value + parent[@__parentAttrName] - parent[@__innerAttrName]) <span class="tag">&lt;/method&gt;</span> <span class="comment">&lt;!--// Editor //--&gt;</span> <span class="tag">&lt;method</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">__getLayoutDomains</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> retval = {} retval[@axis] = true return retval <span class="tag">&lt;/method&gt;</span> <span class="tag">&lt;method</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">__getLayoutParentDomains</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span> retval = {} retval[@__parentAttrName] = true return retval <span class="tag">&lt;/method&gt;</span> <span class="tag">&lt;attribute</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">hiddenattrs</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">expression</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">{attribute:true, value:true, reverse:true}</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">allocation</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">class</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span> <span class="tag">&lt;attribute</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">readonlyattrs</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">expression</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">{axis:true}</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">allocation</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">class</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span> <span class="tag">&lt;attribute</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">attrimportance</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">expression</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">allocation</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">class</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">{axis:-2, name:-1, align:1, updateparent:2, speed:3}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span> <span class="tag">&lt;/class&gt;</span> </pre></td> </tr></table> </body> </html>
{ "content_hash": "b9019f744cb5aea81e306a45caaac107", "timestamp": "", "source": "github", "line_count": 630, "max_line_length": 837, "avg_line_length": 53.01587301587302, "alnum_prop": 0.6470059880239521, "repo_name": "teem2/dreem2", "id": "61b0f024fdf0ca02459886fb2416226b4e6edb7b", "size": "33400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/source/alignlayout.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "6708" }, { "name": "JavaScript", "bytes": "1413757" }, { "name": "Ruby", "bytes": "3163" }, { "name": "Shell", "bytes": "1651" } ], "symlink_target": "" }
function bulletinEditor(collectionId, data) { var newChart = [], newTable = [], newEquation = [], newImage = [], newLinks = [], newFiles = []; var setActiveTab, getActiveTab; var renameUri = false; $(".edit-accordion").on('accordionactivate', function (event, ui) { setActiveTab = $(".edit-accordion").accordion("option", "active"); if (setActiveTab !== false) { Florence.globalVars.activeTab = setActiveTab; } }); getActiveTab = Florence.globalVars.activeTab; accordion(getActiveTab); getLastPosition(); // Metadata load, edition and saving $("#title").on('input', function () { renameUri = true; $(this).textareaAutoSize(); data.description.title = $(this).val(); }); $("#edition").on('input', function () { renameUri = true; $(this).textareaAutoSize(); data.description.edition = $(this).val(); }); if (!data.description.releaseDate) { $('#releaseDate').datepicker({dateFormat: 'dd MM yy'}).on('change', function () { data.description.releaseDate = new Date($(this).datepicker({dateFormat: 'dd MM yy'})[0].value).toISOString(); }); } else { dateTmp = data.description.releaseDate; var dateTmpFormatted = $.datepicker.formatDate('dd MM yy', new Date(dateTmp)); $('#releaseDate').val(dateTmpFormatted).datepicker({dateFormat: 'dd MM yy'}).on('change', function () { data.description.releaseDate = new Date($('#releaseDate').datepicker('getDate')).toISOString(); }); } $("#nextRelease").on('input', function () { $(this).textareaAutoSize(); data.description.nextRelease = $(this).val(); }); if (!data.description.contact) { data.description.contact = {}; } $("#contactName").on('input', function () { $(this).textareaAutoSize(); data.description.contact.name = $(this).val(); }); $("#contactEmail").on('input', function () { $(this).textareaAutoSize(); data.description.contact.email = $(this).val(); }); $("#contactTelephone").on('input', function () { $(this).textareaAutoSize(); data.description.contact.telephone = $(this).val(); }); $("#summary").on('input', function () { $(this).textareaAutoSize(); data.description.summary = $(this).val(); }); $("#headline1").on('input', function () { $(this).textareaAutoSize(); data.description.headline1 = $(this).val(); }); $("#headline2").on('input', function () { $(this).textareaAutoSize(); data.description.headline2 = $(this).val(); }); $("#headline3").on('input', function () { $(this).textareaAutoSize(); data.description.headline3 = $(this).val(); }); $("#keywordsTag").tagit({ availableTags: data.description.keywords, singleField: true, allowSpaces: true, singleFieldNode: $('#keywords') }); $('#keywords').on('change', function () { data.description.keywords = $('#keywords').val().split(','); }); $("#metaDescription").on('input', function () { $(this).textareaAutoSize(); data.description.metaDescription = $(this).val(); }); /* The checked attribute is a boolean attribute and the corresponding property will be true if the attribute is present and has a value other than false */ var checkBoxStatus = function (value) { if (value === "" || value === "false" || value === false) { return false; } return true; }; $("#natStat-checkbox").prop('checked', checkBoxStatus(data.description.nationalStatistic)).click(function () { data.description.nationalStatistic = $("#natStat-checkbox").prop('checked'); }); $("#census-checkbox").prop('checked', data.description.survey ? true : false).click(function () { data.description.survey = $("#census-checkbox").prop('checked') ? 'census' : null; }); // Save var editNav = $('.edit-nav'); editNav.off(); // remove any existing event handlers. editNav.on('click', '.btn-edit-save', function () { save(updateContent); }); // completed to review editNav.on('click', '.btn-edit-save-and-submit-for-review', function () { save(saveAndCompleteContent); }); // reviewed to approve editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () { save(saveAndReviewContent); }); function save(onSave) { Florence.globalVars.pagePos = $(".workspace-edit").scrollTop(); // charts var orderChart = $("#sortable-chart").sortable('toArray'); $(orderChart).each(function (indexCh, nameCh) { var uri = data.charts[parseInt(nameCh)].uri; var title = data.charts[parseInt(nameCh)].title; var filename = data.charts[parseInt(nameCh)].filename; var safeUri = checkPathSlashes(uri); newChart[indexCh] = {uri: safeUri, title: title, filename: filename}; }); data.charts = newChart; // tables var orderTable = $("#sortable-table").sortable('toArray'); $(orderTable).each(function (indexTable, nameTable) { var uri = data.tables[parseInt(nameTable)].uri; var title = data.tables[parseInt(nameTable)].title; var filename = data.tables[parseInt(nameTable)].filename; var version = data.tables[parseInt(nameTable)].version; var safeUri = checkPathSlashes(uri); newTable[indexTable] = {uri: safeUri, title: title, filename: filename, version: version}; }); data.tables = newTable; // equations var orderEquation = $("#sortable-equation").sortable('toArray'); $(orderEquation).each(function (indexEquation, nameEquation) { var uri = data.equations[parseInt(nameEquation)].uri; var title = data.equations[parseInt(nameEquation)].title; var filename = data.equations[parseInt(nameEquation)].filename; var safeUri = checkPathSlashes(uri); newEquation[indexEquation] = {uri: safeUri, title: title, filename: filename}; }); data.equations = newEquation; // images var orderImage = $("#sortable-image").sortable('toArray'); $(orderImage).each(function (indexImage, nameImage) { var uri = data.images[parseInt(nameImage)].uri; var title = data.images[parseInt(nameImage)].title; var filename = data.images[parseInt(nameImage)].filename; var safeUri = checkPathSlashes(uri); newImage[indexImage] = {uri: safeUri, title: title, filename: filename}; }); data.images = newImage; // External links var orderLink = $("#sortable-link").sortable('toArray'); $(orderLink).each(function (indexL, nameL) { var displayText = data.links[parseInt(nameL)].title; var link = $('#link-uri_' + nameL).val(); newLinks[indexL] = {uri: link, title: displayText}; }); data.links = newLinks; // Files are uploaded. Save metadata var orderFile = $("#sortable-pdf").sortable('toArray'); $(orderFile).each(function (indexF, nameF) { var title = $('#pdf-title_' + nameF).val(); var file = data.pdfTable[parseInt(nameF)].file; newFiles[indexF] = {title: title, file: file}; }); data.pdfTable = newFiles; // tags if ($("#selectTopic").val() && $("#selectSubTopic").val()) { data.description.canonicalTopic = $("#selectTopic").val()[0] data.description.secondaryTopics = $("#selectSubTopic").val() } else if ($("#selectTopic").val() && !$("#selectSubTopic").val()) { sweetAlert("Cannot save this page", "A value is required for 'Subtopic' if a 'Topic' has been selected"); return } checkRenameUri(collectionId, data, renameUri, onSave); } }
{ "content_hash": "4faccf45f8237d42867f51cc39e3b9bf", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 121, "avg_line_length": 40.54726368159204, "alnum_prop": 0.5828220858895705, "repo_name": "ONSdigital/florence", "id": "841eba410d639886d7657eede102087ef9ea1660", "size": "8150", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/legacy/js/functions/_t4BulletinEditor.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5324" }, { "name": "Dockerfile", "bytes": "105" }, { "name": "Gherkin", "bytes": "2144" }, { "name": "Go", "bytes": "81514" }, { "name": "HCL", "bytes": "1584" }, { "name": "HTML", "bytes": "31472" }, { "name": "Handlebars", "bytes": "202007" }, { "name": "JavaScript", "bytes": "5340465" }, { "name": "Makefile", "bytes": "2516" }, { "name": "SCSS", "bytes": "233265" }, { "name": "Shell", "bytes": "422" } ], "symlink_target": "" }
package thaumicenergistics.integration.appeng.cell; import javax.annotation.Nullable; import net.minecraft.item.ItemStack; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.IncludeExclude; import appeng.api.networking.security.IActionSource; import appeng.api.storage.ICellInventory; import appeng.api.storage.ICellInventoryHandler; import appeng.api.storage.ISaveProvider; import appeng.api.storage.IStorageChannel; import appeng.api.storage.data.IItemList; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.storage.IAEEssentiaStack; import thaumicenergistics.api.storage.IEssentiaStorageChannel; import thaumicenergistics.integration.appeng.EssentiaList; import thaumicenergistics.util.AEUtil; /** * @author BrockWS */ public class CreativeEssentiaCellInventory implements ICellInventoryHandler<IAEEssentiaStack> { private IItemList<IAEEssentiaStack> storedAspects = new EssentiaList(); private CreativeEssentiaCellInventory() { Aspect.aspects.forEach((s, aspect) -> storedAspects.add(AEUtil.getAEStackFromAspect(aspect, 1000))); } public static ICellInventoryHandler getCell(ItemStack s, ISaveProvider c) { return new CreativeEssentiaCellInventory(); } @Nullable @Override public ICellInventory<IAEEssentiaStack> getCellInv() { return null; } @Override public boolean isPreformatted() { return false; } @Override public boolean isFuzzy() { return false; } @Override public IncludeExclude getIncludeExcludeMode() { return IncludeExclude.WHITELIST; } @Override public AccessRestriction getAccess() { return AccessRestriction.READ_WRITE; } @Override public boolean isPrioritized(IAEEssentiaStack iaeEssentiaStack) { return false; } @Override public boolean canAccept(IAEEssentiaStack iaeEssentiaStack) { return true; } @Override public int getPriority() { return 0; } @Override public int getSlot() { return 0; } @Override public boolean validForPass(int i) { return true; } @Override public IAEEssentiaStack injectItems(IAEEssentiaStack stack, Actionable actionable, IActionSource src) { return null; } @Override public IAEEssentiaStack extractItems(IAEEssentiaStack stack, Actionable actionable, IActionSource src) { return stack.copy(); } @Override public IItemList<IAEEssentiaStack> getAvailableItems(IItemList<IAEEssentiaStack> list) { this.storedAspects.forEach(list::add); return list; } @Override public IStorageChannel<IAEEssentiaStack> getChannel() { return AEUtil.getStorageChannel(IEssentiaStorageChannel.class); } }
{ "content_hash": "c748e01d291ae24720d0e44fcd9fb76d", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 108, "avg_line_length": 26.963636363636365, "alnum_prop": 0.6992582602832097, "repo_name": "Nividica/ThaumicEnergistics", "id": "f67b6b1c103936b3364d8d9c250d97a741dd7bfb", "size": "2966", "binary": false, "copies": "1", "ref": "refs/heads/AE2-RV6", "path": "src/main/java/thaumicenergistics/integration/appeng/cell/CreativeEssentiaCellInventory.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "378381" } ], "symlink_target": "" }
import org.scalatestplus.play._ class IntegrationSpec extends PlaySpec with OneServerPerTest with OneBrowserPerTest with HtmlUnitFactory { // TODO: Write integration spec }
{ "content_hash": "77db0184d892a9a74f6fb9c66a89ebb7", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 106, "avg_line_length": 22.375, "alnum_prop": 0.8100558659217877, "repo_name": "builtamont-oss/play2-scala-pdf", "id": "1f3e1df589ed1c3b3ffcaa49048a4d03521f92a7", "size": "1512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/play25/test/IntegrationSpec.scala", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4068" }, { "name": "HTML", "bytes": "5775" }, { "name": "Scala", "bytes": "78301" }, { "name": "Shell", "bytes": "2553" } ], "symlink_target": "" }
package gui.javafx; import javafx.application.*; import javafx.stage.Stage; import javafx.scene.*; @SuppressWarnings("restriction") public class ClockPaneTest extends Application { ClockPane pane = new ClockPane(); @Override public void start(Stage stage) throws Exception { Scene scene = new Scene(pane, 250,250); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
{ "content_hash": "478bfeb619a6d000d8ab648bdaf41631", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 50, "avg_line_length": 18.956521739130434, "alnum_prop": 0.7224770642201835, "repo_name": "jppreti/GUI", "id": "d3abcd4585bbf122dfa16a8908a9f393ace35e98", "size": "436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gui/src/main/java/gui/javafx/ClockPaneTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "38625" }, { "name": "Java", "bytes": "131382" }, { "name": "JavaScript", "bytes": "33168" } ], "symlink_target": "" }
@implementation NSTimer (BlockSupport) + (NSTimer *)CY_scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void (^)())block repeats:(BOOL)repeats { return [self scheduledTimerWithTimeInterval: interval target: self selector: @selector(CY_blockInvoke:) userInfo: block repeats: repeats]; } + (void) CY_blockInvoke:(NSTimer*)timer { void (^block)() = timer.userInfo; if (block) { block(); } } @end
{ "content_hash": "980d0dab1631b08fc1bec9d98c68e2ec", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 142, "avg_line_length": 31.142857142857142, "alnum_prop": 0.7018348623853211, "repo_name": "CookieYang/CYmusicPlayer", "id": "3c4a6d067416005c927f9e45460b87488d10f11a", "size": "616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CYMusicPlayer/NSTimer+BlockSupport.m", "mode": "33188", "license": "mit", "language": [ { "name": "M", "bytes": "24572" }, { "name": "Objective-C", "bytes": "160866" } ], "symlink_target": "" }
#ifndef JSPLAY_TEXTURECOLLECTION_H #define JSPLAY_TEXTURECOLLECTION_H #include <script/script-object-wrap.h> #include <array> class GraphicsDevice; class Texture2D; class TextureCollection : public ScriptObjectWrap<TextureCollection> { public: TextureCollection(v8::Isolate *isolate, GraphicsDevice *graphicsDevice_) : ScriptObjectWrap(isolate), graphicsDevice_(graphicsDevice_) { } Texture2D*& operator[](const int index) { return textures_[index]; } protected: void Initialize() override; private: static void SetTexture( uint32_t index, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info); GraphicsDevice* graphicsDevice_; std::array<Texture2D*, 4> textures_; }; #endif // JSPLAY_TEXTURECOLLECTION_H
{ "content_hash": "5c021e0e5ae5b01d9ad1207421968faa", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 77, "avg_line_length": 23.852941176470587, "alnum_prop": 0.7065351418002466, "repo_name": "jnsmalm/jsplay", "id": "5e54b4a9d320cfbea0d2b67c8d910c77332a2f2a", "size": "1901", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/graphics/texture-collection.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "192790" }, { "name": "CMake", "bytes": "4278" }, { "name": "GLSL", "bytes": "5729" }, { "name": "JavaScript", "bytes": "192326" } ], "symlink_target": "" }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions; import com.intellij.lang.ASTNode; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.AtomicNotNullLazyValue; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.ResolveCache.PolyVariantResolver; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PropertyUtilBase; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.profiling.ResolveProfiler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyLanguage; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.lexer.TokenSets; import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrParenthesizedExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeArgumentList; import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper; import org.jetbrains.plugins.groovy.lang.psi.impl.*; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl; import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrReferenceTypeEnhancer; import org.jetbrains.plugins.groovy.lang.psi.util.*; import org.jetbrains.plugins.groovy.lang.resolve.DependentResolver; import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; import org.jetbrains.plugins.groovy.lang.typing.GrTypeCalculator; import java.util.*; import static org.jetbrains.plugins.groovy.lang.resolve.GrReferenceResolveRunnerKt.resolveReferenceExpression; /** * @author ilyas */ public class GrReferenceExpressionImpl extends GrReferenceElementImpl<GrExpression> implements GrReferenceExpression { private static final Logger LOG = Logger.getInstance(GrReferenceExpressionImpl.class); public GrReferenceExpressionImpl(@NotNull ASTNode node) { super(node); } private final NotNullLazyValue<GrReferenceExpressionReference> myFakeGetterReference = AtomicNotNullLazyValue.createValue( () -> new GrReferenceExpressionReference(this, true) ); private final NotNullLazyValue<GrReferenceExpressionReference> myFakeReference = AtomicNotNullLazyValue.createValue( () -> new GrReferenceExpressionReference(this, false) ); @NotNull private static List<GroovyResolveResult> filterMembersFromSuperClasses(GroovyResolveResult[] results) { List<GroovyResolveResult> filtered = new ArrayList<>(); for (GroovyResolveResult result : results) { final PsiElement element = result.getElement(); if (element instanceof PsiMember) { if (((PsiMember)element).hasModifierProperty(PsiModifier.PRIVATE)) continue; final PsiClass containingClass = ((PsiMember)element).getContainingClass(); if (containingClass != null) { if (!InheritanceUtil.isInheritor(containingClass, CommonClassNames.JAVA_UTIL_MAP)) continue; final String name = containingClass.getQualifiedName(); if (name != null && name.startsWith("java.")) continue; if (containingClass.getLanguage() != GroovyLanguage.INSTANCE && !InheritanceUtil.isInheritor(containingClass, GroovyCommonClassNames.GROOVY_OBJECT)) { continue; } } } filtered.add(result); } return filtered; } @Override public void accept(GroovyElementVisitor visitor) { visitor.visitReferenceExpression(this); } @Override @Nullable public PsiElement getReferenceNameElement() { final ASTNode lastChild = getNode().getLastChildNode(); if (lastChild == null) return null; if (TokenSets.REFERENCE_NAMES.contains(lastChild.getElementType())) { return lastChild.getPsi(); } return null; } @Override @Nullable public GrExpression getQualifier() { return getQualifierExpression(); } @Override @Nullable public String getReferenceName() { PsiElement nameElement = getReferenceNameElement(); if (nameElement != null) { IElementType nodeType = nameElement.getNode().getElementType(); if (TokenSets.STRING_LITERAL_SET.contains(nodeType)) { final Object value = GrLiteralImpl.getLiteralValue(nameElement); if (value instanceof String) { return (String)value; } } return nameElement.getText(); } return null; } @Override public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { if (!PsiUtil.isValidReferenceName(newElementName)) { final PsiElement old = getReferenceNameElement(); if (old == null) throw new IncorrectOperationException("ref has no name element"); PsiElement element = GroovyPsiElementFactory.getInstance(getProject()).createStringLiteralForReference(newElementName); old.replace(element); return this; } if (PsiUtil.isThisOrSuperRef(this)) return this; final GroovyResolveResult result = advancedResolve(); if (result.isInvokedOnProperty()) { final String name = GroovyPropertyUtils.getPropertyNameByAccessorName(newElementName); if (name != null) { newElementName = name; } } return super.handleElementRename(newElementName); } @Override protected GrReferenceExpression bindWithQualifiedRef(@NotNull String qName) { GrReferenceExpression qualifiedRef = GroovyPsiElementFactory.getInstance(getProject()).createReferenceExpressionFromText(qName); final GrTypeArgumentList list = getTypeArgumentList(); if (list != null) { qualifiedRef.getNode().addChild(list.copy().getNode()); } getNode().getTreeParent().replaceChild(getNode(), qualifiedRef.getNode()); return qualifiedRef; } @Override public boolean isFullyQualified() { if (!ResolveUtil.canResolveToMethod(this) && resolve() instanceof PsiPackage) return true; final GrExpression qualifier = getQualifier(); if (!(qualifier instanceof GrReferenceExpressionImpl)) return false; return ((GrReferenceExpressionImpl)qualifier).isFullyQualified(); } public String toString() { return "Reference expression"; } @Override @Nullable public PsiType getNominalType() { return getNominalType(false); } @Nullable private PsiType getNominalType(boolean rValue) { final GroovyResolveResult resolveResult = PsiImplUtil.extractUniqueResult(multiResolve(false, rValue)); PsiElement resolved = resolveResult.getElement(); for (GrReferenceTypeEnhancer enhancer : GrReferenceTypeEnhancer.EP_NAME.getExtensions()) { PsiType type = enhancer.getReferenceType(this, resolved); if (type != null) { return type; } } IElementType dotType = getDotTokenType(); if (dotType == GroovyTokenTypes.mMEMBER_POINTER) { return GrClosureType.create(multiResolve(false), this); } if (ResolveUtil.isDefinitelyKeyOfMap(this)) { return getTypeFromMapAccess(this); } PsiType result = getNominalTypeInner(resolved); if (result == null) return null; result = TypesUtil.substituteAndNormalizeType(result, resolveResult.getSubstitutor(), resolveResult.getSpreadState(), this); return result; } @Nullable private PsiType getNominalTypeInner(@Nullable PsiElement resolved) { if (resolved == null && !"class".equals(getReferenceName())) { resolved = resolve(); } if (resolved instanceof PsiClass) { final PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory(); if (PsiUtil.isInstanceThisRef(this)) { final PsiClassType categoryType = GdkMethodUtil.getCategoryType((PsiClass)resolved); if (categoryType != null) { return categoryType; } else { return factory.createType((PsiClass)resolved); } } else if (PsiUtil.isSuperReference(this)) { PsiClass contextClass = PsiUtil.getContextClass(this); if (GrTraitUtil.isTrait(contextClass)) { PsiClassType[] extendsTypes = contextClass.getExtendsListTypes(); PsiClassType[] implementsTypes = contextClass.getImplementsListTypes(); PsiClassType[] superTypes = ArrayUtil.mergeArrays(implementsTypes, extendsTypes, PsiClassType.ARRAY_FACTORY); if (superTypes.length > 0) { return PsiIntersectionType.createIntersection(ArrayUtil.reverseArray(superTypes)); } } return factory.createType((PsiClass)resolved); } return TypesUtil.createJavaLangClassType(factory.createType((PsiClass)resolved), getProject(), getResolveScope()); } if (resolved instanceof GrVariable) { return ((GrVariable)resolved).getDeclaredType(); } if (resolved instanceof PsiVariable) { return ((PsiVariable)resolved).getType(); } if (resolved instanceof PsiMethod) { PsiMethod method = (PsiMethod)resolved; if (PropertyUtilBase.isSimplePropertySetter(method) && !method.getName().equals(getReferenceName())) { return method.getParameterList().getParameters()[0].getType(); } //'class' property with explicit generic PsiClass containingClass = method.getContainingClass(); if (containingClass != null && CommonClassNames.JAVA_LANG_OBJECT.equals(containingClass.getQualifiedName()) && "getClass".equals(method.getName())) { return getTypeFromClassRef(); } return PsiUtil.getSmartReturnType(method); } if (resolved == null) { if ("class".equals(getReferenceName())) { final PsiType fromClassRef = getTypeFromClassRef(); if (fromClassRef != null) { return fromClassRef; } } final PsiType fromMapAccess = getTypeFromMapAccess(this); if (fromMapAccess != null) { return fromMapAccess; } final PsiType fromSpreadOperator = getTypeFromSpreadOperator(this); if (fromSpreadOperator != null) { return fromSpreadOperator; } } return null; } @Nullable private static PsiType getTypeFromMapAccess(@NotNull GrReferenceExpressionImpl ref) { //map access GrExpression qualifier = ref.getQualifierExpression(); if (qualifier instanceof GrReferenceExpression) { if (((GrReferenceExpression)qualifier).resolve() instanceof PsiClass) return null; } if (ref.getDotTokenType() == GroovyTokenTypes.mSPREAD_DOT) return null; if (qualifier != null) { PsiType qType = qualifier.getType(); if (qType instanceof PsiClassType) { PsiClassType.ClassResolveResult qResult = ((PsiClassType)qType).resolveGenerics(); PsiClass clazz = qResult.getElement(); if (clazz != null) { PsiClass mapClass = JavaPsiFacade.getInstance(ref.getProject()).findClass(CommonClassNames.JAVA_UTIL_MAP, ref.getResolveScope()); if (mapClass != null && mapClass.getTypeParameters().length == 2) { PsiSubstitutor substitutor = TypeConversionUtil.getClassSubstitutor(mapClass, clazz, qResult.getSubstitutor()); if (substitutor != null) { PsiType substituted = substitutor.substitute(mapClass.getTypeParameters()[1]); if (substituted != null) { return PsiImplUtil.normalizeWildcardTypeByPosition(substituted, ref); } } } } } } return null; } @Nullable private static PsiType getTypeFromSpreadOperator(@NotNull GrReferenceExpressionImpl ref) { if (ref.getDotTokenType() == GroovyTokenTypes.mSPREAD_DOT) { return TypesUtil.createType(CommonClassNames.JAVA_UTIL_LIST, ref); } return null; } @Nullable private PsiType getTypeFromClassRef() { PsiType qualifierType = PsiImplUtil.getQualifierType(this); if (qualifierType == null && !PsiUtil.isCompileStatic(this)) return null; return TypesUtil.createJavaLangClassType(qualifierType, getProject(), getResolveScope()); } @Nullable private static PsiType calculateType(@NotNull GrReferenceExpressionImpl refExpr) { final GroovyResolveResult[] results = refExpr.multiResolve(false, true); final GroovyResolveResult result = PsiImplUtil.extractUniqueResult(results); final PsiElement resolved = result.getElement(); PsiType typeFromCalculators = GrTypeCalculator.getTypeFromCalculators(refExpr); if (typeFromCalculators != null) return typeFromCalculators; if (ResolveUtil.isClassReference(refExpr)) { GrExpression qualifier = refExpr.getQualifier(); LOG.assertTrue(qualifier != null); return qualifier.getType(); } final PsiType nominal = refExpr.getNominalType(true); Boolean reassigned = GrReassignedLocalVarsChecker.isReassignedVar(refExpr); if (reassigned != null && reassigned.booleanValue()) { return GrReassignedLocalVarsChecker.getReassignedVarType(refExpr, true); } final PsiType inferred = getInferredTypes(refExpr, resolved); if (inferred == null) { if (nominal != null) return nominal; //inside nested closure we could still try to infer from variable initializer. Not sound, but makes sense if (resolved instanceof GrVariable) { if (PsiUtil.isCompileStatic(refExpr) && resolved instanceof GrField) { return TypesUtil.getJavaLangObject(refExpr); } LOG.assertTrue(resolved.isValid()); return ((GrVariable)resolved).getTypeGroovy(); } return null; } if (nominal == null) return inferred; if (!TypeConversionUtil.isAssignable(TypeConversionUtil.erasure(nominal), inferred, false)) { if (resolved instanceof GrVariable && ((GrVariable)resolved).getTypeElementGroovy() != null) { return nominal; } } return inferred; } @Nullable private static PsiType getInferredTypes(@NotNull GrReferenceExpressionImpl refExpr, @Nullable PsiElement resolved) { final GrExpression qualifier = refExpr.getQualifier(); if (!(resolved instanceof PsiClass) && !(resolved instanceof PsiPackage)) { if (qualifier == null) { return TypeInferenceHelper.getCurrentContext().getVariableType(refExpr); } else { //map access PsiType qType = qualifier.getType(); if (qType instanceof PsiClassType && !(qType instanceof GrMapType)) { final PsiType mapValueType = getTypeFromMapAccess(refExpr); if (mapValueType != null) { return mapValueType; } } } } return null; } @Nullable @Override public PsiType getType() { return TypeInferenceHelper.getCurrentContext().getExpressionType(this, e -> calculateType(e)); } @Override public GrExpression replaceWithExpression(@NotNull GrExpression newExpr, boolean removeUnnecessaryParentheses) { return PsiImplUtil.replaceExpression(this, newExpr, removeUnnecessaryParentheses); } @NotNull GroovyResolveResult[] doPolyResolve(boolean incompleteCode, boolean forceRValue) { final PsiElement nameElement = getReferenceNameElement(); final String name = getReferenceName(); if (name == null || nameElement == null) return GroovyResolveResult.EMPTY_ARRAY; try { ResolveProfiler.start(); final IElementType nameType = nameElement.getNode().getElementType(); if (nameType == GroovyTokenTypes.kTHIS) { final GroovyResolveResult[] results = GrThisReferenceResolver.resolveThisExpression(this); if (results != null) return results; } else if (nameType == GroovyTokenTypes.kSUPER) { final GroovyResolveResult[] results = GrSuperReferenceResolver.resolveSuperExpression(this); if (results != null) return results; } else if (nameType == GroovyTokenTypes.kCLASS && !PsiUtil.isCompileStatic(this)) { GrExpression qualifier = getQualifier(); if (qualifier == null || qualifier.getType() == null) return GroovyResolveResult.EMPTY_ARRAY; } final GroovyResolveResult[] results = resolveReferenceExpression(this, forceRValue, incompleteCode).toArray(GroovyResolveResult.EMPTY_ARRAY); if (results.length == 0) { return GroovyResolveResult.EMPTY_ARRAY; } else if (!ResolveUtil.canResolveToMethod(this)) { if (!ResolveUtil.mayBeKeyOfMap(this)) { return results; } else { //filter out all members from super classes. We should return only accessible members from map classes final List<GroovyResolveResult> filtered = filterMembersFromSuperClasses(results); return ContainerUtil.toArray(filtered, new GroovyResolveResult[filtered.size()]); } } else { return results; } } finally { final long time = ResolveProfiler.finish(); ResolveProfiler.write("ref", this, time); } } @Override @NotNull public String getCanonicalText() { return getRangeInElement().substring(getElement().getText()); } @Override public boolean hasAt() { return findChildByType(GroovyTokenTypes.mAT) != null; } @Override public boolean hasMemberPointer() { return findChildByType(GroovyTokenTypes.mMEMBER_POINTER) != null; } @Override public boolean isReferenceTo(PsiElement element) { GroovyResolveResult[] results = multiResolve(false); for (GroovyResolveResult result : results) { PsiElement baseTarget = result.getElement(); if (baseTarget == null) continue; if (getManager().areElementsEquivalent(element, baseTarget)) { return true; } PsiElement target = GroovyTargetElementEvaluator.correctSearchTargets(baseTarget); if (target != baseTarget && getManager().areElementsEquivalent(element, target)) { return true; } if (element instanceof PsiMethod && target instanceof PsiMethod) { PsiMethod[] superMethods = ((PsiMethod)target).findSuperMethods(false); //noinspection SuspiciousMethodCalls if (Arrays.asList(superMethods).contains(element)) { return true; } } } return false; } @Override @NotNull public Object[] getVariants() { return ArrayUtil.EMPTY_OBJECT_ARRAY; } @Override public boolean isSoft() { return false; } @Override @Nullable public GrExpression getQualifierExpression() { return findExpressionChild(this); } @Override @Nullable public PsiElement getDotToken() { return findChildByType(TokenSets.DOTS); } @Override public void replaceDotToken(PsiElement newDot) { if (newDot == null) return; if (!TokenSets.DOTS.contains(newDot.getNode().getElementType())) return; final PsiElement oldDot = getDotToken(); if (oldDot == null) return; getNode().replaceChild(oldDot.getNode(), newDot.getNode()); } @Override @Nullable public IElementType getDotTokenType() { PsiElement dot = getDotToken(); return dot == null ? null : dot.getNode().getElementType(); } @Override public PsiReference getReference() { return this; } private static final PolyVariantResolver<GrReferenceExpressionImpl> RESOLVER = new DependentResolver<GrReferenceExpressionImpl>() { @Nullable @Override public Collection<PsiPolyVariantReference> collectDependencies(@NotNull GrReferenceExpressionImpl expression) { final GrExpression qualifier = expression.getQualifier(); if (qualifier == null) return null; final List<PsiPolyVariantReference> result = new SmartList<>(); qualifier.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { if (element instanceof GrReferenceExpression) { super.visitElement(element); } else if (element instanceof GrMethodCall) { super.visitElement(((GrMethodCall)element).getInvokedExpression()); } else if (element instanceof GrParenthesizedExpression) { GrExpression operand = ((GrParenthesizedExpression)element).getOperand(); if (operand != null) super.visitElement(operand); } } @Override protected void elementFinished(PsiElement element) { if (element instanceof GrReferenceExpression) { result.add(((GrReferenceExpression)element)); } } }); return result; } @NotNull @Override public ResolveResult[] doResolve(@NotNull GrReferenceExpressionImpl ref, boolean incomplete) { GroovyResolveResult[] regularResults = ref.multiResolve(incomplete, false); if (PsiUtil.isLValueOfOperatorAssignment(ref)) { Set<GroovyResolveResult> result = ContainerUtil.newLinkedHashSet(); ContainerUtil.addAll(result, ref.multiResolve(incomplete, true)); ContainerUtil.addAll(result, regularResults); return result.toArray(GroovyResolveResult.EMPTY_ARRAY); } else { return regularResults; } } }; @NotNull @Override public GroovyResolveResult[] multiResolve(boolean incompleteCode) { return TypeInferenceHelper.getCurrentContext().multiResolve(this, incompleteCode, RESOLVER); } @NotNull public GroovyResolveResult[] multiResolve(boolean incomplete, boolean forceRValue) { return (forceRValue ? myFakeGetterReference : myFakeReference).getValue().multiResolve(incomplete); } @Override @NotNull public GroovyResolveResult[] getSameNameVariants() { return doPolyResolve(true, false); } @Override public GrReferenceExpression bindToElementViaStaticImport(@NotNull PsiMember member) { if (getQualifier() != null) { throw new IncorrectOperationException("Reference has qualifier"); } if (StringUtil.isEmpty(getReferenceName())) { throw new IncorrectOperationException("Reference has empty name"); } PsiClass containingClass = member.getContainingClass(); if (containingClass == null) { throw new IncorrectOperationException("Member has no containing class"); } final PsiFile file = getContainingFile(); if (file instanceof GroovyFile) { GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject()); String text = "import static " + containingClass.getQualifiedName() + "." + member.getName(); final GrImportStatement statement = factory.createImportStatementFromText(text); ((GroovyFile)file).addImport(statement); } return this; } }
{ "content_hash": "5ad2d2c63b2ca03e7f770d5cffb8049e", "timestamp": "", "source": "github", "line_count": 644, "max_line_length": 147, "avg_line_length": 36.86801242236025, "alnum_prop": 0.7134734448047846, "repo_name": "mglukhikh/intellij-community", "id": "82b38cd2ad2d4e3b10527ce3256e2899a3c23417", "size": "23743", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "60827" }, { "name": "C", "bytes": "211435" }, { "name": "C#", "bytes": "1264" }, { "name": "C++", "bytes": "197674" }, { "name": "CMake", "bytes": "1675" }, { "name": "CSS", "bytes": "201445" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groovy", "bytes": "3243028" }, { "name": "HLSL", "bytes": "57" }, { "name": "HTML", "bytes": "1899088" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "165554704" }, { "name": "JavaScript", "bytes": "570364" }, { "name": "Jupyter Notebook", "bytes": "93222" }, { "name": "Kotlin", "bytes": "4611299" }, { "name": "Lex", "bytes": "147047" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "51276" }, { "name": "Objective-C", "bytes": "27861" }, { "name": "Perl", "bytes": "903" }, { "name": "Perl 6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6680" }, { "name": "Python", "bytes": "25439881" }, { "name": "Roff", "bytes": "37534" }, { "name": "Ruby", "bytes": "1217" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "66341" }, { "name": "Smalltalk", "bytes": "338" }, { "name": "TeX", "bytes": "25473" }, { "name": "Thrift", "bytes": "1846" }, { "name": "TypeScript", "bytes": "9469" }, { "name": "Visual Basic", "bytes": "77" }, { "name": "XSLT", "bytes": "113040" } ], "symlink_target": "" }
<?php namespace app\models; use Yii; /** * This is the model class for table "groups". * * @property integer $id * @property string $name */ class Groups extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'groups'; } /** * @inheritdoc */ public function rules() { return [ [['name'], 'string', 'max' => 255], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'name' => 'กลุ่มงาน', ]; } public function getGroupdep(){ return $this->hasMany(Departments::className(), ['group_id'=>'id']); } }
{ "content_hash": "3db129d5b80af462ec38aef44da905b4", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 76, "avg_line_length": 16.304347826086957, "alnum_prop": 0.4826666666666667, "repo_name": "inamjung/Yiiproject", "id": "67e36d9954e555701327ae0b551edb0a323e389b", "size": "766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/Groups.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "1842" }, { "name": "PHP", "bytes": "439399" } ], "symlink_target": "" }
using namespace foundation; using namespace std; namespace renderer { // // DirectLightingIntegrator class implementation. // // Call graph: // // compute_outgoing_radiance_bsdf_sampling // take_single_bsdf_sample // // compute_outgoing_radiance_light_sampling // add_emitting_triangle_sample_contribution // add_non_physical_light_sample_contribution // // compute_outgoing_radiance_light_sampling_low_variance // add_emitting_triangle_sample_contribution // add_non_physical_light_sample_contribution // // compute_outgoing_radiance_combined_sampling // compute_outgoing_radiance_bsdf_sampling // compute_outgoing_radiance_light_sampling // // compute_outgoing_radiance_combined_sampling_low_variance // compute_outgoing_radiance_bsdf_sampling // compute_outgoing_radiance_light_sampling_low_variance // // compute_incoming_radiance // DirectLightingIntegrator::DirectLightingIntegrator( const ShadingContext& shading_context, const LightSampler& light_sampler, const ShadingPoint& shading_point, const BSDF& bsdf, const void* bsdf_data, const int bsdf_sampling_modes, const int light_sampling_modes, const size_t bsdf_sample_count, const size_t light_sample_count, const bool indirect) : m_shading_context(shading_context) , m_light_sampler(light_sampler) , m_shading_point(shading_point) , m_point(shading_point.get_point()) , m_geometric_normal(shading_point.get_geometric_normal()) , m_shading_basis(shading_point.get_shading_basis()) , m_time(shading_point.get_time()) , m_bsdf(bsdf) , m_bsdf_data(bsdf_data) , m_bsdf_sampling_modes(bsdf_sampling_modes) , m_light_sampling_modes(light_sampling_modes) , m_bsdf_sample_count(bsdf_sample_count) , m_light_sample_count(light_sample_count) , m_indirect(indirect) { } void DirectLightingIntegrator::compute_outgoing_radiance_bsdf_sampling( SamplingContext& sampling_context, const MISHeuristic mis_heuristic, const Dual3d& outgoing, Spectrum& radiance, SpectrumStack& aovs) const { radiance.set(0.0f); aovs.set(0.0f); // No emitting triangles in the scene. if (m_light_sampler.get_emitting_triangle_count() == 0) return; for (size_t i = 0; i < m_bsdf_sample_count; ++i) { take_single_bsdf_sample( sampling_context, mis_heuristic, outgoing, radiance, aovs); } if (m_bsdf_sample_count > 1) { const float rcp_bsdf_sample_count = 1.0f / m_bsdf_sample_count; radiance *= rcp_bsdf_sample_count; aovs *= rcp_bsdf_sample_count; } } void DirectLightingIntegrator::compute_outgoing_radiance_light_sampling( SamplingContext& sampling_context, const MISHeuristic mis_heuristic, const Dual3d& outgoing, Spectrum& radiance, SpectrumStack& aovs) const { radiance.set(0.0f); aovs.set(0.0f); // No light source in the scene. if (!m_light_sampler.has_lights_or_emitting_triangles()) return; // There cannot be any contribution for purely specular BSDFs. if (m_bsdf.is_purely_specular()) return; sampling_context.split_in_place(3, m_light_sample_count); // Add contributions from both emitting triangles and non-physical light sources. for (size_t i = 0; i < m_light_sample_count; ++i) { // Sample both emitting triangles and non-physical light sources. LightSample sample; m_light_sampler.sample( m_time, sampling_context.next2<Vector3f>(), sample); if (sample.m_triangle) { add_emitting_triangle_sample_contribution( sample, mis_heuristic, outgoing, radiance, aovs); } else { add_non_physical_light_sample_contribution( sample, outgoing, radiance, aovs); } } if (m_light_sample_count > 1) { const float rcp_light_sample_count = 1.0f / m_light_sample_count; radiance *= rcp_light_sample_count; aovs *= rcp_light_sample_count; } } void DirectLightingIntegrator::compute_outgoing_radiance_light_sampling_low_variance( SamplingContext& sampling_context, const MISHeuristic mis_heuristic, const Dual3d& outgoing, Spectrum& radiance, SpectrumStack& aovs) const { radiance.set(0.0f); aovs.set(0.0f); // No light source in the scene. if (!m_light_sampler.has_lights_or_emitting_triangles()) return; // There cannot be any contribution for purely specular BSDFs. if (m_bsdf.is_purely_specular()) return; // Add contributions from emitting triangles only. if (m_light_sampler.get_emitting_triangle_count() > 0) { sampling_context.split_in_place(3, m_light_sample_count); for (size_t i = 0; i < m_light_sample_count; ++i) { // Sample emitting triangles only. LightSample sample; m_light_sampler.sample_emitting_triangles( m_time, sampling_context.next2<Vector3f>(), sample); add_emitting_triangle_sample_contribution( sample, mis_heuristic, outgoing, radiance, aovs); } if (m_light_sample_count > 1) { const float rcp_light_sample_count = 1.0f / m_light_sample_count; radiance *= rcp_light_sample_count; aovs *= rcp_light_sample_count; } } // Add contributions from non-physical light sources only. for (size_t i = 0, e = m_light_sampler.get_non_physical_light_count(); i < e; ++i) { LightSample sample; m_light_sampler.sample_non_physical_light(m_time, i, sample); add_non_physical_light_sample_contribution( sample, outgoing, radiance, aovs); } } void DirectLightingIntegrator::compute_outgoing_radiance_combined_sampling( SamplingContext& sampling_context, const Dual3d& outgoing, Spectrum& radiance, SpectrumStack& aovs) const { compute_outgoing_radiance_bsdf_sampling( sampling_context, MISPower2, outgoing, radiance, aovs); Spectrum radiance_light_sampling(Spectrum::Illuminance); SpectrumStack aovs_light_sampling(aovs.size()); compute_outgoing_radiance_light_sampling( sampling_context, MISPower2, outgoing, radiance_light_sampling, aovs_light_sampling); radiance += radiance_light_sampling; aovs += aovs_light_sampling; } void DirectLightingIntegrator::compute_outgoing_radiance_combined_sampling_low_variance( SamplingContext& sampling_context, const Dual3d& outgoing, Spectrum& radiance, SpectrumStack& aovs) const { compute_outgoing_radiance_bsdf_sampling( sampling_context, MISPower2, outgoing, radiance, aovs); Spectrum radiance_light_sampling(Spectrum::Illuminance); SpectrumStack aovs_light_sampling(aovs.size()); compute_outgoing_radiance_light_sampling_low_variance( sampling_context, MISPower2, outgoing, radiance_light_sampling, aovs_light_sampling); radiance += radiance_light_sampling; aovs += aovs_light_sampling; } bool DirectLightingIntegrator::compute_incoming_radiance( SamplingContext& sampling_context, Vector3d& incoming, float& incoming_prob, Spectrum& radiance) const { radiance.set(0.0f); // No light source in the scene. if (!m_light_sampler.has_lights_or_emitting_triangles()) return false; sampling_context.split_in_place(3, 1); // Sample both emitting triangles and non-physical light sources. LightSample sample; m_light_sampler.sample( m_time, sampling_context.next2<Vector3f>(), sample); if (sample.m_triangle) { const Material* material = sample.m_triangle->m_material; const Material::RenderData& material_data = material->get_render_data(); const EDF* edf = material_data.m_edf; // No contribution if we are computing indirect lighting but this light does not cast indirect light. if (m_indirect && !(edf->get_flags() & EDF::CastIndirectLight)) return false; // Compute the incoming direction in world space. incoming = sample.m_point - m_point; // No contribution if the shading point is behind the light. double cos_on_light = dot(-incoming, sample.m_shading_normal); if (cos_on_light <= 0.0) return false; // Compute the transmission factor between the light sample and the shading point. const float transmission = m_shading_context.get_tracer().trace_between( m_shading_point, sample.m_point, VisibilityFlags::ShadowRay); // Discard occluded samples. if (transmission == 0.0f) return false; // Don't use this sample if we're closer than the light near start value. const double square_distance = square_norm(incoming); if (square_distance < square(edf->get_light_near_start())) return false; // Normalize the incoming direction. const double rcp_square_distance = 1.0 / square_distance; const double rcp_distance = sqrt(rcp_square_distance); incoming *= rcp_distance; cos_on_light *= rcp_distance; // Build a shading point on the light source. ShadingPoint light_shading_point; sample.make_shading_point( light_shading_point, sample.m_shading_normal, m_shading_context.get_intersector()); if (material_data.m_shader_group) { m_shading_context.execute_osl_emission( *material_data.m_shader_group, light_shading_point); } // Evaluate the EDF. edf->evaluate( edf->evaluate_inputs(m_shading_context, light_shading_point), Vector3f(sample.m_geometric_normal), Basis3f(Vector3f(sample.m_shading_normal)), -Vector3f(incoming), radiance); // Compute probability with respect to solid angle of incoming direction. const float g = static_cast<float>(cos_on_light * rcp_square_distance); incoming_prob = sample.m_probability / g; // Compute and return the incoming radiance. radiance *= transmission * g / sample.m_probability; } else { const Light* light = sample.m_light; // No contribution if we are computing indirect lighting but this light does not cast indirect light. if (m_indirect && !(light->get_flags() & Light::CastIndirectLight)) return false; // Evaluate the light. Vector3d emission_position, emission_direction; light->evaluate( m_shading_context, sample.m_light_transform, m_point, emission_position, emission_direction, radiance); // Compute the transmission factor between the light sample and the shading point. const float transmission = m_shading_context.get_tracer().trace_between( m_shading_point, emission_position, VisibilityFlags::ShadowRay); // Discard occluded samples. if (transmission == 0.0f) return false; // Compute the incoming direction in world space. incoming = -emission_direction; incoming_prob = BSDF::DiracDelta; // Compute and return the incoming radiance. const float attenuation = light->compute_distance_attenuation(m_point, emission_position); radiance *= transmission * attenuation / sample.m_probability; } return true; } void DirectLightingIntegrator::take_single_bsdf_sample( SamplingContext& sampling_context, const MISHeuristic mis_heuristic, const Dual3d& outgoing, Spectrum& radiance, SpectrumStack& aovs) const { assert(m_light_sampler.get_emitting_triangle_count() > 0); // Sample the BSDF. BSDFSample sample(&m_shading_point, Dual3f(outgoing)); m_bsdf.sample( sampling_context, m_bsdf_data, false, // not adjoint true, // multiply by |cos(incoming, normal)| sample); // Filter scattering modes. if (!(m_bsdf_sampling_modes & sample.m_mode)) return; // Trace a ray in the direction of the reflection. float weight; const ShadingPoint& light_shading_point = m_shading_context.get_tracer().trace( m_shading_point, Vector3d(sample.m_incoming.get_value()), VisibilityFlags::ShadowRay, weight); // todo: wouldn't it be more efficient to look the environment up at this point? if (!light_shading_point.hit()) return; // Retrieve the material at the intersection point. const Material* material = light_shading_point.get_material(); if (material == 0) return; const Material::RenderData& material_data = material->get_render_data(); // Retrieve the EDF at the intersection point. const EDF* edf = material_data.m_edf; if (edf == 0) return; // No contribution if we are computing indirect lighting but this light does not cast indirect light. if (m_indirect && !(edf->get_flags() & EDF::CastIndirectLight)) return; // Cull the samples on the back side of the lights' shading surface. const float cos_on = dot(-sample.m_incoming.get_value(), Vector3f(light_shading_point.get_shading_normal())); if (cos_on <= 0.0f) return; if (material_data.m_shader_group) { m_shading_context.execute_osl_emission( *material_data.m_shader_group, light_shading_point); } // Evaluate emitted radiance. Spectrum edf_value(Spectrum::Illuminance); float edf_prob; edf->evaluate( edf->evaluate_inputs(m_shading_context, light_shading_point), Vector3f(light_shading_point.get_geometric_normal()), Basis3f(light_shading_point.get_shading_basis()), -sample.m_incoming.get_value(), edf_value, edf_prob); if (edf_prob == 0.0f) return; // Compute the square distance between the light sample and the shading point. const double square_distance = square(light_shading_point.get_distance()); // Don't use this sample if we're closer than the light near start value. if (square_distance < square(edf->get_light_near_start())) return; if (sample.m_probability != BSDF::DiracDelta) { if (mis_heuristic != MISNone && square_distance > 0.0) { // Transform bsdf_prob to surface area measure (Veach: 8.2.2.2 eq. 8.10). const float bsdf_prob_area = sample.m_probability * cos_on / static_cast<float>(square_distance); // Compute the probability density wrt. surface area mesure of the light sample. const float light_prob_area = m_light_sampler.evaluate_pdf(light_shading_point); // Apply the weighting function. weight *= mis( mis_heuristic, m_bsdf_sample_count * bsdf_prob_area, m_light_sample_count * light_prob_area); } edf_value *= weight / sample.m_probability; } // Add the contribution of this sample to the illumination. edf_value *= sample.m_value; radiance += edf_value; aovs.add(edf->get_render_layer_index(), edf_value); } void DirectLightingIntegrator::add_emitting_triangle_sample_contribution( const LightSample& sample, const MISHeuristic mis_heuristic, const Dual3d& outgoing, Spectrum& radiance, SpectrumStack& aovs) const { const Material* material = sample.m_triangle->m_material; const Material::RenderData& material_data = material->get_render_data(); const EDF* edf = material_data.m_edf; // No contribution if we are computing indirect lighting but this light does not cast indirect light. if (m_indirect && !(edf->get_flags() & EDF::CastIndirectLight)) return; // Compute the incoming direction in world space. Vector3d incoming = sample.m_point - m_point; // Cull light samples behind the shading surface if the BSDF is either reflective or transmissive, // but not both. if (m_bsdf.get_type() != BSDF::AllBSDFTypes) { double cos_in = dot(incoming, m_shading_basis.get_normal()); if (m_bsdf.get_type() == BSDF::Transmissive) cos_in = -cos_in; if (cos_in <= 0.0) return; } // No contribution if the shading point is behind the light. double cos_on = dot(-incoming, sample.m_shading_normal); if (cos_on <= 0.0) return; // Compute the transmission factor between the light sample and the shading point. const float transmission = m_shading_context.get_tracer().trace_between( m_shading_point, sample.m_point, VisibilityFlags::ShadowRay); // Discard occluded samples. if (transmission == 0.0f) return; // Compute the square distance between the light sample and the shading point. const double square_distance = square_norm(incoming); const double rcp_sample_square_distance = 1.0 / square_distance; const double rcp_sample_distance = sqrt(rcp_sample_square_distance); // Don't use this sample if we're closer than the light near start value. if (square_distance < square(edf->get_light_near_start())) return; // Normalize the incoming direction. incoming *= rcp_sample_distance; cos_on *= rcp_sample_distance; // Evaluate the BSDF. Spectrum bsdf_value; const float bsdf_prob = m_bsdf.evaluate( m_bsdf_data, false, // not adjoint true, // multiply by |cos(incoming, normal)| Vector3f(m_geometric_normal), Basis3f(m_shading_basis), Vector3f(outgoing.get_value()), Vector3f(incoming), m_light_sampling_modes, bsdf_value); if (bsdf_prob == 0.0f) return; // Build a shading point on the light source. ShadingPoint light_shading_point; sample.make_shading_point( light_shading_point, sample.m_shading_normal, m_shading_context.get_intersector()); if (material_data.m_shader_group) { m_shading_context.execute_osl_emission( *material_data.m_shader_group, light_shading_point); } // Evaluate the EDF. Spectrum edf_value(Spectrum::Illuminance); edf->evaluate( edf->evaluate_inputs(m_shading_context, light_shading_point), Vector3f(sample.m_geometric_normal), Basis3f(Vector3f(sample.m_shading_normal)), -Vector3f(incoming), edf_value); const float g = static_cast<float>(cos_on * rcp_sample_square_distance); float weight = transmission * g / sample.m_probability; // Apply MIS weighting. weight *= mis( mis_heuristic, m_light_sample_count * sample.m_probability, m_bsdf_sample_count * bsdf_prob * g); // Add the contribution of this sample to the illumination. edf_value *= weight; edf_value *= bsdf_value; radiance += edf_value; aovs.add(edf->get_render_layer_index(), edf_value); } void DirectLightingIntegrator::add_non_physical_light_sample_contribution( const LightSample& sample, const Dual3d& outgoing, Spectrum& radiance, SpectrumStack& aovs) const { const Light* light = sample.m_light; // No contribution if we are computing indirect lighting but this light does not cast indirect light. if (m_indirect && !(light->get_flags() & Light::CastIndirectLight)) return; // Evaluate the light. Vector3d emission_position, emission_direction; Spectrum light_value(Spectrum::Illuminance); light->evaluate( m_shading_context, sample.m_light_transform, m_point, emission_position, emission_direction, light_value); // Compute the incoming direction in world space. const Vector3d incoming = -emission_direction; // Cull light samples behind the shading surface if the BSDF is either reflective or transmissive, // but not both. if (m_bsdf.get_type() != BSDF::AllBSDFTypes) { double cos_in = dot(incoming, m_shading_basis.get_normal()); if (m_bsdf.get_type() == BSDF::Transmissive) cos_in = -cos_in; if (cos_in <= 0.0) return; } // Compute the transmission factor between the light sample and the shading point. const float transmission = m_shading_context.get_tracer().trace_between( m_shading_point, emission_position, VisibilityFlags::ShadowRay); // Discard occluded samples. if (transmission == 0.0f) return; // Evaluate the BSDF. Spectrum bsdf_value; const float bsdf_prob = m_bsdf.evaluate( m_bsdf_data, false, // not adjoint true, // multiply by |cos(incoming, normal)| Vector3f(m_geometric_normal), Basis3f(m_shading_basis), Vector3f(outgoing.get_value()), Vector3f(incoming), m_light_sampling_modes, bsdf_value); if (bsdf_prob == 0.0f) return; // Add the contribution of this sample to the illumination. const float attenuation = light->compute_distance_attenuation(m_point, emission_position); const float weight = transmission * attenuation / sample.m_probability; light_value *= weight; light_value *= bsdf_value; radiance += light_value; aovs.add(light->get_render_layer_index(), light_value); } } // namespace renderer
{ "content_hash": "b21e7c2040881bc9a50cec5fbaa9ec5a", "timestamp": "", "source": "github", "line_count": 694, "max_line_length": 113, "avg_line_length": 33.29250720461095, "alnum_prop": 0.604631032244103, "repo_name": "aiivashchenko/appleseed", "id": "9bfc6f23032dac044f4f34e2298e21dc90b6bf3e", "size": "25238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/appleseed/renderer/kernel/lighting/directlightingintegrator.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "211" }, { "name": "C", "bytes": "1395946" }, { "name": "C++", "bytes": "9111244" }, { "name": "CMake", "bytes": "226630" }, { "name": "HTML", "bytes": "38058" }, { "name": "Makefile", "bytes": "717" }, { "name": "Objective-C", "bytes": "6087" }, { "name": "Python", "bytes": "312469" }, { "name": "Shell", "bytes": "2798" } ], "symlink_target": "" }
package voogasalad_GucciGames.gameplayer.controller.dummy; public enum MapObjectBasicType { TILE, STRUCTURE, UNIT }
{ "content_hash": "257124a37afef0b9ad453ce34630dbed", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 58, "avg_line_length": 17, "alnum_prop": 0.8151260504201681, "repo_name": "mym987/CPS308_Game_Final", "id": "91a5535061ad35e6a65e7a116b174693e91af8ea", "size": "119", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/voogasalad_GucciGames/gameplayer/controller/dummy/MapObjectBasicType.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4022" }, { "name": "Java", "bytes": "659100" }, { "name": "PHP", "bytes": "6031" } ], "symlink_target": "" }
'use strict'; /** * @ngdoc directive * @name izzyposWebApp.directive:adminPosHeader * @description * # adminPosHeader */ angular.module('sbAdminApp') .directive('sidebar',['$location',function() { return { templateUrl:'scripts/directives/sidebar/sidebar.html', restrict: 'E', replace: true, scope: { }, controller:function($scope,$location){ $scope.selectedMenu = 'dashboard'; $scope.collapseVar = 0; $scope.multiCollapseVar = 0; $scope.check = function(x){ if(x==$scope.collapseVar) $scope.collapseVar = 0; else $scope.collapseVar = x; }; $scope.multiCheck = function(y){ if(y==$scope.multiCollapseVar) $scope.multiCollapseVar = 0; else $scope.multiCollapseVar = y; } $scope.currentUrl = function(){ return $location.path(); console.log($location.path()); } } } }]);
{ "content_hash": "314711e945defc9a241a401b9df88cbf", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 60, "avg_line_length": 22.934782608695652, "alnum_prop": 0.5222748815165876, "repo_name": "sjbgit/sb_admin_test", "id": "b9994e03ccee13f6dbb3b836135a694f56c5e7fc", "size": "1055", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/scripts/directives/sidebar/sidebar.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "48278" }, { "name": "CSS", "bytes": "10476" }, { "name": "HTML", "bytes": "322912" }, { "name": "JavaScript", "bytes": "134264" } ], "symlink_target": "" }
#include "libxml.h" #include <string.h> #include <stdarg.h> #include <assert.h> #if defined (_WIN32) && !defined(__CYGWIN__) #if defined (_MSC_VER) || defined(__BORLANDC__) #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") #define gettimeofday(p1,p2) #endif /* _MSC_VER */ #endif /* _WIN32 */ #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef HAVE_TIME_H #include <time.h> #endif #ifdef __MINGW32__ #define _WINSOCKAPI_ #include <wsockcompat.h> #include <winsock2.h> #undef XML_SOCKLEN_T #define XML_SOCKLEN_T unsigned int #endif #ifdef HAVE_SYS_TIMEB_H #include <sys/timeb.h> #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> /* seems needed for Solaris */ #ifndef MAP_FAILED #define MAP_FAILED ((void *) -1) #endif #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_LIBREADLINE #include <readline/readline.h> #ifdef HAVE_LIBHISTORY #include <readline/history.h> #endif #endif #include <libxml/xmlmemory.h> #include <libxml/parser.h> #include <libxml/parserInternals.h> #include <libxml/HTMLparser.h> #include <libxml/HTMLtree.h> #include <libxml/tree.h> #include <libxml/xpath.h> #include <libxml/debugXML.h> #include <libxml/xmlerror.h> #ifdef LIBXML_XINCLUDE_ENABLED #include <libxml/xinclude.h> #endif #ifdef LIBXML_CATALOG_ENABLED #include <libxml/catalog.h> #endif #include <libxml/globals.h> #include <libxml/xmlreader.h> #ifdef LIBXML_SCHEMATRON_ENABLED #include <libxml/schematron.h> #endif #ifdef LIBXML_SCHEMAS_ENABLED #include <libxml/relaxng.h> #include <libxml/xmlschemas.h> #endif #ifdef LIBXML_PATTERN_ENABLED #include <libxml/pattern.h> #endif #ifdef LIBXML_C14N_ENABLED #include <libxml/c14n.h> #endif #ifdef LIBXML_OUTPUT_ENABLED #include <libxml/xmlsave.h> #endif #ifndef XML_XML_DEFAULT_CATALOG #define XML_XML_DEFAULT_CATALOG "file:///etc/xml/catalog" #endif typedef enum { XMLLINT_RETURN_OK = 0, /* No error */ XMLLINT_ERR_UNCLASS, /* Unclassified */ XMLLINT_ERR_DTD, /* Error in DTD */ XMLLINT_ERR_VALID, /* Validation error */ XMLLINT_ERR_RDFILE, /* CtxtReadFile error */ XMLLINT_ERR_SCHEMACOMP, /* Schema compilation */ XMLLINT_ERR_OUT, /* Error writing output */ XMLLINT_ERR_SCHEMAPAT, /* Error in schema pattern */ XMLLINT_ERR_RDREGIS, /* Error in Reader registration */ XMLLINT_ERR_MEM /* Out of memory error */ } xmllintReturnCode; #ifdef LIBXML_DEBUG_ENABLED static int shell = 0; static int debugent = 0; #endif static int debug = 0; static int maxmem = 0; #ifdef LIBXML_TREE_ENABLED static int copy = 0; #endif /* LIBXML_TREE_ENABLED */ static int recovery = 0; static int noent = 0; static int noblanks = 0; static int noout = 0; static int nowrap = 0; #ifdef LIBXML_OUTPUT_ENABLED static int format = 0; static const char *output = NULL; static int compress = 0; static int oldout = 0; #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_VALID_ENABLED static int valid = 0; static int postvalid = 0; static char * dtdvalid = NULL; static char * dtdvalidfpi = NULL; #endif #ifdef LIBXML_SCHEMAS_ENABLED static char * relaxng = NULL; static xmlRelaxNGPtr relaxngschemas = NULL; static char * schema = NULL; static xmlSchemaPtr wxschemas = NULL; #endif #ifdef LIBXML_SCHEMATRON_ENABLED static char * schematron = NULL; static xmlSchematronPtr wxschematron = NULL; #endif static int repeat = 0; static int insert = 0; #if defined(LIBXML_HTML_ENABLED) || defined(LIBXML_VALID_ENABLED) static int html = 0; static int xmlout = 0; #endif static int htmlout = 0; #ifdef LIBXML_PUSH_ENABLED static int push = 0; #endif /* LIBXML_PUSH_ENABLED */ #ifdef HAVE_SYS_MMAN_H static int memory = 0; #endif static int testIO = 0; static char *encoding = NULL; #ifdef LIBXML_XINCLUDE_ENABLED static int xinclude = 0; #endif static int dtdattrs = 0; static int loaddtd = 0; static xmllintReturnCode progresult = XMLLINT_RETURN_OK; static int timing = 0; static int generate = 0; static int dropdtd = 0; #ifdef LIBXML_CATALOG_ENABLED static int catalogs = 0; static int nocatalogs = 0; #endif #ifdef LIBXML_C14N_ENABLED static int canonical = 0; static int canonical_11 = 0; static int exc_canonical = 0; #endif #ifdef LIBXML_READER_ENABLED static int stream = 0; static int walker = 0; #endif /* LIBXML_READER_ENABLED */ static int chkregister = 0; static int nbregister = 0; #ifdef LIBXML_SAX1_ENABLED static int sax1 = 0; #endif /* LIBXML_SAX1_ENABLED */ #ifdef LIBXML_PATTERN_ENABLED static const char *pattern = NULL; static xmlPatternPtr patternc = NULL; static xmlStreamCtxtPtr patstream = NULL; #endif static int options = XML_PARSE_COMPACT; static int sax = 0; static int oldxml10 = 0; /************************************************************************ * * * Entity loading control and customization. * * * ************************************************************************/ #define MAX_PATHS 64 #ifdef _WIN32 # define PATH_SEPARATOR ';' #else # define PATH_SEPARATOR ':' #endif static xmlChar *paths[MAX_PATHS + 1]; static int nbpaths = 0; static int load_trace = 0; static void parsePath(const xmlChar *path) { const xmlChar *cur; if (path == NULL) return; while (*path != 0) { if (nbpaths >= MAX_PATHS) { fprintf(stderr, "MAX_PATHS reached: too many paths\n"); return; } cur = path; while ((*cur == ' ') || (*cur == PATH_SEPARATOR)) cur++; path = cur; while ((*cur != 0) && (*cur != ' ') && (*cur != PATH_SEPARATOR)) cur++; if (cur != path) { paths[nbpaths] = xmlStrndup(path, cur - path); if (paths[nbpaths] != NULL) nbpaths++; path = cur; } } } static xmlExternalEntityLoader defaultEntityLoader = NULL; static xmlParserInputPtr xmllintExternalEntityLoader(const char *URL, const char *ID, xmlParserCtxtPtr ctxt) { xmlParserInputPtr ret; warningSAXFunc warning = NULL; errorSAXFunc err = NULL; int i; const char *lastsegment = URL; const char *iter = URL; if ((nbpaths > 0) && (iter != NULL)) { while (*iter != 0) { if (*iter == '/') lastsegment = iter + 1; iter++; } } if ((ctxt != NULL) && (ctxt->sax != NULL)) { warning = ctxt->sax->warning; err = ctxt->sax->error; ctxt->sax->warning = NULL; ctxt->sax->error = NULL; } if (defaultEntityLoader != NULL) { ret = defaultEntityLoader(URL, ID, ctxt); if (ret != NULL) { if (warning != NULL) ctxt->sax->warning = warning; if (err != NULL) ctxt->sax->error = err; if (load_trace) { fprintf \ (stderr, "Loaded URL=\"%s\" ID=\"%s\"\n", URL ? URL : "(null)", ID ? ID : "(null)"); } return(ret); } } for (i = 0;i < nbpaths;i++) { xmlChar *newURL; newURL = xmlStrdup((const xmlChar *) paths[i]); newURL = xmlStrcat(newURL, (const xmlChar *) "/"); newURL = xmlStrcat(newURL, (const xmlChar *) lastsegment); if (newURL != NULL) { ret = defaultEntityLoader((const char *)newURL, ID, ctxt); if (ret != NULL) { if (warning != NULL) ctxt->sax->warning = warning; if (err != NULL) ctxt->sax->error = err; if (load_trace) { fprintf \ (stderr, "Loaded URL=\"%s\" ID=\"%s\"\n", newURL, ID ? ID : "(null)"); } xmlFree(newURL); return(ret); } xmlFree(newURL); } } if (err != NULL) ctxt->sax->error = err; if (warning != NULL) { ctxt->sax->warning = warning; if (URL != NULL) warning(ctxt, "failed to load external entity \"%s\"\n", URL); else if (ID != NULL) warning(ctxt, "failed to load external entity \"%s\"\n", ID); } return(NULL); } /************************************************************************ * * * Memory allocation consumption debugging * * * ************************************************************************/ static void OOM(void) { fprintf(stderr, "Ran out of memory needs > %d bytes\n", maxmem); progresult = XMLLINT_ERR_MEM; } static void myFreeFunc(void *mem) { xmlMemFree(mem); } static void * myMallocFunc(size_t size) { void *ret; ret = xmlMemMalloc(size); if (ret != NULL) { if (xmlMemUsed() > maxmem) { OOM(); xmlMemFree(ret); return (NULL); } } return (ret); } static void * myReallocFunc(void *mem, size_t size) { void *ret; ret = xmlMemRealloc(mem, size); if (ret != NULL) { if (xmlMemUsed() > maxmem) { OOM(); xmlMemFree(ret); return (NULL); } } return (ret); } static char * myStrdupFunc(const char *str) { char *ret; ret = xmlMemoryStrdup(str); if (ret != NULL) { if (xmlMemUsed() > maxmem) { OOM(); xmlFree(ret); return (NULL); } } return (ret); } /************************************************************************ * * * Internal timing routines to remove the necessity to have * * unix-specific function calls. * * * ************************************************************************/ #ifndef HAVE_GETTIMEOFDAY #ifdef HAVE_SYS_TIMEB_H #ifdef HAVE_SYS_TIME_H #ifdef HAVE_FTIME static int my_gettimeofday(struct timeval *tvp, void *tzp) { struct timeb timebuffer; ftime(&timebuffer); if (tvp) { tvp->tv_sec = timebuffer.time; tvp->tv_usec = timebuffer.millitm * 1000L; } return (0); } #define HAVE_GETTIMEOFDAY 1 #define gettimeofday my_gettimeofday #endif /* HAVE_FTIME */ #endif /* HAVE_SYS_TIME_H */ #endif /* HAVE_SYS_TIMEB_H */ #endif /* !HAVE_GETTIMEOFDAY */ #if defined(HAVE_GETTIMEOFDAY) static struct timeval begin, end; /* * startTimer: call where you want to start timing */ static void startTimer(void) { gettimeofday(&begin, NULL); } /* * endTimer: call where you want to stop timing and to print out a * message about the timing performed; format is a printf * type argument */ static void XMLCDECL endTimer(const char *fmt, ...) { long msec; va_list ap; gettimeofday(&end, NULL); msec = end.tv_sec - begin.tv_sec; msec *= 1000; msec += (end.tv_usec - begin.tv_usec) / 1000; #ifndef HAVE_STDARG_H #error "endTimer required stdarg functions" #endif va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, " took %ld ms\n", msec); } #elif defined(HAVE_TIME_H) /* * No gettimeofday function, so we have to make do with calling clock. * This is obviously less accurate, but there's little we can do about * that. */ #ifndef CLOCKS_PER_SEC #define CLOCKS_PER_SEC 100 #endif static clock_t begin, end; static void startTimer(void) { begin = clock(); } static void XMLCDECL endTimer(const char *fmt, ...) { long msec; va_list ap; end = clock(); msec = ((end - begin) * 1000) / CLOCKS_PER_SEC; #ifndef HAVE_STDARG_H #error "endTimer required stdarg functions" #endif va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, " took %ld ms\n", msec); } #else /* * We don't have a gettimeofday or time.h, so we just don't do timing */ static void startTimer(void) { /* * Do nothing */ } static void XMLCDECL endTimer(char *format, ...) { /* * We cannot do anything because we don't have a timing function */ #ifdef HAVE_STDARG_H va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); fprintf(stderr, " was not timed\n", msec); #else /* We don't have gettimeofday, time or stdarg.h, what crazy world is * this ?! */ #endif } #endif /************************************************************************ * * * HTML ouput * * * ************************************************************************/ static char buffer[50000]; static void xmlHTMLEncodeSend(void) { char *result; result = (char *) xmlEncodeEntitiesReentrant(NULL, BAD_CAST buffer); if (result) { xmlGenericError(xmlGenericErrorContext, "%s", result); xmlFree(result); } buffer[0] = 0; } /** * xmlHTMLPrintFileInfo: * @input: an xmlParserInputPtr input * * Displays the associated file and line informations for the current input */ static void xmlHTMLPrintFileInfo(xmlParserInputPtr input) { int len; xmlGenericError(xmlGenericErrorContext, "<p>"); len = strlen(buffer); if (input != NULL) { if (input->filename) { snprintf(&buffer[len], sizeof(buffer) - len, "%s:%d: ", input->filename, input->line); } else { snprintf(&buffer[len], sizeof(buffer) - len, "Entity: line %d: ", input->line); } } xmlHTMLEncodeSend(); } /** * xmlHTMLPrintFileContext: * @input: an xmlParserInputPtr input * * Displays current context within the input content for error tracking */ static void xmlHTMLPrintFileContext(xmlParserInputPtr input) { const xmlChar *cur, *base; int len; int n; if (input == NULL) return; xmlGenericError(xmlGenericErrorContext, "<pre>\n"); cur = input->cur; base = input->base; while ((cur > base) && ((*cur == '\n') || (*cur == '\r'))) { cur--; } n = 0; while ((n++ < 80) && (cur > base) && (*cur != '\n') && (*cur != '\r')) cur--; if ((*cur == '\n') || (*cur == '\r')) cur++; base = cur; n = 0; while ((*cur != 0) && (*cur != '\n') && (*cur != '\r') && (n < 79)) { len = strlen(buffer); snprintf(&buffer[len], sizeof(buffer) - len, "%c", (unsigned char) *cur++); n++; } len = strlen(buffer); snprintf(&buffer[len], sizeof(buffer) - len, "\n"); cur = input->cur; while ((*cur == '\n') || (*cur == '\r')) cur--; n = 0; while ((cur != base) && (n++ < 80)) { len = strlen(buffer); snprintf(&buffer[len], sizeof(buffer) - len, " "); base++; } len = strlen(buffer); snprintf(&buffer[len], sizeof(buffer) - len, "^\n"); xmlHTMLEncodeSend(); xmlGenericError(xmlGenericErrorContext, "</pre>"); } /** * xmlHTMLError: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format an error messages, gives file, line, position and * extra parameters. */ static void XMLCDECL xmlHTMLError(void *ctx, const char *msg, ...) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; xmlParserInputPtr input; va_list args; int len; buffer[0] = 0; input = ctxt->input; if ((input != NULL) && (input->filename == NULL) && (ctxt->inputNr > 1)) { input = ctxt->inputTab[ctxt->inputNr - 2]; } xmlHTMLPrintFileInfo(input); xmlGenericError(xmlGenericErrorContext, "<b>error</b>: "); va_start(args, msg); len = strlen(buffer); vsnprintf(&buffer[len], sizeof(buffer) - len, msg, args); va_end(args); xmlHTMLEncodeSend(); xmlGenericError(xmlGenericErrorContext, "</p>\n"); xmlHTMLPrintFileContext(input); xmlHTMLEncodeSend(); } /** * xmlHTMLWarning: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format a warning messages, gives file, line, position and * extra parameters. */ static void XMLCDECL xmlHTMLWarning(void *ctx, const char *msg, ...) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; xmlParserInputPtr input; va_list args; int len; buffer[0] = 0; input = ctxt->input; if ((input != NULL) && (input->filename == NULL) && (ctxt->inputNr > 1)) { input = ctxt->inputTab[ctxt->inputNr - 2]; } xmlHTMLPrintFileInfo(input); xmlGenericError(xmlGenericErrorContext, "<b>warning</b>: "); va_start(args, msg); len = strlen(buffer); vsnprintf(&buffer[len], sizeof(buffer) - len, msg, args); va_end(args); xmlHTMLEncodeSend(); xmlGenericError(xmlGenericErrorContext, "</p>\n"); xmlHTMLPrintFileContext(input); xmlHTMLEncodeSend(); } /** * xmlHTMLValidityError: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format an validity error messages, gives file, * line, position and extra parameters. */ static void XMLCDECL xmlHTMLValidityError(void *ctx, const char *msg, ...) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; xmlParserInputPtr input; va_list args; int len; buffer[0] = 0; input = ctxt->input; if ((input->filename == NULL) && (ctxt->inputNr > 1)) input = ctxt->inputTab[ctxt->inputNr - 2]; xmlHTMLPrintFileInfo(input); xmlGenericError(xmlGenericErrorContext, "<b>validity error</b>: "); len = strlen(buffer); va_start(args, msg); vsnprintf(&buffer[len], sizeof(buffer) - len, msg, args); va_end(args); xmlHTMLEncodeSend(); xmlGenericError(xmlGenericErrorContext, "</p>\n"); xmlHTMLPrintFileContext(input); xmlHTMLEncodeSend(); progresult = XMLLINT_ERR_VALID; } /** * xmlHTMLValidityWarning: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format a validity warning messages, gives file, line, * position and extra parameters. */ static void XMLCDECL xmlHTMLValidityWarning(void *ctx, const char *msg, ...) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; xmlParserInputPtr input; va_list args; int len; buffer[0] = 0; input = ctxt->input; if ((input->filename == NULL) && (ctxt->inputNr > 1)) input = ctxt->inputTab[ctxt->inputNr - 2]; xmlHTMLPrintFileInfo(input); xmlGenericError(xmlGenericErrorContext, "<b>validity warning</b>: "); va_start(args, msg); len = strlen(buffer); vsnprintf(&buffer[len], sizeof(buffer) - len, msg, args); va_end(args); xmlHTMLEncodeSend(); xmlGenericError(xmlGenericErrorContext, "</p>\n"); xmlHTMLPrintFileContext(input); xmlHTMLEncodeSend(); } /************************************************************************ * * * Shell Interface * * * ************************************************************************/ #ifdef LIBXML_DEBUG_ENABLED #ifdef LIBXML_XPATH_ENABLED /** * xmlShellReadline: * @prompt: the prompt value * * Read a string * * Returns a pointer to it or NULL on EOF the caller is expected to * free the returned string. */ static char * xmlShellReadline(char *prompt) { #ifdef HAVE_LIBREADLINE char *line_read; /* Get a line from the user. */ line_read = readline (prompt); /* If the line has any text in it, save it on the history. */ if (line_read && *line_read) add_history (line_read); return (line_read); #else char line_read[501]; char *ret; int len; if (prompt != NULL) fprintf(stdout, "%s", prompt); if (!fgets(line_read, 500, stdin)) return(NULL); line_read[500] = 0; len = strlen(line_read); ret = (char *) malloc(len + 1); if (ret != NULL) { memcpy (ret, line_read, len + 1); } return(ret); #endif } #endif /* LIBXML_XPATH_ENABLED */ #endif /* LIBXML_DEBUG_ENABLED */ /************************************************************************ * * * I/O Interfaces * * * ************************************************************************/ static int myRead(FILE *f, char * buf, int len) { return(fread(buf, 1, len, f)); } static void myClose(FILE *f) { if (f != stdin) { fclose(f); } } /************************************************************************ * * * SAX based tests * * * ************************************************************************/ /* * empty SAX block */ static xmlSAXHandler emptySAXHandlerStruct = { NULL, /* internalSubset */ NULL, /* isStandalone */ NULL, /* hasInternalSubset */ NULL, /* hasExternalSubset */ NULL, /* resolveEntity */ NULL, /* getEntity */ NULL, /* entityDecl */ NULL, /* notationDecl */ NULL, /* attributeDecl */ NULL, /* elementDecl */ NULL, /* unparsedEntityDecl */ NULL, /* setDocumentLocator */ NULL, /* startDocument */ NULL, /* endDocument */ NULL, /* startElement */ NULL, /* endElement */ NULL, /* reference */ NULL, /* characters */ NULL, /* ignorableWhitespace */ NULL, /* processingInstruction */ NULL, /* comment */ NULL, /* xmlParserWarning */ NULL, /* xmlParserError */ NULL, /* xmlParserError */ NULL, /* getParameterEntity */ NULL, /* cdataBlock; */ NULL, /* externalSubset; */ XML_SAX2_MAGIC, NULL, NULL, /* startElementNs */ NULL, /* endElementNs */ NULL /* xmlStructuredErrorFunc */ }; static xmlSAXHandlerPtr emptySAXHandler = &emptySAXHandlerStruct; extern xmlSAXHandlerPtr debugSAXHandler; static int callbacks; /** * isStandaloneDebug: * @ctxt: An XML parser context * * Is this document tagged standalone ? * * Returns 1 if true */ static int isStandaloneDebug(void *ctx ATTRIBUTE_UNUSED) { callbacks++; if (noout) return(0); fprintf(stdout, "SAX.isStandalone()\n"); return(0); } /** * hasInternalSubsetDebug: * @ctxt: An XML parser context * * Does this document has an internal subset * * Returns 1 if true */ static int hasInternalSubsetDebug(void *ctx ATTRIBUTE_UNUSED) { callbacks++; if (noout) return(0); fprintf(stdout, "SAX.hasInternalSubset()\n"); return(0); } /** * hasExternalSubsetDebug: * @ctxt: An XML parser context * * Does this document has an external subset * * Returns 1 if true */ static int hasExternalSubsetDebug(void *ctx ATTRIBUTE_UNUSED) { callbacks++; if (noout) return(0); fprintf(stdout, "SAX.hasExternalSubset()\n"); return(0); } /** * internalSubsetDebug: * @ctxt: An XML parser context * * Does this document has an internal subset */ static void internalSubsetDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) { callbacks++; if (noout) return; fprintf(stdout, "SAX.internalSubset(%s,", name); if (ExternalID == NULL) fprintf(stdout, " ,"); else fprintf(stdout, " %s,", ExternalID); if (SystemID == NULL) fprintf(stdout, " )\n"); else fprintf(stdout, " %s)\n", SystemID); } /** * externalSubsetDebug: * @ctxt: An XML parser context * * Does this document has an external subset */ static void externalSubsetDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) { callbacks++; if (noout) return; fprintf(stdout, "SAX.externalSubset(%s,", name); if (ExternalID == NULL) fprintf(stdout, " ,"); else fprintf(stdout, " %s,", ExternalID); if (SystemID == NULL) fprintf(stdout, " )\n"); else fprintf(stdout, " %s)\n", SystemID); } /** * resolveEntityDebug: * @ctxt: An XML parser context * @publicId: The public ID of the entity * @systemId: The system ID of the entity * * Special entity resolver, better left to the parser, it has * more context than the application layer. * The default behaviour is to NOT resolve the entities, in that case * the ENTITY_REF nodes are built in the structure (and the parameter * values). * * Returns the xmlParserInputPtr if inlined or NULL for DOM behaviour. */ static xmlParserInputPtr resolveEntityDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *publicId, const xmlChar *systemId) { callbacks++; if (noout) return(NULL); /* xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; */ fprintf(stdout, "SAX.resolveEntity("); if (publicId != NULL) fprintf(stdout, "%s", (char *)publicId); else fprintf(stdout, " "); if (systemId != NULL) fprintf(stdout, ", %s)\n", (char *)systemId); else fprintf(stdout, ", )\n"); return(NULL); } /** * getEntityDebug: * @ctxt: An XML parser context * @name: The entity name * * Get an entity by name * * Returns the xmlParserInputPtr if inlined or NULL for DOM behaviour. */ static xmlEntityPtr getEntityDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name) { callbacks++; if (noout) return(NULL); fprintf(stdout, "SAX.getEntity(%s)\n", name); return(NULL); } /** * getParameterEntityDebug: * @ctxt: An XML parser context * @name: The entity name * * Get a parameter entity by name * * Returns the xmlParserInputPtr */ static xmlEntityPtr getParameterEntityDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name) { callbacks++; if (noout) return(NULL); fprintf(stdout, "SAX.getParameterEntity(%s)\n", name); return(NULL); } /** * entityDeclDebug: * @ctxt: An XML parser context * @name: the entity name * @type: the entity type * @publicId: The public ID of the entity * @systemId: The system ID of the entity * @content: the entity value (without processing). * * An entity definition has been parsed */ static void entityDeclDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content) { const xmlChar *nullstr = BAD_CAST "(null)"; /* not all libraries handle printing null pointers nicely */ if (publicId == NULL) publicId = nullstr; if (systemId == NULL) systemId = nullstr; if (content == NULL) content = (xmlChar *)nullstr; callbacks++; if (noout) return; fprintf(stdout, "SAX.entityDecl(%s, %d, %s, %s, %s)\n", name, type, publicId, systemId, content); } /** * attributeDeclDebug: * @ctxt: An XML parser context * @name: the attribute name * @type: the attribute type * * An attribute definition has been parsed */ static void attributeDeclDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar * elem, const xmlChar * name, int type, int def, const xmlChar * defaultValue, xmlEnumerationPtr tree) { callbacks++; if (noout) return; if (defaultValue == NULL) fprintf(stdout, "SAX.attributeDecl(%s, %s, %d, %d, NULL, ...)\n", elem, name, type, def); else fprintf(stdout, "SAX.attributeDecl(%s, %s, %d, %d, %s, ...)\n", elem, name, type, def, defaultValue); xmlFreeEnumeration(tree); } /** * elementDeclDebug: * @ctxt: An XML parser context * @name: the element name * @type: the element type * @content: the element value (without processing). * * An element definition has been parsed */ static void elementDeclDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, int type, xmlElementContentPtr content ATTRIBUTE_UNUSED) { callbacks++; if (noout) return; fprintf(stdout, "SAX.elementDecl(%s, %d, ...)\n", name, type); } /** * notationDeclDebug: * @ctxt: An XML parser context * @name: The name of the notation * @publicId: The public ID of the entity * @systemId: The system ID of the entity * * What to do when a notation declaration has been parsed. */ static void notationDeclDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId) { callbacks++; if (noout) return; fprintf(stdout, "SAX.notationDecl(%s, %s, %s)\n", (char *) name, (char *) publicId, (char *) systemId); } /** * unparsedEntityDeclDebug: * @ctxt: An XML parser context * @name: The name of the entity * @publicId: The public ID of the entity * @systemId: The system ID of the entity * @notationName: the name of the notation * * What to do when an unparsed entity declaration is parsed */ static void unparsedEntityDeclDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId, const xmlChar *notationName) { const xmlChar *nullstr = BAD_CAST "(null)"; if (publicId == NULL) publicId = nullstr; if (systemId == NULL) systemId = nullstr; if (notationName == NULL) notationName = nullstr; callbacks++; if (noout) return; fprintf(stdout, "SAX.unparsedEntityDecl(%s, %s, %s, %s)\n", (char *) name, (char *) publicId, (char *) systemId, (char *) notationName); } /** * setDocumentLocatorDebug: * @ctxt: An XML parser context * @loc: A SAX Locator * * Receive the document locator at startup, actually xmlDefaultSAXLocator * Everything is available on the context, so this is useless in our case. */ static void setDocumentLocatorDebug(void *ctx ATTRIBUTE_UNUSED, xmlSAXLocatorPtr loc ATTRIBUTE_UNUSED) { callbacks++; if (noout) return; fprintf(stdout, "SAX.setDocumentLocator()\n"); } /** * startDocumentDebug: * @ctxt: An XML parser context * * called when the document start being processed. */ static void startDocumentDebug(void *ctx ATTRIBUTE_UNUSED) { callbacks++; if (noout) return; fprintf(stdout, "SAX.startDocument()\n"); } /** * endDocumentDebug: * @ctxt: An XML parser context * * called when the document end has been detected. */ static void endDocumentDebug(void *ctx ATTRIBUTE_UNUSED) { callbacks++; if (noout) return; fprintf(stdout, "SAX.endDocument()\n"); } /** * startElementDebug: * @ctxt: An XML parser context * @name: The element name * * called when an opening tag has been processed. */ static void startElementDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar **atts) { int i; callbacks++; if (noout) return; fprintf(stdout, "SAX.startElement(%s", (char *) name); if (atts != NULL) { for (i = 0;(atts[i] != NULL);i++) { fprintf(stdout, ", %s='", atts[i++]); if (atts[i] != NULL) fprintf(stdout, "%s'", atts[i]); } } fprintf(stdout, ")\n"); } /** * endElementDebug: * @ctxt: An XML parser context * @name: The element name * * called when the end of an element has been detected. */ static void endElementDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name) { callbacks++; if (noout) return; fprintf(stdout, "SAX.endElement(%s)\n", (char *) name); } /** * charactersDebug: * @ctxt: An XML parser context * @ch: a xmlChar string * @len: the number of xmlChar * * receiving some chars from the parser. * Question: how much at a time ??? */ static void charactersDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *ch, int len) { char out[40]; int i; callbacks++; if (noout) return; for (i = 0;(i<len) && (i < 30);i++) out[i] = ch[i]; out[i] = 0; fprintf(stdout, "SAX.characters(%s, %d)\n", out, len); } /** * referenceDebug: * @ctxt: An XML parser context * @name: The entity name * * called when an entity reference is detected. */ static void referenceDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name) { callbacks++; if (noout) return; fprintf(stdout, "SAX.reference(%s)\n", name); } /** * ignorableWhitespaceDebug: * @ctxt: An XML parser context * @ch: a xmlChar string * @start: the first char in the string * @len: the number of xmlChar * * receiving some ignorable whitespaces from the parser. * Question: how much at a time ??? */ static void ignorableWhitespaceDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *ch, int len) { char out[40]; int i; callbacks++; if (noout) return; for (i = 0;(i<len) && (i < 30);i++) out[i] = ch[i]; out[i] = 0; fprintf(stdout, "SAX.ignorableWhitespace(%s, %d)\n", out, len); } /** * processingInstructionDebug: * @ctxt: An XML parser context * @target: the target name * @data: the PI data's * @len: the number of xmlChar * * A processing instruction has been parsed. */ static void processingInstructionDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *target, const xmlChar *data) { callbacks++; if (noout) return; if (data != NULL) fprintf(stdout, "SAX.processingInstruction(%s, %s)\n", (char *) target, (char *) data); else fprintf(stdout, "SAX.processingInstruction(%s, NULL)\n", (char *) target); } /** * cdataBlockDebug: * @ctx: the user data (XML parser context) * @value: The pcdata content * @len: the block length * * called when a pcdata block has been parsed */ static void cdataBlockDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *value, int len) { callbacks++; if (noout) return; fprintf(stdout, "SAX.pcdata(%.20s, %d)\n", (char *) value, len); } /** * commentDebug: * @ctxt: An XML parser context * @value: the comment content * * A comment has been parsed. */ static void commentDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *value) { callbacks++; if (noout) return; fprintf(stdout, "SAX.comment(%s)\n", value); } /** * warningDebug: * @ctxt: An XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format a warning messages, gives file, line, position and * extra parameters. */ static void XMLCDECL warningDebug(void *ctx ATTRIBUTE_UNUSED, const char *msg, ...) { va_list args; callbacks++; if (noout) return; va_start(args, msg); fprintf(stdout, "SAX.warning: "); vfprintf(stdout, msg, args); va_end(args); } /** * errorDebug: * @ctxt: An XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format a error messages, gives file, line, position and * extra parameters. */ static void XMLCDECL errorDebug(void *ctx ATTRIBUTE_UNUSED, const char *msg, ...) { va_list args; callbacks++; if (noout) return; va_start(args, msg); fprintf(stdout, "SAX.error: "); vfprintf(stdout, msg, args); va_end(args); } /** * fatalErrorDebug: * @ctxt: An XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format a fatalError messages, gives file, line, position and * extra parameters. */ static void XMLCDECL fatalErrorDebug(void *ctx ATTRIBUTE_UNUSED, const char *msg, ...) { va_list args; callbacks++; if (noout) return; va_start(args, msg); fprintf(stdout, "SAX.fatalError: "); vfprintf(stdout, msg, args); va_end(args); } static xmlSAXHandler debugSAXHandlerStruct = { internalSubsetDebug, isStandaloneDebug, hasInternalSubsetDebug, hasExternalSubsetDebug, resolveEntityDebug, getEntityDebug, entityDeclDebug, notationDeclDebug, attributeDeclDebug, elementDeclDebug, unparsedEntityDeclDebug, setDocumentLocatorDebug, startDocumentDebug, endDocumentDebug, startElementDebug, endElementDebug, referenceDebug, charactersDebug, ignorableWhitespaceDebug, processingInstructionDebug, commentDebug, warningDebug, errorDebug, fatalErrorDebug, getParameterEntityDebug, cdataBlockDebug, externalSubsetDebug, 1, NULL, NULL, NULL, NULL }; xmlSAXHandlerPtr debugSAXHandler = &debugSAXHandlerStruct; /* * SAX2 specific callbacks */ /** * startElementNsDebug: * @ctxt: An XML parser context * @name: The element name * * called when an opening tag has been processed. */ static void startElementNsDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes) { int i; callbacks++; if (noout) return; fprintf(stdout, "SAX.startElementNs(%s", (char *) localname); if (prefix == NULL) fprintf(stdout, ", NULL"); else fprintf(stdout, ", %s", (char *) prefix); if (URI == NULL) fprintf(stdout, ", NULL"); else fprintf(stdout, ", '%s'", (char *) URI); fprintf(stdout, ", %d", nb_namespaces); if (namespaces != NULL) { for (i = 0;i < nb_namespaces * 2;i++) { fprintf(stdout, ", xmlns"); if (namespaces[i] != NULL) fprintf(stdout, ":%s", namespaces[i]); i++; fprintf(stdout, "='%s'", namespaces[i]); } } fprintf(stdout, ", %d, %d", nb_attributes, nb_defaulted); if (attributes != NULL) { for (i = 0;i < nb_attributes * 5;i += 5) { if (attributes[i + 1] != NULL) fprintf(stdout, ", %s:%s='", attributes[i + 1], attributes[i]); else fprintf(stdout, ", %s='", attributes[i]); fprintf(stdout, "%.4s...', %d", attributes[i + 3], (int)(attributes[i + 4] - attributes[i + 3])); } } fprintf(stdout, ")\n"); } /** * endElementDebug: * @ctxt: An XML parser context * @name: The element name * * called when the end of an element has been detected. */ static void endElementNsDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI) { callbacks++; if (noout) return; fprintf(stdout, "SAX.endElementNs(%s", (char *) localname); if (prefix == NULL) fprintf(stdout, ", NULL"); else fprintf(stdout, ", %s", (char *) prefix); if (URI == NULL) fprintf(stdout, ", NULL)\n"); else fprintf(stdout, ", '%s')\n", (char *) URI); } static xmlSAXHandler debugSAX2HandlerStruct = { internalSubsetDebug, isStandaloneDebug, hasInternalSubsetDebug, hasExternalSubsetDebug, resolveEntityDebug, getEntityDebug, entityDeclDebug, notationDeclDebug, attributeDeclDebug, elementDeclDebug, unparsedEntityDeclDebug, setDocumentLocatorDebug, startDocumentDebug, endDocumentDebug, NULL, NULL, referenceDebug, charactersDebug, ignorableWhitespaceDebug, processingInstructionDebug, commentDebug, warningDebug, errorDebug, fatalErrorDebug, getParameterEntityDebug, cdataBlockDebug, externalSubsetDebug, XML_SAX2_MAGIC, NULL, startElementNsDebug, endElementNsDebug, NULL }; static xmlSAXHandlerPtr debugSAX2Handler = &debugSAX2HandlerStruct; static void testSAX(const char *filename) { xmlSAXHandlerPtr handler; const char *user_data = "user_data"; /* mostly for debugging */ xmlParserInputBufferPtr buf = NULL; xmlParserInputPtr inputStream; xmlParserCtxtPtr ctxt = NULL; xmlSAXHandlerPtr old_sax = NULL; callbacks = 0; if (noout) { handler = emptySAXHandler; #ifdef LIBXML_SAX1_ENABLED } else if (sax1) { handler = debugSAXHandler; #endif } else { handler = debugSAX2Handler; } /* * it's not the simplest code but the most generic in term of I/O */ buf = xmlParserInputBufferCreateFilename(filename, XML_CHAR_ENCODING_NONE); if (buf == NULL) { goto error; } #ifdef LIBXML_SCHEMAS_ENABLED if (wxschemas != NULL) { int ret; xmlSchemaValidCtxtPtr vctxt; vctxt = xmlSchemaNewValidCtxt(wxschemas); xmlSchemaSetValidErrors(vctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); ret = xmlSchemaValidateStream(vctxt, buf, 0, handler, (void *)user_data); if (repeat == 0) { if (ret == 0) { fprintf(stderr, "%s validates\n", filename); } else if (ret > 0) { fprintf(stderr, "%s fails to validate\n", filename); progresult = XMLLINT_ERR_VALID; } else { fprintf(stderr, "%s validation generated an internal error\n", filename); progresult = XMLLINT_ERR_VALID; } } xmlSchemaFreeValidCtxt(vctxt); } else #endif { /* * Create the parser context amd hook the input */ ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { xmlFreeParserInputBuffer(buf); goto error; } old_sax = ctxt->sax; ctxt->sax = handler; ctxt->userData = (void *) user_data; inputStream = xmlNewIOInputStream(ctxt, buf, XML_CHAR_ENCODING_NONE); if (inputStream == NULL) { xmlFreeParserInputBuffer(buf); goto error; } inputPush(ctxt, inputStream); /* do the parsing */ xmlParseDocument(ctxt); if (ctxt->myDoc != NULL) { fprintf(stderr, "SAX generated a doc !\n"); xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } } error: if (ctxt != NULL) { ctxt->sax = old_sax; xmlFreeParserCtxt(ctxt); } } /************************************************************************ * * * Stream Test processing * * * ************************************************************************/ #ifdef LIBXML_READER_ENABLED static void processNode(xmlTextReaderPtr reader) { const xmlChar *name, *value; int type, empty; type = xmlTextReaderNodeType(reader); empty = xmlTextReaderIsEmptyElement(reader); if (debug) { name = xmlTextReaderConstName(reader); if (name == NULL) name = BAD_CAST "--"; value = xmlTextReaderConstValue(reader); printf("%d %d %s %d %d", xmlTextReaderDepth(reader), type, name, empty, xmlTextReaderHasValue(reader)); if (value == NULL) printf("\n"); else { printf(" %s\n", value); } } #ifdef LIBXML_PATTERN_ENABLED if (patternc) { xmlChar *path = NULL; int match = -1; if (type == XML_READER_TYPE_ELEMENT) { /* do the check only on element start */ match = xmlPatternMatch(patternc, xmlTextReaderCurrentNode(reader)); if (match) { #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED) path = xmlGetNodePath(xmlTextReaderCurrentNode(reader)); printf("Node %s matches pattern %s\n", path, pattern); #else printf("Node %s matches pattern %s\n", xmlTextReaderConstName(reader), pattern); #endif } } if (patstream != NULL) { int ret; if (type == XML_READER_TYPE_ELEMENT) { ret = xmlStreamPush(patstream, xmlTextReaderConstLocalName(reader), xmlTextReaderConstNamespaceUri(reader)); if (ret < 0) { fprintf(stderr, "xmlStreamPush() failure\n"); xmlFreeStreamCtxt(patstream); patstream = NULL; } else if (ret != match) { #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED) if (path == NULL) { path = xmlGetNodePath( xmlTextReaderCurrentNode(reader)); } #endif fprintf(stderr, "xmlPatternMatch and xmlStreamPush disagree\n"); if (path != NULL) fprintf(stderr, " pattern %s node %s\n", pattern, path); else fprintf(stderr, " pattern %s node %s\n", pattern, xmlTextReaderConstName(reader)); } } if ((type == XML_READER_TYPE_END_ELEMENT) || ((type == XML_READER_TYPE_ELEMENT) && (empty))) { ret = xmlStreamPop(patstream); if (ret < 0) { fprintf(stderr, "xmlStreamPop() failure\n"); xmlFreeStreamCtxt(patstream); patstream = NULL; } } } if (path != NULL) xmlFree(path); } #endif } static void streamFile(char *filename) { xmlTextReaderPtr reader; int ret; #ifdef HAVE_SYS_MMAN_H int fd = -1; struct stat info; const char *base = NULL; xmlParserInputBufferPtr input = NULL; if (memory) { if (stat(filename, &info) < 0) return; if ((fd = open(filename, O_RDONLY)) < 0) return; base = mmap(NULL, info.st_size, PROT_READ, MAP_SHARED, fd, 0) ; if (base == (void *) MAP_FAILED) return; reader = xmlReaderForMemory(base, info.st_size, filename, NULL, options); } else #endif reader = xmlReaderForFile(filename, NULL, options); #ifdef LIBXML_PATTERN_ENABLED if (pattern != NULL) { patternc = xmlPatterncompile((const xmlChar *) pattern, NULL, 0, NULL); if (patternc == NULL) { xmlGenericError(xmlGenericErrorContext, "Pattern %s failed to compile\n", pattern); progresult = XMLLINT_ERR_SCHEMAPAT; pattern = NULL; } } if (patternc != NULL) { patstream = xmlPatternGetStreamCtxt(patternc); if (patstream != NULL) { ret = xmlStreamPush(patstream, NULL, NULL); if (ret < 0) { fprintf(stderr, "xmlStreamPush() failure\n"); xmlFreeStreamCtxt(patstream); patstream = NULL; } } } #endif if (reader != NULL) { #ifdef LIBXML_VALID_ENABLED if (valid) xmlTextReaderSetParserProp(reader, XML_PARSER_VALIDATE, 1); else #endif /* LIBXML_VALID_ENABLED */ xmlTextReaderSetParserProp(reader, XML_PARSER_LOADDTD, 1); #ifdef LIBXML_SCHEMAS_ENABLED if (relaxng != NULL) { if ((timing) && (!repeat)) { startTimer(); } ret = xmlTextReaderRelaxNGValidate(reader, relaxng); if (ret < 0) { xmlGenericError(xmlGenericErrorContext, "Relax-NG schema %s failed to compile\n", relaxng); progresult = XMLLINT_ERR_SCHEMACOMP; relaxng = NULL; } if ((timing) && (!repeat)) { endTimer("Compiling the schemas"); } } if (schema != NULL) { if ((timing) && (!repeat)) { startTimer(); } ret = xmlTextReaderSchemaValidate(reader, schema); if (ret < 0) { xmlGenericError(xmlGenericErrorContext, "XSD schema %s failed to compile\n", schema); progresult = XMLLINT_ERR_SCHEMACOMP; schema = NULL; } if ((timing) && (!repeat)) { endTimer("Compiling the schemas"); } } #endif /* * Process all nodes in sequence */ if ((timing) && (!repeat)) { startTimer(); } ret = xmlTextReaderRead(reader); while (ret == 1) { if ((debug) #ifdef LIBXML_PATTERN_ENABLED || (patternc) #endif ) processNode(reader); ret = xmlTextReaderRead(reader); } if ((timing) && (!repeat)) { #ifdef LIBXML_SCHEMAS_ENABLED if (relaxng != NULL) endTimer("Parsing and validating"); else #endif #ifdef LIBXML_VALID_ENABLED if (valid) endTimer("Parsing and validating"); else #endif endTimer("Parsing"); } #ifdef LIBXML_VALID_ENABLED if (valid) { if (xmlTextReaderIsValid(reader) != 1) { xmlGenericError(xmlGenericErrorContext, "Document %s does not validate\n", filename); progresult = XMLLINT_ERR_VALID; } } #endif /* LIBXML_VALID_ENABLED */ #ifdef LIBXML_SCHEMAS_ENABLED if ((relaxng != NULL) || (schema != NULL)) { if (xmlTextReaderIsValid(reader) != 1) { fprintf(stderr, "%s fails to validate\n", filename); progresult = XMLLINT_ERR_VALID; } else { fprintf(stderr, "%s validates\n", filename); } } #endif /* * Done, cleanup and status */ xmlFreeTextReader(reader); if (ret != 0) { fprintf(stderr, "%s : failed to parse\n", filename); progresult = XMLLINT_ERR_UNCLASS; } } else { fprintf(stderr, "Unable to open %s\n", filename); progresult = XMLLINT_ERR_UNCLASS; } #ifdef LIBXML_PATTERN_ENABLED if (patstream != NULL) { xmlFreeStreamCtxt(patstream); patstream = NULL; } #endif #ifdef HAVE_SYS_MMAN_H if (memory) { xmlFreeParserInputBuffer(input); munmap((char *) base, info.st_size); close(fd); } #endif } static void walkDoc(xmlDocPtr doc) { xmlTextReaderPtr reader; int ret; #ifdef LIBXML_PATTERN_ENABLED xmlNodePtr root; const xmlChar *namespaces[22]; int i; xmlNsPtr ns; root = xmlDocGetRootElement(doc); for (ns = root->nsDef, i = 0;ns != NULL && i < 20;ns=ns->next) { namespaces[i++] = ns->href; namespaces[i++] = ns->prefix; } namespaces[i++] = NULL; namespaces[i] = NULL; if (pattern != NULL) { patternc = xmlPatterncompile((const xmlChar *) pattern, doc->dict, 0, &namespaces[0]); if (patternc == NULL) { xmlGenericError(xmlGenericErrorContext, "Pattern %s failed to compile\n", pattern); progresult = XMLLINT_ERR_SCHEMAPAT; pattern = NULL; } } if (patternc != NULL) { patstream = xmlPatternGetStreamCtxt(patternc); if (patstream != NULL) { ret = xmlStreamPush(patstream, NULL, NULL); if (ret < 0) { fprintf(stderr, "xmlStreamPush() failure\n"); xmlFreeStreamCtxt(patstream); patstream = NULL; } } } #endif /* LIBXML_PATTERN_ENABLED */ reader = xmlReaderWalker(doc); if (reader != NULL) { if ((timing) && (!repeat)) { startTimer(); } ret = xmlTextReaderRead(reader); while (ret == 1) { if ((debug) #ifdef LIBXML_PATTERN_ENABLED || (patternc) #endif ) processNode(reader); ret = xmlTextReaderRead(reader); } if ((timing) && (!repeat)) { endTimer("walking through the doc"); } xmlFreeTextReader(reader); if (ret != 0) { fprintf(stderr, "failed to walk through the doc\n"); progresult = XMLLINT_ERR_UNCLASS; } } else { fprintf(stderr, "Failed to crate a reader from the document\n"); progresult = XMLLINT_ERR_UNCLASS; } #ifdef LIBXML_PATTERN_ENABLED if (patstream != NULL) { xmlFreeStreamCtxt(patstream); patstream = NULL; } #endif } #endif /* LIBXML_READER_ENABLED */ /************************************************************************ * * * Tree Test processing * * * ************************************************************************/ static void parseAndPrintFile(char *filename, xmlParserCtxtPtr rectxt) { xmlDocPtr doc = NULL; #ifdef LIBXML_TREE_ENABLED xmlDocPtr tmp; #endif /* LIBXML_TREE_ENABLED */ if ((timing) && (!repeat)) startTimer(); #ifdef LIBXML_TREE_ENABLED if (filename == NULL) { if (generate) { xmlNodePtr n; doc = xmlNewDoc(BAD_CAST "1.0"); n = xmlNewDocNode(doc, NULL, BAD_CAST "info", NULL); xmlNodeSetContent(n, BAD_CAST "abc"); xmlDocSetRootElement(doc, n); } } #endif /* LIBXML_TREE_ENABLED */ #ifdef LIBXML_HTML_ENABLED #ifdef LIBXML_PUSH_ENABLED else if ((html) && (push)) { FILE *f; #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) f = fopen(filename, "rb"); #else f = fopen(filename, "r"); #endif if (f != NULL) { int res, size = 3; char chars[4096]; htmlParserCtxtPtr ctxt; /* if (repeat) */ size = 4096; res = fread(chars, 1, 4, f); if (res > 0) { ctxt = htmlCreatePushParserCtxt(NULL, NULL, chars, res, filename, XML_CHAR_ENCODING_NONE); while ((res = fread(chars, 1, size, f)) > 0) { htmlParseChunk(ctxt, chars, res, 0); } htmlParseChunk(ctxt, chars, 0, 1); doc = ctxt->myDoc; htmlFreeParserCtxt(ctxt); } fclose(f); } } #endif /* LIBXML_PUSH_ENABLED */ #ifdef HAVE_SYS_MMAN_H else if ((html) && (memory)) { int fd; struct stat info; const char *base; if (stat(filename, &info) < 0) return; if ((fd = open(filename, O_RDONLY)) < 0) return; base = mmap(NULL, info.st_size, PROT_READ, MAP_SHARED, fd, 0) ; if (base == (void *) MAP_FAILED) return; doc = htmlReadMemory((char *) base, info.st_size, filename, NULL, options); munmap((char *) base, info.st_size); close(fd); } #endif else if (html) { doc = htmlReadFile(filename, NULL, options); } #endif /* LIBXML_HTML_ENABLED */ else { #ifdef LIBXML_PUSH_ENABLED /* * build an XML tree from a string; */ if (push) { FILE *f; /* '-' Usually means stdin -<sven@zen.org> */ if ((filename[0] == '-') && (filename[1] == 0)) { f = stdin; } else { #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) f = fopen(filename, "rb"); #else f = fopen(filename, "r"); #endif } if (f != NULL) { int ret; int res, size = 1024; char chars[1024]; xmlParserCtxtPtr ctxt; /* if (repeat) size = 1024; */ res = fread(chars, 1, 4, f); if (res > 0) { ctxt = xmlCreatePushParserCtxt(NULL, NULL, chars, res, filename); xmlCtxtUseOptions(ctxt, options); while ((res = fread(chars, 1, size, f)) > 0) { xmlParseChunk(ctxt, chars, res, 0); } xmlParseChunk(ctxt, chars, 0, 1); doc = ctxt->myDoc; ret = ctxt->wellFormed; xmlFreeParserCtxt(ctxt); if (!ret) { xmlFreeDoc(doc); doc = NULL; } } } } else #endif /* LIBXML_PUSH_ENABLED */ if (testIO) { if ((filename[0] == '-') && (filename[1] == 0)) { doc = xmlReadFd(0, NULL, NULL, options); } else { FILE *f; #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) f = fopen(filename, "rb"); #else f = fopen(filename, "r"); #endif if (f != NULL) { if (rectxt == NULL) doc = xmlReadIO((xmlInputReadCallback) myRead, (xmlInputCloseCallback) myClose, f, filename, NULL, options); else doc = xmlCtxtReadIO(rectxt, (xmlInputReadCallback) myRead, (xmlInputCloseCallback) myClose, f, filename, NULL, options); } else doc = NULL; } } else if (htmlout) { xmlParserCtxtPtr ctxt; if (rectxt == NULL) ctxt = xmlNewParserCtxt(); else ctxt = rectxt; if (ctxt == NULL) { doc = NULL; } else { ctxt->sax->error = xmlHTMLError; ctxt->sax->warning = xmlHTMLWarning; ctxt->vctxt.error = xmlHTMLValidityError; ctxt->vctxt.warning = xmlHTMLValidityWarning; doc = xmlCtxtReadFile(ctxt, filename, NULL, options); if (rectxt == NULL) xmlFreeParserCtxt(ctxt); } #ifdef HAVE_SYS_MMAN_H } else if (memory) { int fd; struct stat info; const char *base; if (stat(filename, &info) < 0) return; if ((fd = open(filename, O_RDONLY)) < 0) return; base = mmap(NULL, info.st_size, PROT_READ, MAP_SHARED, fd, 0) ; if (base == (void *) MAP_FAILED) return; if (rectxt == NULL) doc = xmlReadMemory((char *) base, info.st_size, filename, NULL, options); else doc = xmlCtxtReadMemory(rectxt, (char *) base, info.st_size, filename, NULL, options); munmap((char *) base, info.st_size); close(fd); #endif #ifdef LIBXML_VALID_ENABLED } else if (valid) { xmlParserCtxtPtr ctxt = NULL; if (rectxt == NULL) ctxt = xmlNewParserCtxt(); else ctxt = rectxt; if (ctxt == NULL) { doc = NULL; } else { doc = xmlCtxtReadFile(ctxt, filename, NULL, options); if (ctxt->valid == 0) progresult = XMLLINT_ERR_RDFILE; if (rectxt == NULL) xmlFreeParserCtxt(ctxt); } #endif /* LIBXML_VALID_ENABLED */ } else { if (rectxt != NULL) doc = xmlCtxtReadFile(rectxt, filename, NULL, options); else { #ifdef LIBXML_SAX1_ENABLED if (sax1) doc = xmlParseFile(filename); else #endif /* LIBXML_SAX1_ENABLED */ doc = xmlReadFile(filename, NULL, options); } } } /* * If we don't have a document we might as well give up. Do we * want an error message here? <sven@zen.org> */ if (doc == NULL) { progresult = XMLLINT_ERR_UNCLASS; return; } if ((timing) && (!repeat)) { endTimer("Parsing"); } /* * Remove DOCTYPE nodes */ if (dropdtd) { xmlDtdPtr dtd; dtd = xmlGetIntSubset(doc); if (dtd != NULL) { xmlUnlinkNode((xmlNodePtr)dtd); xmlFreeDtd(dtd); } } #ifdef LIBXML_XINCLUDE_ENABLED if (xinclude) { if ((timing) && (!repeat)) { startTimer(); } if (xmlXIncludeProcessFlags(doc, options) < 0) progresult = XMLLINT_ERR_UNCLASS; if ((timing) && (!repeat)) { endTimer("Xinclude processing"); } } #endif #ifdef LIBXML_DEBUG_ENABLED #ifdef LIBXML_XPATH_ENABLED /* * shell interaction */ if (shell) { xmlXPathOrderDocElems(doc); xmlShell(doc, filename, xmlShellReadline, stdout); } #endif #endif #ifdef LIBXML_TREE_ENABLED /* * test intermediate copy if needed. */ if (copy) { tmp = doc; if (timing) { startTimer(); } doc = xmlCopyDoc(doc, 1); if (timing) { endTimer("Copying"); } if (timing) { startTimer(); } xmlFreeDoc(tmp); if (timing) { endTimer("Freeing original"); } } #endif /* LIBXML_TREE_ENABLED */ #ifdef LIBXML_VALID_ENABLED if ((insert) && (!html)) { const xmlChar* list[256]; int nb, i; xmlNodePtr node; if (doc->children != NULL) { node = doc->children; while ((node != NULL) && (node->last == NULL)) node = node->next; if (node != NULL) { nb = xmlValidGetValidElements(node->last, NULL, list, 256); if (nb < 0) { fprintf(stderr, "could not get valid list of elements\n"); } else if (nb == 0) { fprintf(stderr, "No element can be inserted under root\n"); } else { fprintf(stderr, "%d element types can be inserted under root:\n", nb); for (i = 0;i < nb;i++) { fprintf(stderr, "%s\n", (char *) list[i]); } } } } }else #endif /* LIBXML_VALID_ENABLED */ #ifdef LIBXML_READER_ENABLED if (walker) { walkDoc(doc); } #endif /* LIBXML_READER_ENABLED */ #ifdef LIBXML_OUTPUT_ENABLED if (noout == 0) { int ret; /* * print it. */ #ifdef LIBXML_DEBUG_ENABLED if (!debug) { #endif if ((timing) && (!repeat)) { startTimer(); } #ifdef LIBXML_HTML_ENABLED if ((html) && (!xmlout)) { if (compress) { htmlSaveFile(output ? output : "-", doc); } else if (encoding != NULL) { if ( format ) { htmlSaveFileFormat(output ? output : "-", doc, encoding, 1); } else { htmlSaveFileFormat(output ? output : "-", doc, encoding, 0); } } else if (format) { htmlSaveFileFormat(output ? output : "-", doc, NULL, 1); } else { FILE *out; if (output == NULL) out = stdout; else { out = fopen(output,"wb"); } if (out != NULL) { if (htmlDocDump(out, doc) < 0) progresult = XMLLINT_ERR_OUT; if (output != NULL) fclose(out); } else { fprintf(stderr, "failed to open %s\n", output); progresult = XMLLINT_ERR_OUT; } } if ((timing) && (!repeat)) { endTimer("Saving"); } } else #endif #ifdef LIBXML_C14N_ENABLED if (canonical) { xmlChar *result = NULL; int size; size = xmlC14NDocDumpMemory(doc, NULL, XML_C14N_1_0, NULL, 1, &result); if (size >= 0) { write(1, result, size); xmlFree(result); } else { fprintf(stderr, "Failed to canonicalize\n"); progresult = XMLLINT_ERR_OUT; } } else if (canonical) { xmlChar *result = NULL; int size; size = xmlC14NDocDumpMemory(doc, NULL, XML_C14N_1_1, NULL, 1, &result); if (size >= 0) { write(1, result, size); xmlFree(result); } else { fprintf(stderr, "Failed to canonicalize\n"); progresult = XMLLINT_ERR_OUT; } } else if (exc_canonical) { xmlChar *result = NULL; int size; size = xmlC14NDocDumpMemory(doc, NULL, XML_C14N_EXCLUSIVE_1_0, NULL, 1, &result); if (size >= 0) { write(1, result, size); xmlFree(result); } else { fprintf(stderr, "Failed to canonicalize\n"); progresult = XMLLINT_ERR_OUT; } } else #endif #ifdef HAVE_SYS_MMAN_H if (memory) { xmlChar *result; int len; if (encoding != NULL) { if ( format ) { xmlDocDumpFormatMemoryEnc(doc, &result, &len, encoding, 1); } else { xmlDocDumpMemoryEnc(doc, &result, &len, encoding); } } else { if (format) xmlDocDumpFormatMemory(doc, &result, &len, 1); else xmlDocDumpMemory(doc, &result, &len); } if (result == NULL) { fprintf(stderr, "Failed to save\n"); progresult = XMLLINT_ERR_OUT; } else { write(1, result, len); xmlFree(result); } } else #endif /* HAVE_SYS_MMAN_H */ if (compress) { xmlSaveFile(output ? output : "-", doc); } else if (oldout) { if (encoding != NULL) { if ( format ) { ret = xmlSaveFormatFileEnc(output ? output : "-", doc, encoding, 1); } else { ret = xmlSaveFileEnc(output ? output : "-", doc, encoding); } if (ret < 0) { fprintf(stderr, "failed save to %s\n", output ? output : "-"); progresult = XMLLINT_ERR_OUT; } } else if (format) { ret = xmlSaveFormatFile(output ? output : "-", doc, 1); if (ret < 0) { fprintf(stderr, "failed save to %s\n", output ? output : "-"); progresult = XMLLINT_ERR_OUT; } } else { FILE *out; if (output == NULL) out = stdout; else { out = fopen(output,"wb"); } if (out != NULL) { if (xmlDocDump(out, doc) < 0) progresult = XMLLINT_ERR_OUT; if (output != NULL) fclose(out); } else { fprintf(stderr, "failed to open %s\n", output); progresult = XMLLINT_ERR_OUT; } } } else { xmlSaveCtxtPtr ctxt; int saveOpts = 0; if (format) saveOpts |= XML_SAVE_FORMAT; if (xmlout) saveOpts |= XML_SAVE_AS_XML; if (output == NULL) ctxt = xmlSaveToFd(1, encoding, saveOpts); else ctxt = xmlSaveToFilename(output, encoding, saveOpts); if (ctxt != NULL) { if (xmlSaveDoc(ctxt, doc) < 0) { fprintf(stderr, "failed save to %s\n", output ? output : "-"); progresult = XMLLINT_ERR_OUT; } xmlSaveClose(ctxt); } else { progresult = XMLLINT_ERR_OUT; } } if ((timing) && (!repeat)) { endTimer("Saving"); } #ifdef LIBXML_DEBUG_ENABLED } else { FILE *out; if (output == NULL) out = stdout; else { out = fopen(output,"wb"); } if (out != NULL) { xmlDebugDumpDocument(out, doc); if (output != NULL) fclose(out); } else { fprintf(stderr, "failed to open %s\n", output); progresult = XMLLINT_ERR_OUT; } } #endif } #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_VALID_ENABLED /* * A posteriori validation test */ if ((dtdvalid != NULL) || (dtdvalidfpi != NULL)) { xmlDtdPtr dtd; if ((timing) && (!repeat)) { startTimer(); } if (dtdvalid != NULL) dtd = xmlParseDTD(NULL, (const xmlChar *)dtdvalid); else dtd = xmlParseDTD((const xmlChar *)dtdvalidfpi, NULL); if ((timing) && (!repeat)) { endTimer("Parsing DTD"); } if (dtd == NULL) { if (dtdvalid != NULL) xmlGenericError(xmlGenericErrorContext, "Could not parse DTD %s\n", dtdvalid); else xmlGenericError(xmlGenericErrorContext, "Could not parse DTD %s\n", dtdvalidfpi); progresult = XMLLINT_ERR_DTD; } else { xmlValidCtxtPtr cvp; if ((cvp = xmlNewValidCtxt()) == NULL) { xmlGenericError(xmlGenericErrorContext, "Couldn't allocate validation context\n"); exit(-1); } cvp->userData = (void *) stderr; cvp->error = (xmlValidityErrorFunc) fprintf; cvp->warning = (xmlValidityWarningFunc) fprintf; if ((timing) && (!repeat)) { startTimer(); } if (!xmlValidateDtd(cvp, doc, dtd)) { if (dtdvalid != NULL) xmlGenericError(xmlGenericErrorContext, "Document %s does not validate against %s\n", filename, dtdvalid); else xmlGenericError(xmlGenericErrorContext, "Document %s does not validate against %s\n", filename, dtdvalidfpi); progresult = XMLLINT_ERR_VALID; } if ((timing) && (!repeat)) { endTimer("Validating against DTD"); } xmlFreeValidCtxt(cvp); xmlFreeDtd(dtd); } } else if (postvalid) { xmlValidCtxtPtr cvp; if ((cvp = xmlNewValidCtxt()) == NULL) { xmlGenericError(xmlGenericErrorContext, "Couldn't allocate validation context\n"); exit(-1); } if ((timing) && (!repeat)) { startTimer(); } cvp->userData = (void *) stderr; cvp->error = (xmlValidityErrorFunc) fprintf; cvp->warning = (xmlValidityWarningFunc) fprintf; if (!xmlValidateDocument(cvp, doc)) { xmlGenericError(xmlGenericErrorContext, "Document %s does not validate\n", filename); progresult = XMLLINT_ERR_VALID; } if ((timing) && (!repeat)) { endTimer("Validating"); } xmlFreeValidCtxt(cvp); } #endif /* LIBXML_VALID_ENABLED */ #ifdef LIBXML_SCHEMATRON_ENABLED if (wxschematron != NULL) { xmlSchematronValidCtxtPtr ctxt; int ret; int flag; if ((timing) && (!repeat)) { startTimer(); } if (debug) flag = XML_SCHEMATRON_OUT_XML; else flag = XML_SCHEMATRON_OUT_TEXT; if (noout) flag |= XML_SCHEMATRON_OUT_QUIET; ctxt = xmlSchematronNewValidCtxt(wxschematron, flag); #if 0 xmlSchematronSetValidErrors(ctxt, (xmlSchematronValidityErrorFunc) fprintf, (xmlSchematronValidityWarningFunc) fprintf, stderr); #endif ret = xmlSchematronValidateDoc(ctxt, doc); if (ret == 0) { fprintf(stderr, "%s validates\n", filename); } else if (ret > 0) { fprintf(stderr, "%s fails to validate\n", filename); progresult = XMLLINT_ERR_VALID; } else { fprintf(stderr, "%s validation generated an internal error\n", filename); progresult = XMLLINT_ERR_VALID; } xmlSchematronFreeValidCtxt(ctxt); if ((timing) && (!repeat)) { endTimer("Validating"); } } #endif #ifdef LIBXML_SCHEMAS_ENABLED if (relaxngschemas != NULL) { xmlRelaxNGValidCtxtPtr ctxt; int ret; if ((timing) && (!repeat)) { startTimer(); } ctxt = xmlRelaxNGNewValidCtxt(relaxngschemas); xmlRelaxNGSetValidErrors(ctxt, (xmlRelaxNGValidityErrorFunc) fprintf, (xmlRelaxNGValidityWarningFunc) fprintf, stderr); ret = xmlRelaxNGValidateDoc(ctxt, doc); if (ret == 0) { fprintf(stderr, "%s validates\n", filename); } else if (ret > 0) { fprintf(stderr, "%s fails to validate\n", filename); progresult = XMLLINT_ERR_VALID; } else { fprintf(stderr, "%s validation generated an internal error\n", filename); progresult = XMLLINT_ERR_VALID; } xmlRelaxNGFreeValidCtxt(ctxt); if ((timing) && (!repeat)) { endTimer("Validating"); } } else if (wxschemas != NULL) { xmlSchemaValidCtxtPtr ctxt; int ret; if ((timing) && (!repeat)) { startTimer(); } ctxt = xmlSchemaNewValidCtxt(wxschemas); xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); ret = xmlSchemaValidateDoc(ctxt, doc); if (ret == 0) { fprintf(stderr, "%s validates\n", filename); } else if (ret > 0) { fprintf(stderr, "%s fails to validate\n", filename); progresult = XMLLINT_ERR_VALID; } else { fprintf(stderr, "%s validation generated an internal error\n", filename); progresult = XMLLINT_ERR_VALID; } xmlSchemaFreeValidCtxt(ctxt); if ((timing) && (!repeat)) { endTimer("Validating"); } } #endif #ifdef LIBXML_DEBUG_ENABLED #if defined(LIBXML_HTML_ENABLED) || defined(LIBXML_VALID_ENABLED) if ((debugent) && (!html)) xmlDebugDumpEntities(stderr, doc); #endif #endif /* * free it. */ if ((timing) && (!repeat)) { startTimer(); } xmlFreeDoc(doc); if ((timing) && (!repeat)) { endTimer("Freeing"); } } /************************************************************************ * * * Usage and Main * * * ************************************************************************/ static void showVersion(const char *name) { fprintf(stderr, "%s: using libxml version %s\n", name, xmlParserVersion); fprintf(stderr, " compiled with: "); if (xmlHasFeature(XML_WITH_THREAD)) fprintf(stderr, "Threads "); if (xmlHasFeature(XML_WITH_TREE)) fprintf(stderr, "Tree "); if (xmlHasFeature(XML_WITH_OUTPUT)) fprintf(stderr, "Output "); if (xmlHasFeature(XML_WITH_PUSH)) fprintf(stderr, "Push "); if (xmlHasFeature(XML_WITH_READER)) fprintf(stderr, "Reader "); if (xmlHasFeature(XML_WITH_PATTERN)) fprintf(stderr, "Patterns "); if (xmlHasFeature(XML_WITH_WRITER)) fprintf(stderr, "Writer "); if (xmlHasFeature(XML_WITH_SAX1)) fprintf(stderr, "SAXv1 "); if (xmlHasFeature(XML_WITH_FTP)) fprintf(stderr, "FTP "); if (xmlHasFeature(XML_WITH_HTTP)) fprintf(stderr, "HTTP "); if (xmlHasFeature(XML_WITH_VALID)) fprintf(stderr, "DTDValid "); if (xmlHasFeature(XML_WITH_HTML)) fprintf(stderr, "HTML "); if (xmlHasFeature(XML_WITH_LEGACY)) fprintf(stderr, "Legacy "); if (xmlHasFeature(XML_WITH_C14N)) fprintf(stderr, "C14N "); if (xmlHasFeature(XML_WITH_CATALOG)) fprintf(stderr, "Catalog "); if (xmlHasFeature(XML_WITH_XPATH)) fprintf(stderr, "XPath "); if (xmlHasFeature(XML_WITH_XPTR)) fprintf(stderr, "XPointer "); if (xmlHasFeature(XML_WITH_XINCLUDE)) fprintf(stderr, "XInclude "); if (xmlHasFeature(XML_WITH_ICONV)) fprintf(stderr, "Iconv "); if (xmlHasFeature(XML_WITH_ISO8859X)) fprintf(stderr, "ISO8859X "); if (xmlHasFeature(XML_WITH_UNICODE)) fprintf(stderr, "Unicode "); if (xmlHasFeature(XML_WITH_REGEXP)) fprintf(stderr, "Regexps "); if (xmlHasFeature(XML_WITH_AUTOMATA)) fprintf(stderr, "Automata "); if (xmlHasFeature(XML_WITH_EXPR)) fprintf(stderr, "Expr "); if (xmlHasFeature(XML_WITH_SCHEMAS)) fprintf(stderr, "Schemas "); if (xmlHasFeature(XML_WITH_SCHEMATRON)) fprintf(stderr, "Schematron "); if (xmlHasFeature(XML_WITH_MODULES)) fprintf(stderr, "Modules "); if (xmlHasFeature(XML_WITH_DEBUG)) fprintf(stderr, "Debug "); if (xmlHasFeature(XML_WITH_DEBUG_MEM)) fprintf(stderr, "MemDebug "); if (xmlHasFeature(XML_WITH_DEBUG_RUN)) fprintf(stderr, "RunDebug "); if (xmlHasFeature(XML_WITH_ZLIB)) fprintf(stderr, "Zlib "); fprintf(stderr, "\n"); } static void usage(const char *name) { printf("Usage : %s [options] XMLfiles ...\n", name); #ifdef LIBXML_OUTPUT_ENABLED printf("\tParse the XML files and output the result of the parsing\n"); #else printf("\tParse the XML files\n"); #endif /* LIBXML_OUTPUT_ENABLED */ printf("\t--version : display the version of the XML library used\n"); #ifdef LIBXML_DEBUG_ENABLED printf("\t--debug : dump a debug tree of the in-memory document\n"); printf("\t--shell : run a navigating shell\n"); printf("\t--debugent : debug the entities defined in the document\n"); #else #ifdef LIBXML_READER_ENABLED printf("\t--debug : dump the nodes content when using --stream\n"); #endif /* LIBXML_READER_ENABLED */ #endif #ifdef LIBXML_TREE_ENABLED printf("\t--copy : used to test the internal copy implementation\n"); #endif /* LIBXML_TREE_ENABLED */ printf("\t--recover : output what was parsable on broken XML documents\n"); printf("\t--huge : remove any internal arbitrary parser limits\n"); printf("\t--noent : substitute entity references by their value\n"); printf("\t--noout : don't output the result tree\n"); printf("\t--path 'paths': provide a set of paths for resources\n"); printf("\t--load-trace : print trace of all external entites loaded\n"); printf("\t--nonet : refuse to fetch DTDs or entities over network\n"); printf("\t--nocompact : do not generate compact text nodes\n"); printf("\t--htmlout : output results as HTML\n"); printf("\t--nowrap : do not put HTML doc wrapper\n"); #ifdef LIBXML_VALID_ENABLED printf("\t--valid : validate the document in addition to std well-formed check\n"); printf("\t--postvalid : do a posteriori validation, i.e after parsing\n"); printf("\t--dtdvalid URL : do a posteriori validation against a given DTD\n"); printf("\t--dtdvalidfpi FPI : same but name the DTD with a Public Identifier\n"); #endif /* LIBXML_VALID_ENABLED */ printf("\t--timing : print some timings\n"); printf("\t--output file or -o file: save to a given file\n"); printf("\t--repeat : repeat 100 times, for timing or profiling\n"); printf("\t--insert : ad-hoc test for valid insertions\n"); #ifdef LIBXML_OUTPUT_ENABLED #ifdef HAVE_ZLIB_H printf("\t--compress : turn on gzip compression of output\n"); #endif #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_HTML_ENABLED printf("\t--html : use the HTML parser\n"); printf("\t--xmlout : force to use the XML serializer when using --html\n"); #endif #ifdef LIBXML_PUSH_ENABLED printf("\t--push : use the push mode of the parser\n"); #endif /* LIBXML_PUSH_ENABLED */ #ifdef HAVE_SYS_MMAN_H printf("\t--memory : parse from memory\n"); #endif printf("\t--maxmem nbbytes : limits memory allocation to nbbytes bytes\n"); printf("\t--nowarning : do not emit warnings from parser/validator\n"); printf("\t--noblanks : drop (ignorable?) blanks spaces\n"); printf("\t--nocdata : replace cdata section with text nodes\n"); #ifdef LIBXML_OUTPUT_ENABLED printf("\t--format : reformat/reindent the input\n"); printf("\t--encode encoding : output in the given encoding\n"); printf("\t--dropdtd : remove the DOCTYPE of the input docs\n"); #endif /* LIBXML_OUTPUT_ENABLED */ printf("\t--c14n : save in W3C canonical format v1.0 (with comments)\n"); printf("\t--c14n11 : save in W3C canonical format v1.1 (with comments)\n"); printf("\t--exc-c14n : save in W3C exclusive canonical format (with comments)\n"); #ifdef LIBXML_C14N_ENABLED #endif /* LIBXML_C14N_ENABLED */ printf("\t--nsclean : remove redundant namespace declarations\n"); printf("\t--testIO : test user I/O support\n"); #ifdef LIBXML_CATALOG_ENABLED printf("\t--catalogs : use SGML catalogs from $SGML_CATALOG_FILES\n"); printf("\t otherwise XML Catalogs starting from \n"); printf("\t %s are activated by default\n", XML_XML_DEFAULT_CATALOG); printf("\t--nocatalogs: deactivate all catalogs\n"); #endif printf("\t--auto : generate a small doc on the fly\n"); #ifdef LIBXML_XINCLUDE_ENABLED printf("\t--xinclude : do XInclude processing\n"); printf("\t--noxincludenode : same but do not generate XInclude nodes\n"); printf("\t--nofixup-base-uris : do not fixup xml:base uris\n"); #endif printf("\t--loaddtd : fetch external DTD\n"); printf("\t--dtdattr : loaddtd + populate the tree with inherited attributes \n"); #ifdef LIBXML_READER_ENABLED printf("\t--stream : use the streaming interface to process very large files\n"); printf("\t--walker : create a reader and walk though the resulting doc\n"); #endif /* LIBXML_READER_ENABLED */ #ifdef LIBXML_PATTERN_ENABLED printf("\t--pattern pattern_value : test the pattern support\n"); #endif printf("\t--chkregister : verify the node registration code\n"); #ifdef LIBXML_SCHEMAS_ENABLED printf("\t--relaxng schema : do RelaxNG validation against the schema\n"); printf("\t--schema schema : do validation against the WXS schema\n"); #endif #ifdef LIBXML_SCHEMATRON_ENABLED printf("\t--schematron schema : do validation against a schematron\n"); #endif #ifdef LIBXML_SAX1_ENABLED printf("\t--sax1: use the old SAX1 interfaces for processing\n"); #endif printf("\t--sax: do not build a tree but work just at the SAX level\n"); printf("\t--oldxml10: use XML-1.0 parsing rules before the 5th edition\n"); printf("\nLibxml project home page: http://xmlsoft.org/\n"); printf("To report bugs or get some help check: http://xmlsoft.org/bugs.html\n"); } static void registerNode(xmlNodePtr node) { node->_private = malloc(sizeof(long)); *(long*)node->_private = (long) 0x81726354; nbregister++; } static void deregisterNode(xmlNodePtr node) { assert(node->_private != NULL); assert(*(long*)node->_private == (long) 0x81726354); free(node->_private); nbregister--; } int main(int argc, char **argv) { int i, acount; int files = 0; int version = 0; const char* indent; if (argc <= 1) { usage(argv[0]); return(1); } LIBXML_TEST_VERSION for (i = 1; i < argc ; i++) { if (!strcmp(argv[i], "-")) break; if (argv[i][0] != '-') continue; if ((!strcmp(argv[i], "-debug")) || (!strcmp(argv[i], "--debug"))) debug++; else #ifdef LIBXML_DEBUG_ENABLED if ((!strcmp(argv[i], "-shell")) || (!strcmp(argv[i], "--shell"))) { shell++; noout = 1; } else #endif #ifdef LIBXML_TREE_ENABLED if ((!strcmp(argv[i], "-copy")) || (!strcmp(argv[i], "--copy"))) copy++; else #endif /* LIBXML_TREE_ENABLED */ if ((!strcmp(argv[i], "-recover")) || (!strcmp(argv[i], "--recover"))) { recovery++; options |= XML_PARSE_RECOVER; } else if ((!strcmp(argv[i], "-huge")) || (!strcmp(argv[i], "--huge"))) { options |= XML_PARSE_HUGE; } else if ((!strcmp(argv[i], "-noent")) || (!strcmp(argv[i], "--noent"))) { noent++; options |= XML_PARSE_NOENT; } else if ((!strcmp(argv[i], "-nsclean")) || (!strcmp(argv[i], "--nsclean"))) { options |= XML_PARSE_NSCLEAN; } else if ((!strcmp(argv[i], "-nocdata")) || (!strcmp(argv[i], "--nocdata"))) { options |= XML_PARSE_NOCDATA; } else if ((!strcmp(argv[i], "-nodict")) || (!strcmp(argv[i], "--nodict"))) { options |= XML_PARSE_NODICT; } else if ((!strcmp(argv[i], "-version")) || (!strcmp(argv[i], "--version"))) { showVersion(argv[0]); version = 1; } else if ((!strcmp(argv[i], "-noout")) || (!strcmp(argv[i], "--noout"))) noout++; #ifdef LIBXML_OUTPUT_ENABLED else if ((!strcmp(argv[i], "-o")) || (!strcmp(argv[i], "-output")) || (!strcmp(argv[i], "--output"))) { i++; output = argv[i]; } #endif /* LIBXML_OUTPUT_ENABLED */ else if ((!strcmp(argv[i], "-htmlout")) || (!strcmp(argv[i], "--htmlout"))) htmlout++; else if ((!strcmp(argv[i], "-nowrap")) || (!strcmp(argv[i], "--nowrap"))) nowrap++; #ifdef LIBXML_HTML_ENABLED else if ((!strcmp(argv[i], "-html")) || (!strcmp(argv[i], "--html"))) { html++; } else if ((!strcmp(argv[i], "-xmlout")) || (!strcmp(argv[i], "--xmlout"))) { xmlout++; } #endif /* LIBXML_HTML_ENABLED */ else if ((!strcmp(argv[i], "-loaddtd")) || (!strcmp(argv[i], "--loaddtd"))) { loaddtd++; options |= XML_PARSE_DTDLOAD; } else if ((!strcmp(argv[i], "-dtdattr")) || (!strcmp(argv[i], "--dtdattr"))) { loaddtd++; dtdattrs++; options |= XML_PARSE_DTDATTR; } #ifdef LIBXML_VALID_ENABLED else if ((!strcmp(argv[i], "-valid")) || (!strcmp(argv[i], "--valid"))) { valid++; options |= XML_PARSE_DTDVALID; } else if ((!strcmp(argv[i], "-postvalid")) || (!strcmp(argv[i], "--postvalid"))) { postvalid++; loaddtd++; options |= XML_PARSE_DTDLOAD; } else if ((!strcmp(argv[i], "-dtdvalid")) || (!strcmp(argv[i], "--dtdvalid"))) { i++; dtdvalid = argv[i]; loaddtd++; options |= XML_PARSE_DTDLOAD; } else if ((!strcmp(argv[i], "-dtdvalidfpi")) || (!strcmp(argv[i], "--dtdvalidfpi"))) { i++; dtdvalidfpi = argv[i]; loaddtd++; options |= XML_PARSE_DTDLOAD; } #endif /* LIBXML_VALID_ENABLED */ else if ((!strcmp(argv[i], "-dropdtd")) || (!strcmp(argv[i], "--dropdtd"))) dropdtd++; else if ((!strcmp(argv[i], "-insert")) || (!strcmp(argv[i], "--insert"))) insert++; else if ((!strcmp(argv[i], "-timing")) || (!strcmp(argv[i], "--timing"))) timing++; else if ((!strcmp(argv[i], "-auto")) || (!strcmp(argv[i], "--auto"))) generate++; else if ((!strcmp(argv[i], "-repeat")) || (!strcmp(argv[i], "--repeat"))) { if (repeat) repeat *= 10; else repeat = 100; } #ifdef LIBXML_PUSH_ENABLED else if ((!strcmp(argv[i], "-push")) || (!strcmp(argv[i], "--push"))) push++; #endif /* LIBXML_PUSH_ENABLED */ #ifdef HAVE_SYS_MMAN_H else if ((!strcmp(argv[i], "-memory")) || (!strcmp(argv[i], "--memory"))) memory++; #endif else if ((!strcmp(argv[i], "-testIO")) || (!strcmp(argv[i], "--testIO"))) testIO++; #ifdef LIBXML_XINCLUDE_ENABLED else if ((!strcmp(argv[i], "-xinclude")) || (!strcmp(argv[i], "--xinclude"))) { xinclude++; options |= XML_PARSE_XINCLUDE; } else if ((!strcmp(argv[i], "-noxincludenode")) || (!strcmp(argv[i], "--noxincludenode"))) { xinclude++; options |= XML_PARSE_XINCLUDE; options |= XML_PARSE_NOXINCNODE; } else if ((!strcmp(argv[i], "-nofixup-base-uris")) || (!strcmp(argv[i], "--nofixup-base-uris"))) { xinclude++; options |= XML_PARSE_XINCLUDE; options |= XML_PARSE_NOBASEFIX; } #endif #ifdef LIBXML_OUTPUT_ENABLED #ifdef HAVE_ZLIB_H else if ((!strcmp(argv[i], "-compress")) || (!strcmp(argv[i], "--compress"))) { compress++; xmlSetCompressMode(9); } #endif #endif /* LIBXML_OUTPUT_ENABLED */ else if ((!strcmp(argv[i], "-nowarning")) || (!strcmp(argv[i], "--nowarning"))) { xmlGetWarningsDefaultValue = 0; xmlPedanticParserDefault(0); options |= XML_PARSE_NOWARNING; } else if ((!strcmp(argv[i], "-pedantic")) || (!strcmp(argv[i], "--pedantic"))) { xmlGetWarningsDefaultValue = 1; xmlPedanticParserDefault(1); options |= XML_PARSE_PEDANTIC; } #ifdef LIBXML_DEBUG_ENABLED else if ((!strcmp(argv[i], "-debugent")) || (!strcmp(argv[i], "--debugent"))) { debugent++; xmlParserDebugEntities = 1; } #endif #ifdef LIBXML_C14N_ENABLED else if ((!strcmp(argv[i], "-c14n")) || (!strcmp(argv[i], "--c14n"))) { canonical++; options |= XML_PARSE_NOENT | XML_PARSE_DTDATTR | XML_PARSE_DTDLOAD; } else if ((!strcmp(argv[i], "-c14n11")) || (!strcmp(argv[i], "--c14n11"))) { canonical_11++; options |= XML_PARSE_NOENT | XML_PARSE_DTDATTR | XML_PARSE_DTDLOAD; } else if ((!strcmp(argv[i], "-exc-c14n")) || (!strcmp(argv[i], "--exc-c14n"))) { exc_canonical++; options |= XML_PARSE_NOENT | XML_PARSE_DTDATTR | XML_PARSE_DTDLOAD; } #endif #ifdef LIBXML_CATALOG_ENABLED else if ((!strcmp(argv[i], "-catalogs")) || (!strcmp(argv[i], "--catalogs"))) { catalogs++; } else if ((!strcmp(argv[i], "-nocatalogs")) || (!strcmp(argv[i], "--nocatalogs"))) { nocatalogs++; } #endif else if ((!strcmp(argv[i], "-encode")) || (!strcmp(argv[i], "--encode"))) { i++; encoding = argv[i]; /* * OK it's for testing purposes */ xmlAddEncodingAlias("UTF-8", "DVEnc"); } else if ((!strcmp(argv[i], "-noblanks")) || (!strcmp(argv[i], "--noblanks"))) { noblanks++; xmlKeepBlanksDefault(0); } else if ((!strcmp(argv[i], "-maxmem")) || (!strcmp(argv[i], "--maxmem"))) { i++; if (sscanf(argv[i], "%d", &maxmem) == 1) { xmlMemSetup(myFreeFunc, myMallocFunc, myReallocFunc, myStrdupFunc); } else { maxmem = 0; } } else if ((!strcmp(argv[i], "-format")) || (!strcmp(argv[i], "--format"))) { noblanks++; #ifdef LIBXML_OUTPUT_ENABLED format++; #endif /* LIBXML_OUTPUT_ENABLED */ xmlKeepBlanksDefault(0); } #ifdef LIBXML_READER_ENABLED else if ((!strcmp(argv[i], "-stream")) || (!strcmp(argv[i], "--stream"))) { stream++; } else if ((!strcmp(argv[i], "-walker")) || (!strcmp(argv[i], "--walker"))) { walker++; noout++; } #endif /* LIBXML_READER_ENABLED */ #ifdef LIBXML_SAX1_ENABLED else if ((!strcmp(argv[i], "-sax1")) || (!strcmp(argv[i], "--sax1"))) { sax1++; options |= XML_PARSE_SAX1; } #endif /* LIBXML_SAX1_ENABLED */ else if ((!strcmp(argv[i], "-sax")) || (!strcmp(argv[i], "--sax"))) { sax++; } else if ((!strcmp(argv[i], "-chkregister")) || (!strcmp(argv[i], "--chkregister"))) { chkregister++; #ifdef LIBXML_SCHEMAS_ENABLED } else if ((!strcmp(argv[i], "-relaxng")) || (!strcmp(argv[i], "--relaxng"))) { i++; relaxng = argv[i]; noent++; options |= XML_PARSE_NOENT; } else if ((!strcmp(argv[i], "-schema")) || (!strcmp(argv[i], "--schema"))) { i++; schema = argv[i]; noent++; #endif #ifdef LIBXML_SCHEMATRON_ENABLED } else if ((!strcmp(argv[i], "-schematron")) || (!strcmp(argv[i], "--schematron"))) { i++; schematron = argv[i]; noent++; #endif } else if ((!strcmp(argv[i], "-nonet")) || (!strcmp(argv[i], "--nonet"))) { options |= XML_PARSE_NONET; xmlSetExternalEntityLoader(xmlNoNetExternalEntityLoader); } else if ((!strcmp(argv[i], "-nocompact")) || (!strcmp(argv[i], "--nocompact"))) { options &= ~XML_PARSE_COMPACT; } else if ((!strcmp(argv[i], "-load-trace")) || (!strcmp(argv[i], "--load-trace"))) { load_trace++; } else if ((!strcmp(argv[i], "-path")) || (!strcmp(argv[i], "--path"))) { i++; parsePath(BAD_CAST argv[i]); #ifdef LIBXML_PATTERN_ENABLED } else if ((!strcmp(argv[i], "-pattern")) || (!strcmp(argv[i], "--pattern"))) { i++; pattern = argv[i]; #endif } else if ((!strcmp(argv[i], "-oldxml10")) || (!strcmp(argv[i], "--oldxml10"))) { oldxml10++; options |= XML_PARSE_OLD10; } else { fprintf(stderr, "Unknown option %s\n", argv[i]); usage(argv[0]); return(1); } } #ifdef LIBXML_CATALOG_ENABLED if (nocatalogs == 0) { if (catalogs) { const char *catal; catal = getenv("SGML_CATALOG_FILES"); if (catal != NULL) { xmlLoadCatalogs(catal); } else { fprintf(stderr, "Variable $SGML_CATALOG_FILES not set\n"); } } } #endif #ifdef LIBXML_SAX1_ENABLED if (sax1) xmlSAXDefaultVersion(1); else xmlSAXDefaultVersion(2); #endif /* LIBXML_SAX1_ENABLED */ if (chkregister) { xmlRegisterNodeDefault(registerNode); xmlDeregisterNodeDefault(deregisterNode); } indent = getenv("XMLLINT_INDENT"); if(indent != NULL) { xmlTreeIndentString = indent; } defaultEntityLoader = xmlGetExternalEntityLoader(); xmlSetExternalEntityLoader(xmllintExternalEntityLoader); xmlLineNumbersDefault(1); if (loaddtd != 0) xmlLoadExtDtdDefaultValue |= XML_DETECT_IDS; if (dtdattrs) xmlLoadExtDtdDefaultValue |= XML_COMPLETE_ATTRS; if (noent != 0) xmlSubstituteEntitiesDefault(1); #ifdef LIBXML_VALID_ENABLED if (valid != 0) xmlDoValidityCheckingDefaultValue = 1; #endif /* LIBXML_VALID_ENABLED */ if ((htmlout) && (!nowrap)) { xmlGenericError(xmlGenericErrorContext, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"\n"); xmlGenericError(xmlGenericErrorContext, "\t\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"); xmlGenericError(xmlGenericErrorContext, "<html><head><title>%s output</title></head>\n", argv[0]); xmlGenericError(xmlGenericErrorContext, "<body bgcolor=\"#ffffff\"><h1 align=\"center\">%s output</h1>\n", argv[0]); } #ifdef LIBXML_SCHEMATRON_ENABLED if ((schematron != NULL) && (sax == 0) #ifdef LIBXML_READER_ENABLED && (stream == 0) #endif /* LIBXML_READER_ENABLED */ ) { xmlSchematronParserCtxtPtr ctxt; /* forces loading the DTDs */ xmlLoadExtDtdDefaultValue |= 1; options |= XML_PARSE_DTDLOAD; if (timing) { startTimer(); } ctxt = xmlSchematronNewParserCtxt(schematron); #if 0 xmlSchematronSetParserErrors(ctxt, (xmlSchematronValidityErrorFunc) fprintf, (xmlSchematronValidityWarningFunc) fprintf, stderr); #endif wxschematron = xmlSchematronParse(ctxt); if (wxschematron == NULL) { xmlGenericError(xmlGenericErrorContext, "Schematron schema %s failed to compile\n", schematron); progresult = XMLLINT_ERR_SCHEMACOMP; schematron = NULL; } xmlSchematronFreeParserCtxt(ctxt); if (timing) { endTimer("Compiling the schemas"); } } #endif #ifdef LIBXML_SCHEMAS_ENABLED if ((relaxng != NULL) && (sax == 0) #ifdef LIBXML_READER_ENABLED && (stream == 0) #endif /* LIBXML_READER_ENABLED */ ) { xmlRelaxNGParserCtxtPtr ctxt; /* forces loading the DTDs */ xmlLoadExtDtdDefaultValue |= 1; options |= XML_PARSE_DTDLOAD; if (timing) { startTimer(); } ctxt = xmlRelaxNGNewParserCtxt(relaxng); xmlRelaxNGSetParserErrors(ctxt, (xmlRelaxNGValidityErrorFunc) fprintf, (xmlRelaxNGValidityWarningFunc) fprintf, stderr); relaxngschemas = xmlRelaxNGParse(ctxt); if (relaxngschemas == NULL) { xmlGenericError(xmlGenericErrorContext, "Relax-NG schema %s failed to compile\n", relaxng); progresult = XMLLINT_ERR_SCHEMACOMP; relaxng = NULL; } xmlRelaxNGFreeParserCtxt(ctxt); if (timing) { endTimer("Compiling the schemas"); } } else if ((schema != NULL) #ifdef LIBXML_READER_ENABLED && (stream == 0) #endif ) { xmlSchemaParserCtxtPtr ctxt; if (timing) { startTimer(); } ctxt = xmlSchemaNewParserCtxt(schema); xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); wxschemas = xmlSchemaParse(ctxt); if (wxschemas == NULL) { xmlGenericError(xmlGenericErrorContext, "WXS schema %s failed to compile\n", schema); progresult = XMLLINT_ERR_SCHEMACOMP; schema = NULL; } xmlSchemaFreeParserCtxt(ctxt); if (timing) { endTimer("Compiling the schemas"); } } #endif /* LIBXML_SCHEMAS_ENABLED */ #ifdef LIBXML_PATTERN_ENABLED if ((pattern != NULL) #ifdef LIBXML_READER_ENABLED && (walker == 0) #endif ) { patternc = xmlPatterncompile((const xmlChar *) pattern, NULL, 0, NULL); if (patternc == NULL) { xmlGenericError(xmlGenericErrorContext, "Pattern %s failed to compile\n", pattern); progresult = XMLLINT_ERR_SCHEMAPAT; pattern = NULL; } } #endif /* LIBXML_PATTERN_ENABLED */ for (i = 1; i < argc ; i++) { if ((!strcmp(argv[i], "-encode")) || (!strcmp(argv[i], "--encode"))) { i++; continue; } else if ((!strcmp(argv[i], "-o")) || (!strcmp(argv[i], "-output")) || (!strcmp(argv[i], "--output"))) { i++; continue; } #ifdef LIBXML_VALID_ENABLED if ((!strcmp(argv[i], "-dtdvalid")) || (!strcmp(argv[i], "--dtdvalid"))) { i++; continue; } if ((!strcmp(argv[i], "-path")) || (!strcmp(argv[i], "--path"))) { i++; continue; } if ((!strcmp(argv[i], "-dtdvalidfpi")) || (!strcmp(argv[i], "--dtdvalidfpi"))) { i++; continue; } #endif /* LIBXML_VALID_ENABLED */ if ((!strcmp(argv[i], "-relaxng")) || (!strcmp(argv[i], "--relaxng"))) { i++; continue; } if ((!strcmp(argv[i], "-maxmem")) || (!strcmp(argv[i], "--maxmem"))) { i++; continue; } if ((!strcmp(argv[i], "-schema")) || (!strcmp(argv[i], "--schema"))) { i++; continue; } if ((!strcmp(argv[i], "-schematron")) || (!strcmp(argv[i], "--schematron"))) { i++; continue; } #ifdef LIBXML_PATTERN_ENABLED if ((!strcmp(argv[i], "-pattern")) || (!strcmp(argv[i], "--pattern"))) { i++; continue; } #endif if ((timing) && (repeat)) startTimer(); /* Remember file names. "-" means stdin. <sven@zen.org> */ if ((argv[i][0] != '-') || (strcmp(argv[i], "-") == 0)) { if (repeat) { xmlParserCtxtPtr ctxt = NULL; for (acount = 0;acount < repeat;acount++) { #ifdef LIBXML_READER_ENABLED if (stream != 0) { streamFile(argv[i]); } else { #endif /* LIBXML_READER_ENABLED */ if (sax) { testSAX(argv[i]); } else { if (ctxt == NULL) ctxt = xmlNewParserCtxt(); parseAndPrintFile(argv[i], ctxt); } #ifdef LIBXML_READER_ENABLED } #endif /* LIBXML_READER_ENABLED */ } if (ctxt != NULL) xmlFreeParserCtxt(ctxt); } else { nbregister = 0; #ifdef LIBXML_READER_ENABLED if (stream != 0) streamFile(argv[i]); else #endif /* LIBXML_READER_ENABLED */ if (sax) { testSAX(argv[i]); } else { parseAndPrintFile(argv[i], NULL); } if ((chkregister) && (nbregister != 0)) { fprintf(stderr, "Registration count off: %d\n", nbregister); progresult = XMLLINT_ERR_RDREGIS; } } files ++; if ((timing) && (repeat)) { endTimer("%d iterations", repeat); } } } if (generate) parseAndPrintFile(NULL, NULL); if ((htmlout) && (!nowrap)) { xmlGenericError(xmlGenericErrorContext, "</body></html>\n"); } if ((files == 0) && (!generate) && (version == 0)) { usage(argv[0]); } #ifdef LIBXML_SCHEMATRON_ENABLED if (wxschematron != NULL) xmlSchematronFree(wxschematron); #endif #ifdef LIBXML_SCHEMAS_ENABLED if (relaxngschemas != NULL) xmlRelaxNGFree(relaxngschemas); if (wxschemas != NULL) xmlSchemaFree(wxschemas); xmlRelaxNGCleanupTypes(); #endif #ifdef LIBXML_PATTERN_ENABLED if (patternc != NULL) xmlFreePattern(patternc); #endif xmlCleanupParser(); xmlMemoryDump(); return(progresult); }
{ "content_hash": "fa6f6a4a7c105ed245f41df4ab75b885", "timestamp": "", "source": "github", "line_count": 3590, "max_line_length": 96, "avg_line_length": 26.01309192200557, "alnum_prop": 0.5989805861629564, "repo_name": "icunning/fcvtc", "id": "25c6fb98ab0c65f98cff1d50e4e1b26d04498436", "size": "93525", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/LTK/opensource/share/doc/libxml2-2.7.4/examples/xmllint.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5029" }, { "name": "C", "bytes": "9356178" }, { "name": "C#", "bytes": "225653" }, { "name": "C++", "bytes": "939270" }, { "name": "CMake", "bytes": "6612" }, { "name": "CSS", "bytes": "1640" }, { "name": "DIGITAL Command Language", "bytes": "8422" }, { "name": "HTML", "bytes": "12744416" }, { "name": "Java", "bytes": "310664" }, { "name": "JavaScript", "bytes": "29707" }, { "name": "M4", "bytes": "16536" }, { "name": "Makefile", "bytes": "719749" }, { "name": "Objective-C", "bytes": "38896" }, { "name": "PHP", "bytes": "19144" }, { "name": "Perl", "bytes": "141913" }, { "name": "Perl 6", "bytes": "2938" }, { "name": "Python", "bytes": "417573" }, { "name": "QMake", "bytes": "3667" }, { "name": "Roff", "bytes": "39378" }, { "name": "Shell", "bytes": "631556" }, { "name": "VCL", "bytes": "4153" }, { "name": "XSLT", "bytes": "582362" } ], "symlink_target": "" }
![Sumo NodeBot](assets/sumo.jpg)
{ "content_hash": "ca1d5f50009a1dbf60144b6a175f73cd", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 32, "avg_line_length": 33, "alnum_prop": 0.7272727272727273, "repo_name": "BrianGenisio/codemash-nodebots-docs", "id": "4e016307b4ff7b6d16a64a055142d3eaef886f1f", "size": "66", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "slides/slides/and-morph-it-into-a-sumobot.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "59" }, { "name": "CoffeeScript", "bytes": "3275" }, { "name": "HTML", "bytes": "4778" }, { "name": "JavaScript", "bytes": "6589" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > </RelativeLayout>
{ "content_hash": "31de38939c5b90ed4528481739bb3a41", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 74, "avg_line_length": 35.833333333333336, "alnum_prop": 0.7302325581395349, "repo_name": "mapia/android", "id": "25162e2b443cff6c0034ce09a2273d0be75e8e50", "size": "215", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "app/src/main/res/layout/overview_map_follow.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1171615" } ], "symlink_target": "" }
package gw.lang.reflect.java.asm; import gw.internal.ext.org.objectweb.asm.signature.SignatureVisitor; /** */ public class FieldSignatureVisitor implements SignatureVisitor { private AsmField _asmField; private AsmType _currentType; private AsmType _typeArg; private boolean _bArray; private Boolean _variance; // null = none, true = covariant, false = contravariant FieldSignatureVisitor( AsmField field ) { _asmField = field; } FieldSignatureVisitor( AsmField field, AsmType type ) { _asmField = field; _currentType = type; } FieldSignatureVisitor( AsmField field, AsmType type, char wildcardVariance ) { _asmField = field; _currentType = type; _variance = wildcardVariance == '+'; } @Override public void visitFormalTypeParameter( String tv ) { throw new IllegalStateException(); } @Override public SignatureVisitor visitClassBound() { throw new IllegalStateException(); } @Override public SignatureVisitor visitInterfaceBound() { throw new IllegalStateException(); } @Override public SignatureVisitor visitSuperclass() { return this; } @Override public SignatureVisitor visitInterface() { throw new IllegalStateException(); } @Override public SignatureVisitor visitParameterType() { // For method only throw new IllegalStateException(); } @Override public SignatureVisitor visitReturnType() { // For method only throw new IllegalStateException(); } @Override public SignatureVisitor visitExceptionType() { // For method only throw new IllegalStateException(); } @Override public void visitBaseType( char c ) { } @Override public void visitTypeVariable( String tv ) { if( _currentType == null ) { _currentType = AsmUtil.makeTypeVariable( tv ); if( _variance != null ) { _currentType = new AsmWildcardType( _currentType, _variance ); } _asmField.setType( _currentType ); } else { _typeArg = AsmUtil.makeTypeVariable( tv ); if( _variance != null ) { _typeArg = new AsmWildcardType( _typeArg, _variance ); } _currentType.addTypeParameter( _typeArg ); } } @Override public SignatureVisitor visitArrayType() { FieldSignatureVisitor visitor = new FieldSignatureVisitor( _asmField, _currentType ); visitor._typeArg = _typeArg; visitor._bArray = true; return visitor; } @Override public void visitClassType( String name ) { if( _currentType == null ) { _currentType = AsmUtil.makeType( name ); if( _variance != null ) { _currentType = new AsmWildcardType( _currentType, _variance ); } _asmField.setType( _currentType ); } else { _typeArg = AsmUtil.makeType( name ); if( _variance != null ) { _typeArg = new AsmWildcardType( _typeArg, _variance ); } _currentType.addTypeParameter( _typeArg ); } } @Override public void visitInnerClassType( String name ) { if( _currentType == null ) { _currentType = AsmUtil.makeType( name ); if( _variance != null ) { _currentType = new AsmWildcardType( _currentType, _variance ); } _asmField.setType( _currentType ); } else { _typeArg = AsmUtil.makeType( name ); if( _variance != null ) { _typeArg = new AsmWildcardType( _typeArg, _variance ); } _currentType.addTypeParameter( _typeArg ); } } @Override public void visitTypeArgument() { _currentType.addTypeParameter( new AsmWildcardType( null, true ) ); } @Override public SignatureVisitor visitTypeArgument( char wildcard ) { if( wildcard != '=' ) { return new FieldSignatureVisitor( _asmField, _typeArg == null ? _currentType : _typeArg, wildcard ); } return new FieldSignatureVisitor( _asmField, _typeArg == null ? _currentType : _typeArg ); } @Override public void visitEnd() { if( _bArray ) { _currentType.incArrayDims(); } } }
{ "content_hash": "d00a35f99f99c6f5b83a3b3ca1884bd1", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 106, "avg_line_length": 25.56050955414013, "alnum_prop": 0.6523797657612759, "repo_name": "gosu-lang/old-gosu-repo", "id": "520bca7aeda09ab9b730582c1fd53e20b34a1cdc", "size": "4063", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gosu-core-api/src/main/java/gw/lang/reflect/java/asm/FieldSignatureVisitor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1793" }, { "name": "Gosu", "bytes": "977856" }, { "name": "Java", "bytes": "15187915" }, { "name": "JavaScript", "bytes": "27526" }, { "name": "Objective-C", "bytes": "56237" }, { "name": "Shell", "bytes": "1423" } ], "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_13) on Tue Sep 21 16:20:46 PDT 2010 --> <TITLE> NetworkServerMBean (Apache Derby 10.6 API Documentation) </TITLE> <META NAME="date" CONTENT="2010-09-21"> <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="NetworkServerMBean (Apache Derby 10.6 API Documentation)"; } } </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="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> Apache Derby 10.6</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV CLASS&nbsp; &nbsp;NEXT CLASS</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/derby/mbeans/drda/NetworkServerMBean.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="NetworkServerMBean.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"> org.apache.derby.mbeans.drda</FONT> <BR> Interface NetworkServerMBean</H2> <HR> <DL> <DT><PRE>public interface <B>NetworkServerMBean</B></DL> </PRE> <P> <p> This is an MBean defining a JMX management and monitoring interface of Derby's Network Server.</p> <p> This MBean is created and registered automatically at Network Server startup if all requirements are met (J2SE 5.0 or better).</p> <p> Key properties for the registered MBean:</p> <ul> <li><code>type=NetworkServer</code></li> <li><code>system=</code><em>runtime system identifier</em> (see <a href="../package-summary.html#package_description">description of package org.apache.derby.mbeans</a>)</li> </ul> <p> If a security manager is installed, accessing attributes and operations of this MBean may require a <code>SystemPermission</code>; see individual method documentation for details.</p> <p> For more information on Managed Beans, refer to the JMX specification.</p> <P> <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../org/apache/derby/drda/NetworkServerControl.html" title="class in org.apache.derby.drda"><CODE>NetworkServerControl</CODE></A>, <A HREF="../../../../../org/apache/derby/security/SystemPermission.html" title="class in org.apache.derby.security"><CODE>SystemPermission</CODE></A>, <a href="../package-summary.html"><code>org.apache.derby.mbeans</code></a></DL> <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;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getAccumulatedConnectionCount()">getAccumulatedConnectionCount</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the accumulated number of connections.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getActiveConnectionCount()">getActiveConnectionCount</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the number of currently active connections.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;long</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getBytesReceived()">getBytesReceived</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the total number of bytes read by the server since it was started.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getBytesReceivedPerSecond()">getBytesReceivedPerSecond</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the number of bytes received per second by the Network Server.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;long</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getBytesSent()">getBytesSent</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the total number of bytes written by the server since it was started.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getBytesSentPerSecond()">getBytesSentPerSecond</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the number of bytes sent per second by the Network Server.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getConnectionCount()">getConnectionCount</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the total number of current connections (waiting or active) to the Network Server.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getConnectionThreadPoolSize()">getConnectionThreadPoolSize</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Get the size of the connection thread pool.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaHost()">getDrdaHost</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the network interface address on which the Network Server is listening.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaKeepAlive()">getDrdaKeepAlive</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Reports whether or not the Derby Network Server will send keepalive probes and attempt to clean up connections for disconnected clients (the value of the <code>derby.drda.keepAlive</code> property).</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaMaxThreads()">getDrdaMaxThreads</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Reports the maximum number of client connection threads the Network Server will allocate at any given time.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaPortNumber()">getDrdaPortNumber</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the port number on which the Network Server is listening for client connections.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaSecurityMechanism()">getDrdaSecurityMechanism</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The Derby security mechanism required by the Network Server for all client connections.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaSslMode()">getDrdaSslMode</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Reports whether client connections must be encrypted using Secure Sockets Layer (SSL), and whether certificate based peer authentication is enabled.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaStreamOutBufferSize()">getDrdaStreamOutBufferSize</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The size of the buffer used for streaming BLOB and CLOB from server to client.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaTimeSlice()">getDrdaTimeSlice</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; If the server property <code>derby.drda.maxThreads</code> is set to a non-zero value, this is the number of milliseconds that each client connection will actively use in the Network Server before yielding to another connection.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaTraceAll()">getDrdaTraceAll</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Whether server-side tracing is enabled for all client connections (sessions).</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaTraceDirectory()">getDrdaTraceDirectory</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Indicates the location of tracing files on the server host, if server tracing has been enabled.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;long</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getStartTime()">getStartTime</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the start time of the network server.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;long</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getUptime()">getUptime</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the time (in milliseconds) the Network Server has been running.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getWaitingConnectionCount()">getWaitingConnectionCount</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Gets the number of currently waiting connections.</TD> </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="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#ping()">ping</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Executes the network server's <code>ping</code> command.</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="getDrdaHost()"><!-- --></A><H3> getDrdaHost</H3> <PRE> java.lang.String <B>getDrdaHost</B>()</PRE> <DL> <DD><p> Gets the network interface address on which the Network Server is listening. This corresponds to the value of the <code>derby.drda.host</code> property.</p> <p> For example, the value "<code>localhost</code>" means that the Network Server is listening on the local loopback interface only. <p> The special value "<code>0.0.0.0</code>" (IPv4 environments only) represents the "unspecified address" - also known as the anylocal or wildcard address. In this context this means that the server is listening on all network interfaces (and may thus be able to see connections from both the local host as well as remote hosts, depending on which network interfaces are available).</p> <p> Requires <code>SystemPermission("server", "control")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the the network interface address on which the Network Server is listening (<code>derby.drda.host</code>)</DL> </DD> </DL> <HR> <A NAME="getDrdaKeepAlive()"><!-- --></A><H3> getDrdaKeepAlive</H3> <PRE> boolean <B>getDrdaKeepAlive</B>()</PRE> <DL> <DD><p> Reports whether or not the Derby Network Server will send keepalive probes and attempt to clean up connections for disconnected clients (the value of the <code>derby.drda.keepAlive</code> property).</p> <p> If <code>true</code>, a keepalive probe is sent to the client if a "long time" (by default, more than two hours) passes with no other data being sent or received. This will detect and clean up connections for clients on powered-off machines or clients that have disconnected unexpectedly. </p> <p> If false, Derby will not attempt to clean up connections from disconnected clients, and will not send keepalive probes.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>whether or not the Derby Network Server will send keepalive probes and attempt to clean up connections for disconnected clients (<code>derby.drda.keepAlive</code>)<DT><B>See Also:</B><DD><a href="http://db.apache.org/derby/docs/dev/adminguide/radmindrdakeepalive.html"><code>derby.drda.keepAlive</code> documentation</a></DL> </DD> </DL> <HR> <A NAME="getDrdaMaxThreads()"><!-- --></A><H3> getDrdaMaxThreads</H3> <PRE> int <B>getDrdaMaxThreads</B>()</PRE> <DL> <DD><p> Reports the maximum number of client connection threads the Network Server will allocate at any given time. This corresponds to the <code>derby.drda.maxThreads</code> property.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the maximum number of client connection threads the Network Server will allocate at any given time (<code>derby.drda.maxThreads</code>)</DL> </DD> </DL> <HR> <A NAME="getDrdaPortNumber()"><!-- --></A><H3> getDrdaPortNumber</H3> <PRE> int <B>getDrdaPortNumber</B>()</PRE> <DL> <DD><p> Gets the port number on which the Network Server is listening for client connections. This corresponds to the value of the <code>derby.drda.portNumber</code> Network Server setting.</p> <p> Requires <code>SystemPermission("server", "control")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the port number on which the Network Server is listening for client connections.</DL> </DD> </DL> <HR> <A NAME="getDrdaSecurityMechanism()"><!-- --></A><H3> getDrdaSecurityMechanism</H3> <PRE> java.lang.String <B>getDrdaSecurityMechanism</B>()</PRE> <DL> <DD><p> The Derby security mechanism required by the Network Server for all client connections. This corresponds to the value of the <code>derby.drda.securityMechanism</code> property on the server.</p> <p> If not set, the empty String will be returned, which means that the Network Server accepts any connection which uses a valid security mechanism.</p> <p> For a list of valid security mechanisms, refer to the documentation for the <code>derby.drda.securityMechanism</code> property in the <i>Derby Server and Administration Guide</i>.</p> <p> Requires <code>SystemPermission("server", "control")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the security mechanism required by the Network Server for all client connections (<code>derby.drda.securityMechanism</code>)</DL> </DD> </DL> <HR> <A NAME="getDrdaSslMode()"><!-- --></A><H3> getDrdaSslMode</H3> <PRE> java.lang.String <B>getDrdaSslMode</B>()</PRE> <DL> <DD><p> Reports whether client connections must be encrypted using Secure Sockets Layer (SSL), and whether certificate based peer authentication is enabled. Refers to the <code>derby.drda.sslMode</code> property.</p> <p> Peer authentication means that the other side of the SSL connection is authenticated based on a trusted certificate installed locally.</p> <p> The value returned is one of "<code>off</code>" (no SSL encryption), "<code>basic</code>" (SSL encryption, no peer authentication) and "<code>peerAuthentication</code>" (SSL encryption and peer authentication). Refer to the <i>Derby Server and Administration Guide</i> for more details.</p> <p> Requires <code>SystemPermission("server", "control")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>whether client connections must be encrypted using Secure Sockets Layer (SSL), and whether certificate based peer authentication is enabled (<code>derby.drda.sslMode</code>)</DL> </DD> </DL> <HR> <A NAME="getDrdaStreamOutBufferSize()"><!-- --></A><H3> getDrdaStreamOutBufferSize</H3> <PRE> int <B>getDrdaStreamOutBufferSize</B>()</PRE> <DL> <DD><p> The size of the buffer used for streaming BLOB and CLOB from server to client. Refers to the <code>derby.drda.streamOutBufferSize</code> property.</p> <p> This setting may improve streaming performance when the default sizes of packets being sent are significantly smaller than the maximum allowed packet size in the network.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the size of the buffer used for streaming blob/clob from server to client (<code>derby.drda.streamOutBufferSize</code>)</DL> </DD> </DL> <HR> <A NAME="getDrdaTimeSlice()"><!-- --></A><H3> getDrdaTimeSlice</H3> <PRE> int <B>getDrdaTimeSlice</B>()</PRE> <DL> <DD><p> If the server property <code>derby.drda.maxThreads</code> is set to a non-zero value, this is the number of milliseconds that each client connection will actively use in the Network Server before yielding to another connection. If this value is 0, a waiting connection will become active once a currently active connection is closed.</p> <p> Refers to the <code>derby.drda.timeSlice</code> server property.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the number of milliseconds that each client connection will actively use in the Network Server before yielding to another connection (<code>derby.drda.timeSlice</code>)<DT><B>See Also:</B><DD><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaMaxThreads()"><CODE>getDrdaMaxThreads()</CODE></A></DL> </DD> </DL> <HR> <A NAME="getDrdaTraceAll()"><!-- --></A><H3> getDrdaTraceAll</H3> <PRE> boolean <B>getDrdaTraceAll</B>()</PRE> <DL> <DD><p> Whether server-side tracing is enabled for all client connections (sessions). Refers to the <code>derby.drda.traceAll</code> server property.</p> <p> Tracing may for example be useful when providing technical support information. The Network Server also supports tracing for individual connections (sessions), see the <i>Derby Server and Administration Guide</i> ("Controlling tracing by using the trace facility") for details.</p> <p> When tracing is enabled, tracing information from each client connection will be written to a separate trace file. </p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>whether tracing for all client connections is enabled (<code>derby.drda.traceAll</code>)<DT><B>See Also:</B><DD><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaTraceDirectory()"><CODE>getDrdaTraceDirectory()</CODE></A></DL> </DD> </DL> <HR> <A NAME="getDrdaTraceDirectory()"><!-- --></A><H3> getDrdaTraceDirectory</H3> <PRE> java.lang.String <B>getDrdaTraceDirectory</B>()</PRE> <DL> <DD><p> Indicates the location of tracing files on the server host, if server tracing has been enabled.</p> <p> If the server setting <code>derby.drda.traceDirectory</code> is set, its value will be returned. Otherwise, the Network Server's default values will be taken into account when producing the result.</p> <p> Requires <code>SystemPermission("server", "control")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the potential location of tracing files on the server host<DT><B>See Also:</B><DD><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaTraceAll()"><CODE>getDrdaTraceAll()</CODE></A></DL> </DD> </DL> <HR> <A NAME="getConnectionCount()"><!-- --></A><H3> getConnectionCount</H3> <PRE> int <B>getConnectionCount</B>()</PRE> <DL> <DD><p> Gets the total number of current connections (waiting or active) to the Network Server.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the number of current connections<DT><B>See Also:</B><DD><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getActiveConnectionCount()"><CODE>getActiveConnectionCount()</CODE></A>, <A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getWaitingConnectionCount()"><CODE>getWaitingConnectionCount()</CODE></A></DL> </DD> </DL> <HR> <A NAME="getActiveConnectionCount()"><!-- --></A><H3> getActiveConnectionCount</H3> <PRE> int <B>getActiveConnectionCount</B>()</PRE> <DL> <DD><p> Gets the number of currently active connections. All connections are active if the DrdaMaxThreads attribute (<code>derby.drda.maxThreads</code> property) is 0.</p> <p> If DrdaMaxThreads is > 0 and DrdaTimeSlice is 0, connections remain active until they are closed. If there are more than DrdaMaxThreads connections, inactive connections will be waiting for some active connection to close. The connection request will return when the connection becomes active.</p> <p> If DrdaMaxThreads is > 0 and DrdaTimeSlice > 0, connections will be alternating beetween active and waiting according to Derby's time slicing algorithm.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the number of active connections<DT><B>See Also:</B><DD><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaMaxThreads()"><CODE>getDrdaMaxThreads()</CODE></A>, <A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaTimeSlice()"><CODE>getDrdaTimeSlice()</CODE></A>, <A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getWaitingConnectionCount()"><CODE>getWaitingConnectionCount()</CODE></A></DL> </DD> </DL> <HR> <A NAME="getWaitingConnectionCount()"><!-- --></A><H3> getWaitingConnectionCount</H3> <PRE> int <B>getWaitingConnectionCount</B>()</PRE> <DL> <DD><p> Gets the number of currently waiting connections. This number will always be 0 if DrdaMaxThreads is 0. Otherwise, if the total number of connections is less than or equal to DrdaMaxThreads, then no connections are waiting.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the number of waiting connections<DT><B>See Also:</B><DD><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getActiveConnectionCount()"><CODE>getActiveConnectionCount()</CODE></A>, <A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaMaxThreads()"><CODE>getDrdaMaxThreads()</CODE></A>, <A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaTimeSlice()"><CODE>getDrdaTimeSlice()</CODE></A></DL> </DD> </DL> <HR> <A NAME="getConnectionThreadPoolSize()"><!-- --></A><H3> getConnectionThreadPoolSize</H3> <PRE> int <B>getConnectionThreadPoolSize</B>()</PRE> <DL> <DD><p> Get the size of the connection thread pool. If DrdaMaxThreads (<code>derby.drda.maxThreads</code>) is set to a non-zero value, the size of the thread pool will not exceed this value.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the size of the Network Server's connection thread pool<DT><B>See Also:</B><DD><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getDrdaMaxThreads()"><CODE>getDrdaMaxThreads()</CODE></A></DL> </DD> </DL> <HR> <A NAME="getAccumulatedConnectionCount()"><!-- --></A><H3> getAccumulatedConnectionCount</H3> <PRE> int <B>getAccumulatedConnectionCount</B>()</PRE> <DL> <DD><p> Gets the accumulated number of connections. This includes all active and waiting connections since the Network Server was started. This number will not decrease as long as the Network Server is running.</p> <p> Require <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the accumulated number of connections made since server startup</DL> </DD> </DL> <HR> <A NAME="getBytesReceived()"><!-- --></A><H3> getBytesReceived</H3> <PRE> long <B>getBytesReceived</B>()</PRE> <DL> <DD><p> Gets the total number of bytes read by the server since it was started. </p> <p> Require <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the total number of bytes received by the server</DL> </DD> </DL> <HR> <A NAME="getBytesSent()"><!-- --></A><H3> getBytesSent</H3> <PRE> long <B>getBytesSent</B>()</PRE> <DL> <DD><p> Gets the total number of bytes written by the server since it was started.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the total number of bytes sent by the server</DL> </DD> </DL> <HR> <A NAME="getBytesReceivedPerSecond()"><!-- --></A><H3> getBytesReceivedPerSecond</H3> <PRE> int <B>getBytesReceivedPerSecond</B>()</PRE> <DL> <DD><p> Gets the number of bytes received per second by the Network Server. This number is calculated by taking into account the number of bytes received since the last calculation (or since MBean startup if it is the first time this attibute is being read).</p> <p> The shortest interval measured is 1 second. This means that a new value will not be calculated unless there has been at least 1 second since the last calculation.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the number of bytes received per second</DL> </DD> </DL> <HR> <A NAME="getBytesSentPerSecond()"><!-- --></A><H3> getBytesSentPerSecond</H3> <PRE> int <B>getBytesSentPerSecond</B>()</PRE> <DL> <DD><p> Gets the number of bytes sent per second by the Network Server. This number is calculated by taking into account the number of bytes sent since the last calculation (or since MBean startup if it is the first time this attibute is being read).</p> <p> The shortest interval measured is 1 second. This means that a new value will not be calculated unless there has been at least 1 second since the last calculation.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the number of bytes sent per millisecond</DL> </DD> </DL> <HR> <A NAME="getStartTime()"><!-- --></A><H3> getStartTime</H3> <PRE> long <B>getStartTime</B>()</PRE> <DL> <DD><p> Gets the start time of the network server. The time is reported as the number of milliseconds (ms) since Unix epoch (1970-01-01 00:00:00 UTC), and corresponds to the value of <code>java.lang.System#currentTimeMillis()</code> at the time the Network Server was started.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the difference, measured in milliseconds, between the time the Network Server was started and Unix epoch (1970-01-01T00:00:00Z)<DT><B>See Also:</B><DD><CODE>System.currentTimeMillis()</CODE></DL> </DD> </DL> <HR> <A NAME="getUptime()"><!-- --></A><H3> getUptime</H3> <PRE> long <B>getUptime</B>()</PRE> <DL> <DD><p> Gets the time (in milliseconds) the Network Server has been running. In other words, the time passed since the server was started.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Returns:</B><DD>the difference, measured in milliseconds, between the current time and the time the Network Server was started<DT><B>See Also:</B><DD><A HREF="../../../../../org/apache/derby/mbeans/drda/NetworkServerMBean.html#getStartTime()"><CODE>getStartTime()</CODE></A></DL> </DD> </DL> <HR> <A NAME="ping()"><!-- --></A><H3> ping</H3> <PRE> void <B>ping</B>() throws java.lang.Exception</PRE> <DL> <DD><p> Executes the network server's <code>ping</code> command. Returns without errors if the server was successfully pinged.</p> <p> Note that the <code>ping</code> command itself will be executed from the network server instance that is actually running the server, and that the result will be transferred via JMX to the JMX client invoking this operation. This means that this operation will test network server connectivity from the same host (machine) as the network server, as opposed to when the <code>ping</code> command (or method) of <code>NetworkServerControl</code> is executed from a remote machine.</p> <p> This operation requires the following permission to be granted to the network server code base if a Java security manager is installed in the server JVM:</p> <codeblock> <code> permission java.net.SocketPermission "*", "connect,resolve"; </code> </codeblock> <p>The value <code>"*"</code> will allow connections from the network server to any host and any port, and may be replaced with a more specific value if so desired. The required value will depend on the value of the <code>-h</code> (or <code>derby.drda.host</code>) (host) and <code>-p</code> (or <code>derby.drda.portNumber</code>) (port) settings of the Network Server.</p> <p> Requires <code>SystemPermission("server", "monitor")</code> if a security manager is installed.</p> <P> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE> - if the ping attempt fails (an indication that the network server is not running properly)<DT><B>See Also:</B><DD><A HREF="../../../../../org/apache/derby/drda/NetworkServerControl.html#ping()"><CODE>NetworkServerControl.ping()</CODE></A>, <CODE>SocketPermission</CODE></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="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> Built on Tue 2010-09-21 16:20:41-0700, from revision 999685</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV CLASS&nbsp; &nbsp;NEXT CLASS</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/derby/mbeans/drda/NetworkServerMBean.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="NetworkServerMBean.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> Apache Derby 10.6 API Documentation - <i>Copyright &copy; 2004,2008 The Apache Software Foundation. All Rights Reserved.</i> </BODY> </HTML>
{ "content_hash": "b9396e0432ffd2c5533cafd710d3939e", "timestamp": "", "source": "github", "line_count": 990, "max_line_length": 241, "avg_line_length": 39.30808080808081, "alnum_prop": 0.6698445329564435, "repo_name": "armoredsoftware/protocol", "id": "19124b33db981951c1db6b3e38f5a5d544847085", "size": "38915", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "measurer/hotspot-measurer/jdk1.6.0_45/db/javadoc/jdbc3/org/apache/derby/mbeans/drda/NetworkServerMBean.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ada", "bytes": "252822" }, { "name": "Assembly", "bytes": "11210154" }, { "name": "Awk", "bytes": "6556" }, { "name": "Batchfile", "bytes": "79841" }, { "name": "C", "bytes": "92554796" }, { "name": "C++", "bytes": "29411093" }, { "name": "CSS", "bytes": "96602" }, { "name": "D", "bytes": "12894" }, { "name": "DIGITAL Command Language", "bytes": "17168" }, { "name": "DTrace", "bytes": "32201" }, { "name": "Emacs Lisp", "bytes": "3647" }, { "name": "FORTRAN", "bytes": "15411" }, { "name": "Go", "bytes": "2202" }, { "name": "Groff", "bytes": "2159080" }, { "name": "HTML", "bytes": "14351037" }, { "name": "Haskell", "bytes": "519183" }, { "name": "Java", "bytes": "9276960" }, { "name": "JavaScript", "bytes": "49539" }, { "name": "Lex", "bytes": "16562" }, { "name": "Logos", "bytes": "184506" }, { "name": "Makefile", "bytes": "1431247" }, { "name": "Objective-C", "bytes": "139451" }, { "name": "Pascal", "bytes": "3521" }, { "name": "Perl", "bytes": "180326" }, { "name": "Python", "bytes": "305456" }, { "name": "R", "bytes": "54" }, { "name": "Scheme", "bytes": "2254611" }, { "name": "Scilab", "bytes": "2316184" }, { "name": "Shell", "bytes": "2184639" }, { "name": "TeX", "bytes": "318429" }, { "name": "XSLT", "bytes": "152406" }, { "name": "Yacc", "bytes": "430581" } ], "symlink_target": "" }
using System.Collections.Generic; namespace Light.Data { /// <summary> /// Order expression. /// </summary> internal class OrderExpression : LightExpression { private List<OrderExpression> _orderExpressions; internal OrderExpression(DataEntityMapping tableMapping) { TableMapping = tableMapping; } /// <summary> /// Concat the specified expression1 and expression2. /// </summary> /// <param name="expression1">Expression1.</param> /// <param name="expression2">Expression2.</param> internal static OrderExpression Concat(OrderExpression expression1, OrderExpression expression2) { if (expression1 == null && expression2 == null) { return null; } if (expression1 == null) { return expression2; } if (expression2 == null) { return expression1; } if (ReferenceEquals(expression1, expression2)) { return expression1; } if (expression1 is RandomOrderExpression || expression2 is RandomOrderExpression) { return expression2; } var deMapping = expression1.TableMapping ?? expression2.TableMapping; var newExpression = new OrderExpression(deMapping); var list = new List<OrderExpression>(); if (expression1._orderExpressions == null) { list.Add(expression1); } else { list.AddRange(expression1._orderExpressions); } if (expression2._orderExpressions == null) { list.Add(expression2); } else { list.AddRange(expression2._orderExpressions); } newExpression._orderExpressions = list; newExpression.MultiOrder = expression1.MultiOrder | expression2.MultiOrder; return newExpression; } /// <param name="expression1">Expression1.</param> /// <param name="expression2">Expression2.</param> public static OrderExpression operator &(OrderExpression expression1, OrderExpression expression2) { return Concat(expression1, expression2); } internal virtual OrderExpression CreateAliasTableNameOrder(string aliasTableName) { var newExpression = new OrderExpression(TableMapping); var list = new List<OrderExpression>(); foreach (var item in list) { var newItem = item.CreateAliasTableNameOrder(aliasTableName); list.Add(newItem); } newExpression._orderExpressions = list; return newExpression; } /// <summary> /// Creates the sql string. /// </summary> /// <returns>The sql string.</returns> /// <param name="factory">Factory.</param> /// <param name="isFullName">If set to <c>true</c> is full name.</param> /// <param name="state">State.</param> internal virtual string CreateSqlString(CommandFactory factory, bool isFullName, CreateSqlState state) { var array = new string [_orderExpressions.Count]; var len = array.Length; for (var i = 0; i < len; i++) { array[i] = _orderExpressions[i].CreateSqlString(factory, isFullName, state); } return factory.CreateConcatOrderExpressionSql(array); } internal bool MultiOrder { get; set; } } }
{ "content_hash": "e4648e7dd2a25f5d888ae140a4351d58", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 110, "avg_line_length": 32.23076923076923, "alnum_prop": 0.5502519225669583, "repo_name": "aquilahkj/Light.Data2", "id": "aaa313918a74194bf704533cb18321a691275262", "size": "3773", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Light.Data/Expressions/OrderExpression.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "4673199" }, { "name": "PLpgSQL", "bytes": "44949" }, { "name": "TSQL", "bytes": "29977" } ], "symlink_target": "" }
namespace Signum.Engine.Maps; public class FluentInclude<T> where T : Entity { public SchemaBuilder SchemaBuilder { get; private set; } public Table Table { get; private set; } public FluentInclude(Table table, SchemaBuilder schemaBuilder) { Table = table; SchemaBuilder = schemaBuilder; } public FluentInclude<T> WithUniqueIndex(Expression<Func<T, object?>> fields, Expression<Func<T, bool>>? where = null, Expression<Func<T, object?>>? includeFields = null) { this.SchemaBuilder.AddUniqueIndex<T>(fields, where, includeFields); return this; } public FluentInclude<T> WithIndex(Expression<Func<T, object?>> fields, Expression<Func<T, bool>>? where = null, Expression<Func<T, object>>? includeFields = null) { this.SchemaBuilder.AddIndex<T>(fields, where, includeFields); return this; } public FluentInclude<T> WithUniqueIndexMList<M>(Expression<Func<T, MList<M>>> mlist, Expression<Func<MListElement<T, M>, object>>? fields = null, Expression<Func<MListElement<T, M>, bool>>? where = null, Expression<Func<MListElement<T, M>, object>>? includeFields = null) { if (fields == null) fields = mle => new { mle.Parent, mle.Element }; this.SchemaBuilder.AddUniqueIndexMList<T, M>(mlist, fields, where, includeFields); return this; } public FluentInclude<T> WithIndexMList<M>(Expression<Func<T, MList<M>>> mlist, Expression<Func<MListElement<T, M>, object>> fields, Expression<Func<MListElement<T, M>, bool>>? where = null, Expression<Func<MListElement<T, M>, object>>? includeFields = null) { this.SchemaBuilder.AddIndexMList<T, M>(mlist, fields, where, includeFields); return this; } public FluentInclude<T> WithLiteModel<M>(Expression<Func<T, M>> constructorExpression, bool isDefault = true) { Lite.RegisterLiteModelConstructor(constructorExpression, isDefault); return this; } }
{ "content_hash": "34e764c71b2b3504ca00c602a8d3f08c", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 173, "avg_line_length": 37.08771929824562, "alnum_prop": 0.6385998107852412, "repo_name": "signumsoftware/framework", "id": "57396a5e5f58123bae432f189c156b9da42b539f", "size": "2114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Signum.Engine/Schema/FluentInclude.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "6726626" }, { "name": "CSS", "bytes": "68144" }, { "name": "PLpgSQL", "bytes": "8638" }, { "name": "PowerShell", "bytes": "3424" }, { "name": "Smalltalk", "bytes": "3" }, { "name": "TypeScript", "bytes": "3363680" }, { "name": "Vim Snippet", "bytes": "51937" } ], "symlink_target": "" }
""" WSGI config for simi project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "simi.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
{ "content_hash": "a1fa09f68a62e849c83898adca683133", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 78, "avg_line_length": 27.357142857142858, "alnum_prop": 0.7702349869451697, "repo_name": "elkingtowa/simi", "id": "0c9758758060b23f02f23036bf3177c7d07cb510", "size": "383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "simi/simi/wsgi.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "120137" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2014 Open Networking Laboratory ~ ~ 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.onosproject</groupId> <artifactId>onos-core</artifactId> <version>1.2.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>onos-core-common</artifactId> <packaging>bundle</packaging> <description>ONOS utilities common to the core modules</description> <dependencies> <dependency> <groupId>org.onosproject</groupId> <artifactId>onos-api</artifactId> </dependency> <dependency> <groupId>org.onosproject</groupId> <artifactId>onos-api</artifactId> <classifier>tests</classifier> <scope>test</scope> </dependency> <dependency> <groupId>org.easymock</groupId> <artifactId>easymock</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.compendium</artifactId> </dependency> <dependency> <groupId>org.apache.felix</groupId> <artifactId>org.apache.felix.scr.annotations</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-scr-plugin</artifactId> </plugin> </plugins> </build> </project>
{ "content_hash": "85578b83d2d357ed5dc939705e571370", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 105, "avg_line_length": 32.45205479452055, "alnum_prop": 0.6200928661882651, "repo_name": "SmartInfrastructures/dreamer", "id": "31c13d853699bc474a2e71a67012ecefface6ce4", "size": "2369", "binary": false, "copies": "2", "ref": "refs/heads/icona", "path": "core/common/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "49724" }, { "name": "HTML", "bytes": "99297" }, { "name": "Java", "bytes": "6721862" }, { "name": "JavaScript", "bytes": "610426" } ], "symlink_target": "" }
Cake Gallery ========= [![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/hugodias/cakegallery?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) CakeGallery is a cakephp plugin to manage galleries, albums and pictures [![Album page](http://i.imgur.com/rRaubYw.png)](https://www.youtube.com/watch?v=3gHRnCI2vHE) With CakeGallery you can: * Create Albums * Add tags, title and status (published or drafts) to albums * Upload multiple pictures at the same time * Create multiple versions for your pictures (thumbnails, crop, resize, etc) * Integrate any album with any other Model in your application --- ### Videos and Resources Installing: [https://www.youtube.com/watch?v=OEgVQQTaWkE](https://www.youtube.com/watch?v=OEgVQQTaWkE) - Portuguese Features: [https://www.youtube.com/watch?v=3gHRnCI2vHE](https://www.youtube.com/watch?v=3gHRnCI2vHE) DEMO (Old version): [http://galleryopenshift-cakeupload.rhcloud.com/gallery](http://galleryopenshift-cakeupload.rhcloud.com/gallery) --- ### Requirements To use CakeGallery you need the following requirements * CakePHP 2.x application * PHP 5.3+ (bundled GD 2.0.28+ for image manipulation) * MySQL * Apache --- ### Version 2.0.0 --- ### Before start * Make sure that your `app/webroot/files` folder is writable --- ### Wizard Installation (recommended) * Clone or Download the Zip file from Github * Copy the `Gallery` folder to your app plugins folder: `app/Plugin/` * Make sure that your `app/Plugin/Gallery/Config` folder is writable (For installation only) * Open your `app/Config/bootstrap.php` file and add the following code ```php CakePlugin::load(array( 'Gallery' => array( 'bootstrap' => true, 'routes' => true ))); ``` * To finish the installation go to your browser and type `http://your-app-url/gallery` and follow the wizard --- ### Manual installation * Clone or Download the Zip file from Github * Copy the `Gallery` folder to your app plugins folder: `app/Plugin/` * Rename the `app/Plugin/Gallery/Config/config.php.install` file to **config.php** * Import the SQL file `app/Plugin/Gallery/Config/cakegallery.sql` to your database * Open your `app/Config/bootstrap.php` file and add the following code ```php CakePlugin::load(array( 'Gallery' => array( 'bootstrap' => true, 'routes' => true ))); ``` * Create a **gallery** folder inside `app/webroot/files` and give it writable permissions. (`app/webroot/files/gallery`) * Check at `http://your-app-url/gallery` to see your plugin working. --- ### FAQ --- #### The images are not showing up If you are using windows , have a chance of the images are not being rendered. This will happen because of windows directory separator. To fix it you can use this solution: [http://stackoverflow.com/a/4095765/708385](http://stackoverflow.com/a/4095765/708385) #### How to attach a gallery to a model? Integrating Gallery with a model of your application is very simple and takes only seconds, and the best is you do not need to change your database. To begin open the model you want to attach a gallery, in this example will be `Product.php` ```php class Product extends AppModel{ public $name = 'Product'; } ``` Now you just need to add the $actsAs attribute in your model: ```php class Product extends AppModel{ public $name = 'Product'; public $actsAs = array('Gallery.Gallery'); } ``` And its done! Now, when you search for this object in database, its pictures will be automatically retrieved from the plugin: ```php $product = $this->Product->findById(10); // // array( // 'Product' => array( // 'id' => '1', // 'name' => 'My Product', // 'price' => '29.00' // ), // 'Gallery' => array( // 'Album' => array( // ... // ), // 'Picture' => array( // ... // ), // 'numPictures' => (int) 2 // ) // ) ``` If you want to manually call for the pictures you will want to disable the automatic feature and call it yourself: ```php public $actsAs = array('Gallery.Gallery' => array('automatic' => false)); ``` ```php // Anycontroller.php $this->Product->id = 10; $this->Product->getGallery(); ``` --- #### How to create a new gallery attached with a model? You should use the Gallery link helper. It is very easy to use. 1. Specify the Gallery helper in your controller 2. Use the gallery link helper passing a model and id ```php # ProductsController.php class ProductsController extends AppController { public $helpers = array('Gallery.Gallery'); } ``` ```php # app/View/Products/view.ctp echo $this->Gallery->link('product', 10); ``` --- #### How to create a standalone gallery? (Non-related gallery) You can create a gallery that don't belongs to any model, a standalone gallery. To create one of those you will use the same example as above, but no arguments are needed ```php # anyview.ctp echo $this->Gallery->link(); ``` --- #### How to change image resize dimensions? All configuration related to images you can find at app/Plugin/Gallery/Config/bootstrap.php ```php $config = array( 'App' => array( # Choose what theme you want to use: # You can find all themes at Gallery/webroot/css/themes # Use the first name in the file as a parameter, eg: cosmo.min.css -> cosmo 'theme' => 'cosmo' ), 'File' => array( # Max size of a file (in megabytes (MB)) 'max_file_size' => '20', # What king pictures the user is allowed to upload? 'allowed_extensions' => array('jpg','png','jpeg','gif') ), 'Pictures' => array( # Resize original image. If you don't want to resize it, you should set a empty array, E.G: 'resize_to' => array() # Default configuration will resize the image to 1024 pixels height (and unlimited width) 'resize_to' => array(0, 1024, false), # Set to TRUE if you want to convert all png files to JPG (reduce significantly image size) 'png2jpg' => true, # Set the JPG quality on each resize. # The recommended value is 85 (85% quality) 'jpg_quality' => 85, # List of additional files generated after upload, like thumbnails, banners, etc 'styles' => array( 'small' => array(50, 50, true), # 50x50 Cropped 'medium' => array(255, 170, true), # 255#170 Cropped 'large' => array(0, 533, false) # 533 pixels height (and unlimited width) ) ) ); Configure::write('GalleryOptions', $config); ``` You can create as many styles you want, just add in the styles array, and future versions will be created on uploading. PS: DO NOT modify the default names as **medium** or **small**. You can safely modify the width, height and action but the names are used by the plugin, so don't change then.
{ "content_hash": "ffc49c35a2721efc10f2f13399221718", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 259, "avg_line_length": 29.462222222222223, "alnum_prop": 0.6964851410469151, "repo_name": "chiranjib7io/sjsm", "id": "0af629799745357c7fa3873678d58d76b51e2f2c", "size": "6629", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/Plugin/Gallery/README.md", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ApacheConf", "bytes": "1785" }, { "name": "Batchfile", "bytes": "3083" }, { "name": "CSS", "bytes": "608525" }, { "name": "HTML", "bytes": "227793" }, { "name": "JavaScript", "bytes": "1795809" }, { "name": "PHP", "bytes": "9304762" }, { "name": "Python", "bytes": "3978" }, { "name": "Shell", "bytes": "4178" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <html> <head> <title>STUI:Scripts:Built In Scripts</title> </head> <body> <h2><a href="../../index.html">STUI</a>:<a href="../index.html">Scripts</a>:Built In Scripts</h2> <p>Documentation for the scripts included with STUI. <ul> <li><a href="RunCommands.html">Run_Commands</a>: run a sequence of commands (the simplest kind of scripting). <li>APOGEE <ul> <li>Cart Change: take two darks <li>dither_clearing_script: STUI wrap for APOGEE dither_clearing_script.txt <li>Evening Cals: take an evening calibration sequence <li>Exposure Sequence: take a sequence of exposures at various dither positions <li>Morning Cals: take a morning calibration sequence <li>Timer: timer display </ul> <li>BOSS <ul> <li>Timer: timer display </ul> <li>Closing <ul> <li>Goto 5 MCP: send the telescope to 5 degrees altitude <li>Quick Close: send telescope to az=121, alt=30 </ul> <li>Engineering <ul> <li>Test BOSS Collimation: exercise the collimation motors and report position error statistics <li>loopCommand: run some sequence of repeated commands <li><a href="PointingData.html">Pointing Data</a>: Take a sequence of engineering camera images to generate a pointing model. </ul> <li>Observations <ul> <li>Dust Counter: log dust counts <li>Fiducial Monitor: log fiducial crossings <li>Log Function: a log of various interesting events <li>Log Support: gather information for the night log <li>Scale Monitor: log changes to plate scale <li>Spiral Pattern: spiral search for guide stars <li>Sticky Offset: allows saving, applying or clearing offsets <li>Telescope Controls: miscellaneous telescope and BOSS commands </ul> <li>Startup <ul> <li>APOGEE Short Dark: check APOGEE by taking a short APOGEE dark <li>Get Versions: list versions of most actors <li>Plugging: list plugged plates and check if plates duplicated <li>Status: show various bits of status from various actors <li>Test Actors: ping most actors; note that ? is shown until the actor responds to the request </ul> <li>Tutorial: scripts for the <a href="../ScriptingTutorial/index.html">Scripting Tutorial</a> </ul> </body> </html>
{ "content_hash": "ea30418068dfb40483e28247aa70d485", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 119, "avg_line_length": 34.0735294117647, "alnum_prop": 0.6965904186447993, "repo_name": "r-owen/stui", "id": "7f309555b14f6a1ce5f9672fb59230102cbc2e20", "size": "2317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TUI/Help/Scripts/BuiltInScripts/index.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "231279" }, { "name": "Python", "bytes": "1297073" } ], "symlink_target": "" }
#include "DunoButton.h" #include "TypeLib.h" #include "DunoGUI.h" #include <iostream> using namespace DunoGUI; using namespace std; DunoButton::DunoButton(DunoLayout* layout, string text, unsigned int width, unsigned int height): DunoWidget("button") { m_text = strToWinStr(text); m_has_on_click = false; m_buttonID = currentID++; unsigned int x, y; layout->getNextPosition(&x, &y, width, height); init(x, y, width, height); } /* Create Widget Objects */ void DunoButton::createWidget(HWND& hWnd) { /* Create The WinAPI Button */ m_button = CreateWindow(L"button", m_text.c_str(), WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON, getX(), getY(), getWidth(), getHeight(), hWnd, (HMENU)m_buttonID, DunoGUIInsistence::getInstence(), NULL); }
{ "content_hash": "30b5e4265182bd7e30a26df370ba1f51", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 97, "avg_line_length": 26.066666666666666, "alnum_prop": 0.6764705882352942, "repo_name": "EdwinRybarczyk/Duno", "id": "9c3de851c5b91c395b48f26181672f0e9a097360", "size": "782", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Duno/DunoGUILib/DunoButton.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1310100" }, { "name": "C#", "bytes": "1685" }, { "name": "C++", "bytes": "2091536" }, { "name": "CMake", "bytes": "1511" }, { "name": "Objective-C", "bytes": "13594" } ], "symlink_target": "" }
template <typename _Object\ > #define CStateChimeraHuntingAbstract CStateChimeraHunting<_Object> TEMPLATE_SPECIALIZATION CStateChimeraHuntingAbstract::CStateChimeraHunting(_Object* obj) : inherited(obj) { add_state(eStateMoveToCover, xr_new<CStateChimeraHuntingMoveToCover<_Object>>(obj)); add_state(eStateComeOut, xr_new<CStateChimeraHuntingComeOut<_Object>>(obj)); } TEMPLATE_SPECIALIZATION bool CStateChimeraHuntingAbstract::check_start_conditions() { return true; } TEMPLATE_SPECIALIZATION bool CStateChimeraHuntingAbstract::check_completion() { return false; } TEMPLATE_SPECIALIZATION void CStateChimeraHuntingAbstract::reselect_state() { if (prev_substate == u32(-1)) select_state(eStateMoveToCover); else if (prev_substate == eStateMoveToCover) select_state(eStateComeOut); else select_state(eStateMoveToCover); } #undef TEMPLATE_SPECIALIZATION #undef CStateChimeraHuntingAbstract
{ "content_hash": "eb0e92e85de8fd3aa5d3767b0dae4380", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 88, "avg_line_length": 32.48275862068966, "alnum_prop": 0.778131634819533, "repo_name": "Im-dex/xray-162", "id": "47aaba43f4c54dd795bc70b638077c0aee92ca33", "size": "1084", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/engine/xrGame/ai/monsters/chimera/chimera_state_hunting_inline.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1642482" }, { "name": "C++", "bytes": "22541957" }, { "name": "CMake", "bytes": "636522" }, { "name": "Objective-C", "bytes": "40174" }, { "name": "Pascal", "bytes": "19058" }, { "name": "xBase", "bytes": "151706" } ], "symlink_target": "" }
import crcjam from './calculators/crcjam.js'; import defineCrc from './define_crc.js'; export default defineCrc('jam', crcjam);
{ "content_hash": "9aa955c6b54c0a256fe44d2912951fbb", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 45, "avg_line_length": 32.25, "alnum_prop": 0.7441860465116279, "repo_name": "alexgorbatchev/node-crc", "id": "5f3e2fae3e1ba0cea0e966b289529fa6bf2e74ac", "size": "129", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/crcjam.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "8463" }, { "name": "JavaScript", "bytes": "9316" }, { "name": "Makefile", "bytes": "595" }, { "name": "Python", "bytes": "170310" }, { "name": "Shell", "bytes": "11106" }, { "name": "TypeScript", "bytes": "40966" } ], "symlink_target": "" }
namespace boost{ namespace math{ typedef policies::policy<policies::overflow_error<policies::throw_on_error> > overflow_policy; // Beta functions. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type beta(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b); // Beta function (2 arguments). template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type beta(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, policies::policy<>); // Beta function (3 arguments). template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type beta(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE); // Beta function (3 arguments). template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type beta(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); // Beta function (3 arguments). template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type betac(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type betac(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE x); // Incomplete beta function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); // Incomplete beta function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibetac(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE x); // Incomplete beta complement function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibetac(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); // Incomplete beta complement function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE p, BOOST_MATH_TEST_TYPE* py); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE p, BOOST_MATH_TEST_TYPE* py, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE p); // Incomplete beta inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE p, const policies::policy<>&); // Incomplete beta inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta_inva(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE p); // Incomplete beta inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta_inva(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE p, const policies::policy<>&); // Incomplete beta inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta_invb(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE p); // Incomplete beta inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta_invb(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE p, const policies::policy<>&); // Incomplete beta inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibetac_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE q, BOOST_MATH_TEST_TYPE* py); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibetac_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE q, BOOST_MATH_TEST_TYPE* py, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibetac_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE q); // Incomplete beta complement inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibetac_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE q, const policies::policy<>&); // Incomplete beta complement inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibetac_inva(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE q); // Incomplete beta complement inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibetac_inva(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE q, const policies::policy<>&); // Incomplete beta complement inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibetac_invb(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE q); // Incomplete beta complement inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibetac_invb(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE q, const policies::policy<>&); // Incomplete beta complement inverse function. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta_derivative(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE x); // derivative of incomplete beta template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ibeta_derivative(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); // derivative of incomplete beta // erf & erfc error functions. template tools::promote_args<BOOST_MATH_TEST_TYPE>::type erf(BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type erf(BOOST_MATH_TEST_TYPE z, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type erfc(BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type erfc(BOOST_MATH_TEST_TYPE z, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type erf_inv(BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type erf_inv(BOOST_MATH_TEST_TYPE z, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type erfc_inv(BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type erfc_inv(BOOST_MATH_TEST_TYPE z, const policies::policy<>& pol); // Polynomials: template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type legendre_next(unsigned l, BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE Pl, BOOST_MATH_TEST_TYPE Plm1); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type legendre_p(int l, BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type legendre_p(int l, BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type legendre_q(unsigned l, BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type legendre_q(unsigned l, BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type legendre_next(unsigned l, unsigned m, BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE Pl, BOOST_MATH_TEST_TYPE Plm1); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type legendre_p(int l, int m, BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type legendre_p(int l, int m, BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type laguerre_next(unsigned n, BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE Ln, BOOST_MATH_TEST_TYPE Lnm1); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type laguerre_next(unsigned n, unsigned l, BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE Pl, BOOST_MATH_TEST_TYPE Plm1); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type laguerre(unsigned n, BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type laguerre(unsigned n, unsigned m, BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); template laguerre_result<int, BOOST_MATH_TEST_TYPE>::type laguerre(unsigned n, int m, BOOST_MATH_TEST_TYPE x); template laguerre_result<unsigned, BOOST_MATH_TEST_TYPE>::type laguerre(unsigned n, unsigned m, BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type hermite(unsigned n, BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type hermite(unsigned n, BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type hermite_next(unsigned n, BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE Hn, BOOST_MATH_TEST_TYPE Hnm1); template std::complex<BOOST_MATH_TEST_TYPE> spherical_harmonic(unsigned n, int m, BOOST_MATH_TEST_TYPE theta, BOOST_MATH_TEST_TYPE phi); template std::complex<BOOST_MATH_TEST_TYPE> spherical_harmonic(unsigned n, int m, BOOST_MATH_TEST_TYPE theta, BOOST_MATH_TEST_TYPE phi, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type spherical_harmonic_r(unsigned n, int m, BOOST_MATH_TEST_TYPE theta, BOOST_MATH_TEST_TYPE phi); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type spherical_harmonic_r(unsigned n, int m, BOOST_MATH_TEST_TYPE theta, BOOST_MATH_TEST_TYPE phi, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type spherical_harmonic_i(unsigned n, int m, BOOST_MATH_TEST_TYPE theta, BOOST_MATH_TEST_TYPE phi); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type spherical_harmonic_i(unsigned n, int m, BOOST_MATH_TEST_TYPE theta, BOOST_MATH_TEST_TYPE phi, const policies::policy<>& pol); // Elliptic integrals: template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_rf(BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE y, BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_rf(BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE y, BOOST_MATH_TEST_TYPE z, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_rd(BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE y, BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_rd(BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE y, BOOST_MATH_TEST_TYPE z, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_rc(BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE y); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_rc(BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE y, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_rj(BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE y, BOOST_MATH_TEST_TYPE z, BOOST_MATH_TEST_TYPE p); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_rj(BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE y, BOOST_MATH_TEST_TYPE z, BOOST_MATH_TEST_TYPE p, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type ellint_2(BOOST_MATH_TEST_TYPE k); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_2(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE phi); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_2(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE phi, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type ellint_1(BOOST_MATH_TEST_TYPE k); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_1(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE phi); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_1(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE phi, const policies::policy<>& pol); template detail::ellint_3_result<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_3(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE v, BOOST_MATH_TEST_TYPE phi); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_3(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE v, BOOST_MATH_TEST_TYPE phi, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type ellint_3(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE v); // Gamma functions. template tools::promote_args<BOOST_MATH_TEST_TYPE>::type tgamma(BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type tgamma1pm1(BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type tgamma1pm1(BOOST_MATH_TEST_TYPE z, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type tgamma(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type tgamma(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE z, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type lgamma(BOOST_MATH_TEST_TYPE z, int* sign); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type lgamma(BOOST_MATH_TEST_TYPE z, int* sign, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type lgamma(BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type lgamma(BOOST_MATH_TEST_TYPE x, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type tgamma_lower(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type tgamma_lower(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE z, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_q(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_q(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE z, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_p(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_p(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE z, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type tgamma_delta_ratio(BOOST_MATH_TEST_TYPE z, BOOST_MATH_TEST_TYPE delta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type tgamma_delta_ratio(BOOST_MATH_TEST_TYPE z, BOOST_MATH_TEST_TYPE delta, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type tgamma_ratio(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type tgamma_ratio(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE b, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_p_derivative(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_p_derivative(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE x, const policies::policy<>&); // gamma inverse. template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_p_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE p); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_p_inva(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE p, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_p_inva(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE p); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_p_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE p, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_q_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE q); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_q_inv(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE q, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_q_inva(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE q); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type gamma_q_inva(BOOST_MATH_TEST_TYPE a, BOOST_MATH_TEST_TYPE q, const policies::policy<>&); // digamma: template tools::promote_args<BOOST_MATH_TEST_TYPE>::type digamma(BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type digamma(BOOST_MATH_TEST_TYPE x, const policies::policy<>&); // Hypotenuse function sqrt(x ^ 2 + y ^ 2). template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type hypot(BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE y); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type hypot(BOOST_MATH_TEST_TYPE x, BOOST_MATH_TEST_TYPE y, const policies::policy<>&); // cbrt - cube root. template tools::promote_args<BOOST_MATH_TEST_TYPE>::type cbrt(BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type cbrt(BOOST_MATH_TEST_TYPE z, const policies::policy<>&); // log1p is log(x + 1) template tools::promote_args<BOOST_MATH_TEST_TYPE>::type log1p(BOOST_MATH_TEST_TYPE); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type log1p(BOOST_MATH_TEST_TYPE, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type log1p<BOOST_MATH_TEST_TYPE, overflow_policy>(BOOST_MATH_TEST_TYPE, const overflow_policy&); // log1pmx is log(x + 1) - x template tools::promote_args<BOOST_MATH_TEST_TYPE>::type log1pmx(BOOST_MATH_TEST_TYPE); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type log1pmx(BOOST_MATH_TEST_TYPE, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type log1pmx(BOOST_MATH_TEST_TYPE, const overflow_policy&); // Exp (x) minus 1 functions. template tools::promote_args<BOOST_MATH_TEST_TYPE>::type expm1(BOOST_MATH_TEST_TYPE); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type expm1(BOOST_MATH_TEST_TYPE, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type expm1(BOOST_MATH_TEST_TYPE, const overflow_policy&); // Power - 1 template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type powm1(const BOOST_MATH_TEST_TYPE a, const BOOST_MATH_TEST_TYPE z); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type powm1(const BOOST_MATH_TEST_TYPE a, const BOOST_MATH_TEST_TYPE z, const policies::policy<>&); // sqrt(1+x) - 1 template tools::promote_args<BOOST_MATH_TEST_TYPE>::type sqrt1pm1(const BOOST_MATH_TEST_TYPE& val); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type sqrt1pm1(const BOOST_MATH_TEST_TYPE& val, const policies::policy<>&); // Bessel functions: template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_bessel_j(BOOST_MATH_TEST_TYPE v, BOOST_MATH_TEST_TYPE x, const policies::policy<> & pol); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_bessel_j(BOOST_MATH_TEST_TYPE v, BOOST_MATH_TEST_TYPE x); template detail::bessel_traits<int, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_bessel_j(int v, BOOST_MATH_TEST_TYPE x); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type sph_bessel(unsigned v, BOOST_MATH_TEST_TYPE x, const policies::policy<> & pol); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type sph_bessel(unsigned v, BOOST_MATH_TEST_TYPE x); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_bessel_i(BOOST_MATH_TEST_TYPE v, BOOST_MATH_TEST_TYPE x, const policies::policy<> & pol); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_bessel_i(BOOST_MATH_TEST_TYPE v, BOOST_MATH_TEST_TYPE x); template detail::bessel_traits<int, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_bessel_i(int v, BOOST_MATH_TEST_TYPE x); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_bessel_k(BOOST_MATH_TEST_TYPE v, BOOST_MATH_TEST_TYPE x, const policies::policy<> & pol); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_bessel_k(BOOST_MATH_TEST_TYPE v, BOOST_MATH_TEST_TYPE x); template detail::bessel_traits<int, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_bessel_k(int v, BOOST_MATH_TEST_TYPE x); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_neumann(BOOST_MATH_TEST_TYPE v, BOOST_MATH_TEST_TYPE x, const policies::policy<> & pol); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_neumann(BOOST_MATH_TEST_TYPE v, BOOST_MATH_TEST_TYPE x); template detail::bessel_traits<int, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type cyl_neumann(int v, BOOST_MATH_TEST_TYPE x); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type sph_neumann(unsigned v, BOOST_MATH_TEST_TYPE x, const policies::policy<> & pol); template detail::bessel_traits<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE, policies::policy<> >::result_type sph_neumann(unsigned v, BOOST_MATH_TEST_TYPE x); // Airy Functions: template tools::promote_args<BOOST_MATH_TEST_TYPE>::type airy_ai(BOOST_MATH_TEST_TYPE x, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type airy_ai(BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type airy_bi(BOOST_MATH_TEST_TYPE x, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type airy_bi(BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type airy_ai_prime(BOOST_MATH_TEST_TYPE x, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type airy_ai_prime(BOOST_MATH_TEST_TYPE x); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type airy_bi_prime(BOOST_MATH_TEST_TYPE x, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type airy_bi_prime(BOOST_MATH_TEST_TYPE x); // Exponential Integral template tools::promote_args<BOOST_MATH_TEST_TYPE>::type expint(unsigned n, BOOST_MATH_TEST_TYPE z, const policies::policy<> &); template detail::expint_result<int, BOOST_MATH_TEST_TYPE>::type expint(int const z, BOOST_MATH_TEST_TYPE const u); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type expint(BOOST_MATH_TEST_TYPE z); // Zeta: template tools::promote_args<BOOST_MATH_TEST_TYPE>::type zeta(BOOST_MATH_TEST_TYPE s, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type zeta(BOOST_MATH_TEST_TYPE s); // Jacobi Functions: template tools::promote_args<BOOST_MATH_TEST_TYPE>::type jacobi_elliptic(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, BOOST_MATH_TEST_TYPE* pcn, BOOST_MATH_TEST_TYPE* pdn, const policies::policy<>&); template tools::promote_args<BOOST_MATH_TEST_TYPE>::type jacobi_elliptic(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, BOOST_MATH_TEST_TYPE* pcn, BOOST_MATH_TEST_TYPE* pdn); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_sn(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_sn(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_cn(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_cn(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_dn(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_dn(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_cd(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_cd(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_dc(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_dc(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_ns(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_ns(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_sd(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_sd(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_ds(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_ds(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_nc(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_nc(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_nd(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_nd(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_sc(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_sc(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_cs(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta, const policies::policy<>& pol); template tools::promote_args<BOOST_MATH_TEST_TYPE, BOOST_MATH_TEST_TYPE>::type jacobi_cs(BOOST_MATH_TEST_TYPE k, BOOST_MATH_TEST_TYPE theta); }} // namespaces
{ "content_hash": "810a8d700a92efaca1a045e4799ca42c", "timestamp": "", "source": "github", "line_count": 403, "max_line_length": 218, "avg_line_length": 76.20347394540943, "alnum_prop": 0.7194073591663953, "repo_name": "cpascal/af-cpp", "id": "60cf003d2dd7480db686131e2c3a04ee4fff7a60", "size": "30937", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "apdos/exts/boost_1_53_0/libs/math/test/test_instances.hpp", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "142321" }, { "name": "Batchfile", "bytes": "45292" }, { "name": "C", "bytes": "2380742" }, { "name": "C#", "bytes": "41850" }, { "name": "C++", "bytes": "141733840" }, { "name": "CMake", "bytes": "1784" }, { "name": "CSS", "bytes": "303526" }, { "name": "Cuda", "bytes": "27558" }, { "name": "FORTRAN", "bytes": "1440" }, { "name": "Groff", "bytes": "8174" }, { "name": "HTML", "bytes": "80494592" }, { "name": "IDL", "bytes": "15" }, { "name": "JavaScript", "bytes": "134468" }, { "name": "Lex", "bytes": "1318" }, { "name": "Makefile", "bytes": "1028949" }, { "name": "Max", "bytes": "36857" }, { "name": "Objective-C", "bytes": "4297" }, { "name": "PHP", "bytes": "60249" }, { "name": "Perl", "bytes": "30505" }, { "name": "Perl6", "bytes": "2130" }, { "name": "Python", "bytes": "1751993" }, { "name": "QML", "bytes": "613" }, { "name": "Rebol", "bytes": "372" }, { "name": "Shell", "bytes": "374946" }, { "name": "Tcl", "bytes": "1205" }, { "name": "TeX", "bytes": "13819" }, { "name": "XSLT", "bytes": "780775" }, { "name": "Yacc", "bytes": "19612" } ], "symlink_target": "" }
namespace tensor { template<class T> using enable_if_integer_t = typename std::enable_if<std::is_integral<T>::value>::type; template<class T> using enable_if_float_t = typename std::enable_if<std::is_floating_point<T>::value>::type; } #endif // TENSOR_TRAITS_H
{ "content_hash": "83a0e920b6e7d5788e4cc0afb6c2ec25", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 90, "avg_line_length": 22.083333333333332, "alnum_prop": 0.7169811320754716, "repo_name": "allebacco/tensorlib", "id": "fa2dc1bab26da3b50b84e7ab780457fe9a669f0e", "size": "366", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/tensor_traits.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "567" }, { "name": "C++", "bytes": "37718" }, { "name": "CMake", "bytes": "4404" } ], "symlink_target": "" }
package org.apache.calcite.rel.rules; import org.apache.calcite.plan.RelOptRule; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelOptRuleOperand; import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.plan.SubstitutionVisitor; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Aggregate; import org.apache.calcite.rel.core.Aggregate.Group; import org.apache.calcite.rel.core.AggregateCall; import org.apache.calcite.rel.core.Filter; import org.apache.calcite.rel.core.RelFactories; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexUtil; import org.apache.calcite.sql.SqlAggFunction; import org.apache.calcite.tools.RelBuilderFactory; import org.apache.calcite.util.ImmutableBitSet; import org.apache.calcite.util.mapping.Mappings; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; /** * Planner rule that matches an {@link org.apache.calcite.rel.core.Aggregate} * on a {@link org.apache.calcite.rel.core.Filter} and transposes them, * pushing the aggregate below the filter. * * <p>In some cases, it is necessary to split the aggregate. * * <p>This rule does not directly improve performance. The aggregate will * have to process more rows, to produce aggregated rows that will be thrown * away. The rule might be beneficial if the predicate is very expensive to * evaluate. The main use of the rule is to match a query that has a filter * under an aggregate to an existing aggregate table. * * @see org.apache.calcite.rel.rules.FilterAggregateTransposeRule */ public class AggregateFilterTransposeRule extends RelOptRule { public static final AggregateFilterTransposeRule INSTANCE = new AggregateFilterTransposeRule(); private AggregateFilterTransposeRule() { this( operand(Aggregate.class, operand(Filter.class, any())), RelFactories.LOGICAL_BUILDER); } /** Creates an AggregateFilterTransposeRule. */ public AggregateFilterTransposeRule(RelOptRuleOperand operand, RelBuilderFactory relBuilderFactory) { super(operand, relBuilderFactory, null); } public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final Filter filter = call.rel(1); // Do the columns used by the filter appear in the output of the aggregate? final ImmutableBitSet filterColumns = RelOptUtil.InputFinder.bits(filter.getCondition()); final ImmutableBitSet newGroupSet = aggregate.getGroupSet().union(filterColumns); final RelNode input = filter.getInput(); final RelMetadataQuery mq = call.getMetadataQuery(); final Boolean unique = mq.areColumnsUnique(input, newGroupSet); if (unique != null && unique) { // The input is already unique on the grouping columns, so there's little // advantage of aggregating again. More important, without this check, // the rule fires forever: A-F => A-F-A => A-A-F-A => A-A-A-F-A => ... return; } final boolean allColumnsInAggregate = aggregate.getGroupSet().contains(filterColumns); final Aggregate newAggregate = aggregate.copy(aggregate.getTraitSet(), input, newGroupSet, null, aggregate.getAggCallList()); final Mappings.TargetMapping mapping = Mappings.target( newGroupSet::indexOf, input.getRowType().getFieldCount(), newGroupSet.cardinality()); final RexNode newCondition = RexUtil.apply(mapping, filter.getCondition()); final Filter newFilter = filter.copy(filter.getTraitSet(), newAggregate, newCondition); if (allColumnsInAggregate && aggregate.getGroupType() == Group.SIMPLE) { // Everything needed by the filter is returned by the aggregate. assert newGroupSet.equals(aggregate.getGroupSet()); call.transformTo(newFilter); } else { // If aggregate uses grouping sets, we always need to split it. // Otherwise, it means that grouping sets are not used, but the // filter needs at least one extra column, and now aggregate it away. final ImmutableBitSet.Builder topGroupSet = ImmutableBitSet.builder(); for (int c : aggregate.getGroupSet()) { topGroupSet.set(newGroupSet.indexOf(c)); } ImmutableList<ImmutableBitSet> newGroupingSets = null; if (aggregate.getGroupType() != Group.SIMPLE) { ImmutableList.Builder<ImmutableBitSet> newGroupingSetsBuilder = ImmutableList.builder(); for (ImmutableBitSet groupingSet : aggregate.getGroupSets()) { final ImmutableBitSet.Builder newGroupingSet = ImmutableBitSet.builder(); for (int c : groupingSet) { newGroupingSet.set(newGroupSet.indexOf(c)); } newGroupingSetsBuilder.add(newGroupingSet.build()); } newGroupingSets = newGroupingSetsBuilder.build(); } final List<AggregateCall> topAggCallList = new ArrayList<>(); int i = newGroupSet.cardinality(); for (AggregateCall aggregateCall : aggregate.getAggCallList()) { final SqlAggFunction rollup = SubstitutionVisitor.getRollup(aggregateCall.getAggregation()); if (rollup == null) { // This aggregate cannot be rolled up. return; } if (aggregateCall.isDistinct()) { // Cannot roll up distinct. return; } topAggCallList.add( AggregateCall.create(rollup, aggregateCall.isDistinct(), aggregateCall.isApproximate(), aggregateCall.ignoreNulls(), ImmutableList.of(i++), -1, aggregateCall.collation, aggregateCall.type, aggregateCall.name)); } final Aggregate topAggregate = aggregate.copy(aggregate.getTraitSet(), newFilter, topGroupSet.build(), newGroupingSets, topAggCallList); call.transformTo(topAggregate); } } } // End AggregateFilterTransposeRule.java
{ "content_hash": "d324f6d623407889c2c671036986a50b", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 79, "avg_line_length": 42.166666666666664, "alnum_prop": 0.7061923583662714, "repo_name": "xhoong/incubator-calcite", "id": "52d994f7b5f35bc1aa0826809f45adfb8d39d2d9", "size": "6869", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2810" }, { "name": "CSS", "bytes": "36471" }, { "name": "HTML", "bytes": "17486" }, { "name": "Java", "bytes": "10611122" }, { "name": "Ruby", "bytes": "854" }, { "name": "Shell", "bytes": "3490" } ], "symlink_target": "" }
require 'spec_helper' require_relative 'shared' module RichCitationsProcessor RSpec.describe Serializers::JSON do let(:paper) { Models::CitingPaper.new } subject { Serializers::JSON.new(paper) } let(:json) { MultiJson.load( subject.serialize ) } it_should_behave_like 'a serializer' describe "paper info" do it "should return the paper metadata" do paper.uri = TestURI.new('http://example.com/a').wrap paper.word_count = 42 paper.bibliographic = { 'metadata' => 1 } expect(json).to eq( 'uri_source'=>'test', 'word_count' => 42, 'uri'=>'http://example.com/a', 'bibliographic'=>{'metadata'=>1} ) end it "should include extended URI data" do paper.uri = TestURI.new('http://example.com/a').wrap(more:'sample') expect(json).to eq( 'uri_source'=>'test', 'uri'=>'http://example.com/a', 'bibliographic'=>{ 'more' => 'sample'} ) end it "should not return nil fields" do expect(json).to eq( {} ) end end shared_examples_for 'authors' do it "should include authors" do authors_list.add(family:'Smith') authors_list.add(family:'Brown') expect(json_authors).to eq( [ { 'family'=>'Smith'}, { 'family' => 'Brown' } ] ) end it "should include authors with family/given names" do authors_list.add(family:'Smith', given:'John') expect(json_authors).to eq( [ { 'family'=>'Smith', 'given' => 'John' } ] ) end it "should include authors with literal names" do authors_list.add(literal:'The PLOS Labs Team') expect(json_authors).to eq( [ { 'literal'=>'The PLOS Labs Team' } ] ) end it "should include authors with emails" do authors_list.add(family:'Smith', given:'John', email:'john@example.com') expect(json_authors).to eq( [ { 'family'=>'Smith', 'given' => 'John', 'email' => 'john@example.com' } ] ) end it "should include authors with affiliations" do authors_list.add(family:'Smith', given:'John', affiliation:'PLOS Labs') expect(json_authors).to eq( [ { 'family'=>'Smith', 'given' => 'John', 'affiliation' => 'PLOS Labs' } ] ) end it "should include an empty object if no metadata is uspplied" do authors_list.add expect(json_authors).to eq( [ { } ] ) end end describe "citing paper authors" do let(:json_authors) { json['bibliographic']['author']} let(:authors_list) { paper.authors } include_examples 'authors' end describe 'references' do let(:references) { json['references']} it "should have references" do paper.references.add(id:'1', number:1) paper.references.add(id:'2', number:2) expect(references).to eq([{'id' => '1', 'number'=>1}, {'id'=>'2', 'number'=>2}]) end it "should have metadata for each reference" do paper.references.add(id:'1', number:1, uri:TestURI.new('http://example.com/a').wrap, original_citation:'Citation', accessed_at:DateTime.new(2014, 10, 15, 14, 02, 42), bibliographic: { 'metadata' => 42} ) expect(references).to eq([{"id"=>"1", "number"=>1, "uri_source"=>"test", "uri"=>"http://example.com/a", "accessed_at"=>"2014-10-15T14:02:42.000+00:00", "original_citation"=>"Citation", "bibliographic"=>{"metadata"=>42}}] ) end it "should include extended URI metadata in each reference" do paper.references.add(id:'1', number:1, uri:TestURI.new('http://example.com/a').wrap(more:'sample') ) expect(references).to eq([{"id"=>"1", "number"=>1, "uri_source"=>"test", "uri"=>"http://example.com/a", "bibliographic"=>{"more"=>"sample"}}] ) end it "should return empty metadata for unspecified properties" do paper.references.add() expect(references).to eq([{}]) end describe "reference paper authors" do let(:json_authors) { references.first['bibliographic']['author']} let(:authors_list) { paper.references.add.authors } include_examples 'authors' end describe "referenced citation groups" do it "should return list of cited groups" do r1 = paper.references.add(id:"r1") r2 = paper.references.add(id:"r2") g1 = paper.citation_groups.add(id:'g1') g2 = paper.citation_groups.add(id:'g2') g3 = paper.citation_groups.add(id:'g3') r1.citation_groups.add(g1) r1.citation_groups.add(g3) r1.citation_groups.add(g2) r2.citation_groups.add(g2) expect(references).to eq([{"id"=>"r1", "citation_groups"=>["g1", "g3", "g2"]}, {"id"=>"r2", "citation_groups"=>["g2"]}]) end end end describe 'citation_groups' do let(:citation_groups) { json['citation_groups']} it "should have groups" do paper.citation_groups.add(id:'1') paper.citation_groups.add(id:'2') expect(citation_groups).to eq([{'id' => '1'}, {'id'=>'2'}]) end it "should have metadata for each citation_groups" do paper.citation_groups.add(id:'1', section:'Section', word_position:42) expect(citation_groups).to eq([{"id"=>"1", "section"=>'Section', "word_position"=>42}]) end it "should return empty metadata for unspecified properties" do paper.citation_groups.add() expect(citation_groups).to eq([{}]) end describe "context" do it "should be returned" do paper.citation_groups.add(id: "g1", truncated_before: true, text_before: 'Before', citation: 'Citation', text_after: 'After', truncated_after: true ) expect(citation_groups).to eq([{'id'=>'g1', "context"=>{"truncated_before"=>true, "text_before"=>"Before", "citation"=>"Citation", "text_after"=>"After", "truncated_after"=>true } } ] ) end it "should not include nil values" do paper.citation_groups.add(id: "g1", citation: 'Citation') expect(citation_groups).to eq([{'id'=>'g1', "context"=>{"citation"=>"Citation"} }]) end it "should not be returned if all the values are nil" do paper.citation_groups.add(id: "g1") expect(citation_groups).to eq([{'id'=>'g1'}]) end end describe "referenced citation groups" do it "should return list of cited groups" do r1 = paper.references.add(id:'r1') r2 = paper.references.add(id:'r2') r3 = paper.references.add(id:'r3') g1 = paper.citation_groups.add(id:'g1') g2 = paper.citation_groups.add(id:'g2') g1.references.add(r1) g1.references.add(r3) g1.references.add(r2) g2.references.add(r2) expect(citation_groups).to eq([{"id"=>"g1", "references"=>["r1", "r3", "r2"]}, {"id"=>"g2", "references"=>["r2"]}]) end end end end end
{ "content_hash": "4a066b7706c9994064b2adcd17b4569f", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 135, "avg_line_length": 34.94954128440367, "alnum_prop": 0.5353720960756004, "repo_name": "PLOS/rich_citations_processor", "id": "23352720288690500d7c86bdfb99cb342b930cb0", "size": "8725", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/serializers/json_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "305457" } ], "symlink_target": "" }