text
stringlengths
2
1.04M
meta
dict
<?php $conf = include '../config.php'; $directory = 'img/background/'; $scanned_directory = array_diff(scandir('../' . $directory), array('..', '.')); $key = array_rand($scanned_directory); echo $conf['uri'] . '/' . $directory . $scanned_directory[$key];
{ "content_hash": "779d1ed8b9bdb5c7e1de58057fd2d5eb", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 79, "avg_line_length": 25.9, "alnum_prop": 0.61003861003861, "repo_name": "ziggi/video-roulette", "id": "4f6d02ebe68210ace5b994856eac5f193d238352", "size": "259", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/getbackground.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "196" }, { "name": "CSS", "bytes": "7939" }, { "name": "JavaScript", "bytes": "3914" }, { "name": "PHP", "bytes": "13867" } ], "symlink_target": "" }
// // LLPLevelViewController.m // myInke // // Created by He_bi on 2017/6/4. // Copyright © 2017年 He_bi. All rights reserved. // #import "LLPLevelViewController.h" @interface LLPLevelViewController () @end @implementation LLPLevelViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end
{ "content_hash": "8dbf07fae77a09a6bf739417aa0a5f31", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 102, "avg_line_length": 23.027027027027028, "alnum_prop": 0.7276995305164319, "repo_name": "heruohuan/inkeLive", "id": "3fc5ab2a5da102cc651b6d19e92f427757629ea4", "size": "855", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "myInke/Classes/Me/ViewController/LLPLevelViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "233795" }, { "name": "Ruby", "bytes": "481" } ], "symlink_target": "" }
package nl.nn.adapterframework.statistics; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import nl.nn.adapterframework.statistics.HasStatistics.Action; @RunWith(Parameterized.class) public class StatisticsKeeperTest { @Parameter(0) public String description=null; @Parameter(1) public Class<IBasics> basicsClass; @Parameters(name = "{index}: {0} - {1}") public static Collection estimators() { return Arrays.asList(new Object[][] { { "classic", Basics.class }, { "micrometer", MicroMeterBasics.class } }); } public StatisticsKeeper createStatisticsKeeper(boolean publishPercentiles, boolean publishHistograms, boolean calculatePercentiles) { try { StringTokenizer boundariesTokenizer = new StringTokenizer("100,1000,2000,10000",","); return new StatisticsKeeper("test", basicsClass.newInstance(), boundariesTokenizer, publishPercentiles, publishHistograms, calculatePercentiles, 2); } catch (InstantiationException | IllegalAccessException e) { fail(e.getMessage()); } return null; } public StatisticsKeeper createStatisticsKeeper() { return createStatisticsKeeper(false, false, true); } public void testLineair(StatisticsKeeper sk) { for (int i=0; i<100; i++) { sk.addValue(i); } assertEquals(100, sk.getCount()); assertEquals(0, sk.getMin()); assertEquals(99, sk.getMax()); assertEquals(49.5, sk.getAvg(), 0.001); assertEquals(4950, sk.getTotal(), 0.001); assertEquals(841.0, sk.getVariance(), 0.001); assertEquals(328350, sk.getTotalSquare(), 0.001); assertEquals(29.0, sk.getStdDev(), 0.001); assertEquals(49.5, getItemValueByName(sk, "p50"), 0.5); assertEquals(94.5, getItemValueByName(sk, "p95"), 1.5); assertEquals(97.5, getItemValueByName(sk, "p98"), 2.5); } public void testRandom(StatisticsKeeper sk, boolean withPercentiles) { int count = 10000; int limit = 100; int sum=0; long sumsq=0; Random rand = new Random(); for (int i=0; i<count; i++) { int value = rand.nextInt(100); sum+=value; sumsq += value*value; sk.addValue(value); } assertEquals(count, sk.getCount()); assertEquals(0, sk.getMin()); assertEquals(99, sk.getMax()); assertEquals((limit-1)/2.0, sk.getAvg(), 1.0); assertEquals((limit-1)*(count/2), sk.getTotal(), count*1.0); assertEquals(842.0, sk.getVariance(), 50.0); assertEquals(sumsq, sk.getTotalSquare(), 0.001); assertEquals(29.0, sk.getStdDev(), 1.0); if (withPercentiles) { assertEquals(49.5, getItemValueByName(sk, "p50"), 2.0); assertEquals(94.5, getItemValueByName(sk, "p95"), 2.0); assertEquals(97.5, getItemValueByName(sk, "p98"), 2.0); } } @Test public void testLineair() { StatisticsKeeper sk = createStatisticsKeeper(); sk.initMetrics(new SimpleMeterRegistry(), "testLineair", null); testLineair(sk); } @Test public void testLineairPublishPercentiles() { StatisticsKeeper sk = createStatisticsKeeper(true, false, false); sk.initMetrics(new SimpleMeterRegistry(), "testLineair", null); testLineair(sk); } @Test public void testLineairPublishHistograms() { StatisticsKeeper sk = createStatisticsKeeper(false, true, false); sk.initMetrics(new SimpleMeterRegistry(), "testLineair", null); testLineair(sk); } @Test public void testRandom() { StatisticsKeeper sk = createStatisticsKeeper(); sk.initMetrics(new SimpleMeterRegistry(), "testRandom", null); testRandom(sk, true); } @Test public void testRandomPublishPercentiles() { StatisticsKeeper sk = createStatisticsKeeper(true, false, false); sk.initMetrics(new SimpleMeterRegistry(), "testRandom", null); testRandom(sk, true); } @Test public void testRandomPublishHistograms() { StatisticsKeeper sk = createStatisticsKeeper(false, true, false); sk.initMetrics(new SimpleMeterRegistry(), "testRandom", null); assertEquals(16, sk.getItemCount()); testRandom(sk, true); } @Test public void testRandomNoPercentiles() { StatisticsKeeper sk = createStatisticsKeeper(false, false, false); sk.initMetrics(new SimpleMeterRegistry(), "testRandom", null); assertEquals(12, sk.getItemCount()); testRandom(sk, false); } double getItemValueByName(StatisticsKeeper sk, String name) { return (double)sk.getItemValue(sk.getItemIndex(name)); } @Test public void testInterval() { StatisticsKeeper sk = createStatisticsKeeper(); sk.initMetrics(new SimpleMeterRegistry(), "testInterval", null); assertEquals(sk.getIntervalItemName(0), 0L, sk.getIntervalItemValue(0)); // count assertEquals(sk.getIntervalItemName(1), null, sk.getIntervalItemValue(1)); // min assertEquals(sk.getIntervalItemName(2), null, sk.getIntervalItemValue(2)); // max assertEquals(sk.getIntervalItemName(3), null, sk.getIntervalItemValue(3)); // avg assertEquals(sk.getIntervalItemName(4), 0L, sk.getIntervalItemValue(4)); // sum assertEquals(sk.getIntervalItemName(5), 0L, sk.getIntervalItemValue(5)); // sumSq for (int i=0; i<100; i++) { sk.addValue(i); } assertEquals(100, sk.getCount()); assertEquals(0, sk.getMin()); assertEquals(99, sk.getMax()); assertEquals(49.5, sk.getAvg(), 0.001); assertEquals(4950, sk.getTotal(), 0.001); assertEquals(841.0, sk.getVariance(), 0.001); assertEquals(sk.getIntervalItemName(0), 100L, sk.getIntervalItemValue(0)); // count assertEquals(sk.getIntervalItemName(1), 0L, sk.getIntervalItemValue(1)); // min assertEquals(sk.getIntervalItemName(2), 99L, sk.getIntervalItemValue(2)); // max assertEquals(sk.getIntervalItemName(3), 49.5, sk.getIntervalItemValue(3)); // avg assertEquals(sk.getIntervalItemName(4), 4950L, sk.getIntervalItemValue(4)); // sum assertEquals(sk.getIntervalItemName(5), 328350L, sk.getIntervalItemValue(5)); // sumSq sk.performAction(Action.MARK_FULL); assertEquals(sk.getIntervalItemName(0), 0L, sk.getIntervalItemValue(0)); // count assertEquals(sk.getIntervalItemName(1), null, sk.getIntervalItemValue(1)); // min assertEquals(sk.getIntervalItemName(2), null, sk.getIntervalItemValue(2)); // max assertEquals(sk.getIntervalItemName(3), null, sk.getIntervalItemValue(3)); // avg assertEquals(sk.getIntervalItemName(4), 0L, sk.getIntervalItemValue(4)); // sum assertEquals(sk.getIntervalItemName(5), 0L, sk.getIntervalItemValue(5)); // sumSq for (int i=200; i<300; i++) { sk.addValue(i); } assertEquals(200, sk.getCount()); assertEquals(0, sk.getMin()); assertEquals(299, sk.getMax()); assertEquals(149.5, sk.getAvg(), 0.001); assertEquals(29900, sk.getTotal(), 0.001); assertEquals(10887.0, sk.getVariance(), 0.001); assertEquals(sk.getIntervalItemName(0), 100L, sk.getIntervalItemValue(0)); // count assertEquals(sk.getIntervalItemName(1), 200L, sk.getIntervalItemValue(1)); // min assertEquals(sk.getIntervalItemName(2), 299L, sk.getIntervalItemValue(2)); // max assertEquals(sk.getIntervalItemName(3), 249.5, sk.getIntervalItemValue(3)); // avg assertEquals(sk.getIntervalItemName(4), 24950L, sk.getIntervalItemValue(4)); // sum assertEquals(sk.getIntervalItemName(5), 6308350L, sk.getIntervalItemValue(5)); // sumSq } @Test public void testGetMap() { StatisticsKeeper sk = createStatisticsKeeper(); sk.initMetrics(new SimpleMeterRegistry(), "group", new ArrayList<>()); for (int i=0; i<100; i++) { sk.addValue(i*100); } Map<String,Object> map = sk.asMap(); assertMapValue(map, "name", "test"); assertMapValue(map, "count", "100"); assertMapValue(map, "min", "0"); assertMapValue(map, "max", "9900"); assertMapValue(map, "avg", "4950.0"); assertMapValue(map, "stdDev", "2901.1"); assertMapValue(map, "100ms", "1.0"); assertMapValue(map, "1000ms", "10.0"); assertMapValue(map, "2000ms", "20.0"); assertMapValue(map, "10000ms", "100.0"); // assertMapValue(map, "p50", "4950.0"); // assertMapValue(map, "p90", "8950.0"); // assertMapValue(map, "p95", "9450.0"); // assertMapValue(map, "p98", "9750.0"); } public void assertMapValue(Map<String,Object> map, String key, String value) { assertEquals(value, map.get(key).toString()); } @Test public void testLabelsAndTypes() { List<String> labels = StatisticsKeeper.getLabels(); List<String> types = StatisticsKeeper.getTypes(); assertEquals("name", labels.get(0)); assertEquals("STRING", types.get(0)); assertEquals("count", labels.get(1)); assertEquals("INTEGER", types.get(1)); } }
{ "content_hash": "e01daffd105e1ace9333d3ea4f476fa6", "timestamp": "", "source": "github", "line_count": 260, "max_line_length": 151, "avg_line_length": 34.08846153846154, "alnum_prop": 0.717364323592463, "repo_name": "ibissource/iaf", "id": "4de21c517901f56fe007e940a47288596820acc0", "size": "8863", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/test/java/nl/nn/adapterframework/statistics/StatisticsKeeperTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "12835" }, { "name": "CSS", "bytes": "183245" }, { "name": "Dockerfile", "bytes": "11185" }, { "name": "HTML", "bytes": "187009" }, { "name": "Java", "bytes": "9699471" }, { "name": "JavaScript", "bytes": "1754626" }, { "name": "Less", "bytes": "78481" }, { "name": "PLSQL", "bytes": "2900" }, { "name": "Python", "bytes": "14514" }, { "name": "Rich Text Format", "bytes": "43789" }, { "name": "Roff", "bytes": "1046" }, { "name": "SCSS", "bytes": "79489" }, { "name": "Shell", "bytes": "9171" }, { "name": "TSQL", "bytes": "3354" }, { "name": "XQuery", "bytes": "37" }, { "name": "XSLT", "bytes": "252809" } ], "symlink_target": "" }
A .Net Stardard class library for C#
{ "content_hash": "269b3b125678d69fdb2fc7756b7e39ff", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 36, "avg_line_length": 37, "alnum_prop": 0.7567567567567568, "repo_name": "Army-Ant/ArmyAnt.Net", "id": "c6950d41175c3cc7bd751ed9cbe2990588bd43a3", "size": "51", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "68008" } ], "symlink_target": "" }
% Description: Tools is a static class that conatins basic % routines and helper functions for Curve class and more. % 2017 Girum G. Demisse, girumdemisse@gmail.com/girum.demisse@uni.lu % Computer vision team, University of Luxembourg. %------------------------------------------------ classdef Tools methods(Static) function [rot,trans] = Trans_Mat(point1,point2) % Description: Computes high dimensional rigid-transformation % from point1 to point 2 that preserves world coordinate frame. % INPUT : point1, and point2 - two row vectors (1xn) % OUTPUT : rot - (nxn) rotation matrix % trans - (nx1) translation vector c = size(point1,2); CC = [point1;point2]; CC = CC - repmat(mean(CC),2,1); % rotation plane estimation [~,~,V]=svd(CC); p1 = (V'*point1')'; p2 = (V'*point2')'; % solve optimal rotation on 2D projection of points R = Tools.Opt_rot(p1(1,1:2),p2(1,1:2)); E = eye(c); E(1:2,1:2) = R; rot = E; % representing rotation matrix with respect to original frame rot = V*rot*V'; trans = point2' - rot*point1'; end function rot = Opt_rot(p1, p2) % Description: computes optimal rotation from p1 to p2 % INPUT : p1 and p2 - two row vectors (1xn) % OUTPUT : rot - (nxn) rotation matrix c = size(p1,2); corr = p1'*p2; [U,~,V]=svd(corr); E = eye(c); E(end,end) = det(V*U'); rot = V*E*U'; end function [area,comps] = Curve_area(points,varargin) % Description: computes area of a PLANAR curve. if the curve is closed % it uses Green's theorem. % % INPUT : points - ordered set of 2-dimensional points (mx2) % [optional] - set 0 for open curves % - set 1 for closed curves (default). % OUTPUT : area - final result (scalar) % comps - piece-wise area under the curve (mx1) pointsT = [points;points(1,:)]; if nargin > 1 if varargin{1} == 0 % CAUTION !! integration along the first dimension pointsT = points; end end avg_y = 0.5 * (pointsT(1:end-1,2) + pointsT(2:end,2)); integral = diff(pointsT(:,1)).* avg_y; comps = integral; % direction of point ordering does not matter due to % the absolute value. area = abs(sum(comps)); end function [integrated,comps] = Curve_length(points,varargin) % Description: computes length of a curve % INPUT : points - ordered set of n-dimensional points (mxn) % : [optional] scalar - 0 to identify open curves % - different from 0 to % identify closed curves (default). % OUTPUT : integrated - final curve length (scalar) % comps - piece-wise length (mx1) if nargin > 1 % curve length for open curves if varargin{1} == 0 tangent = diff(points); end else % curve length for closed curves tangent = (points - [points(end,:);points(1:end-1,:)]); end comps = sqrt(sum(tangent.^2,2)); integrated = sum(comps); end function [m,ind] = Min_M(MAT) % Description: Computes minimum value from an array of reals % INPUT : MAT -(mxn) array of numbers % OUTPUT : m - the minimum value % ind - index of the solution, [row_index,column_index] ind = zeros(1,2); [l,I] = min(MAT); [m,ind(1,2)] = min(l); ind(1,1) = I(ind(1,2)); end function points = process(points,varargin) % Description: The function samples and normaliz points from it % argument "points". % INPUT : points - (mxn)set of m input points % : [optional] - scalar to state the sample size. % OUTPUT : points - sampled and normalized points if nargin > 1 % number of sample size is specified points = curvspace(points,varargin{1}); else % Default: takes input size as sample size points = curvspace(points,length(points)); end points = Tools.normal_points(points); end function Normal_points = normal_points(points) % Description: The function centers and normalizes input data. % INPUT : points - (mxn) orderd set of m input points in % n-dimensional space. % OUTPUT : Normals_points - (mxn) centered and normalized points r = size(points,1); cen_p = points - repmat(mean(points),r,1); Normal_points = cen_p./sqrt(sum(sum(cen_p.^2,2))); end function [c1_r,c2_r] = DP_sampling(c1,c2,alpha,beta,window_size,type,sample_points) % Description: Optimally sample points for correspondance % estimation. % INPUT : c1 - instance of a Curve class. % : c2 - instance of a Curve class, NOTE: |c2.points| == |c1.points| % : alpha - a scalar constant to weight deformation term. % : beta - a scalar constant to weight constraint term. % : window_size - a positive scalar determing the window size of the % charts. % : type - = 1 for fixing c1 to uniform and optimally sampling c2. % - = 0 for sampling both curves optimally. % : sample_points - scalar value, determins the number of points to be sampled % sample_points << |c2.points|. % OUTPUT : c1_r - incase of "type" = 1, uniformly sampled c1. % incase of "type" = 0, optimally sampled c1. % : c2_r - optimally sampled c2. num_points = size(c1.points,1); if sample_points > num_points error('The number of sample points exceeds the total number of points !!'); elseif sample_points <= 0 error('The number of sample points cannot be zero or negartive !!'); elseif mod(num_points,sample_points) ~= 0 warning('The number of sample points does not divide the total number of points. Choose approprately for exact solution.'); end if type == 1 l = ceil(num_points/sample_points); % uniformly sampled c1 c1_r = c1; c1_r.points = Tools.normal_points(c1_r.points(1:l:num_points,:)); %c1_r.points = Tools.process(c1.points,sample_points); c1_r = curve_rep(c1_r); opt_index = dp_optimal_point_sampling_Single(c1_r,c2,alpha,beta,window_size); % second curve optimal sampling solution c2_r = c2; c2_r.points = Tools.normal_points(c2.points(opt_index,:)); c2_r = curve_rep(c2_r); elseif type == 0 % sampling both shapes opt_index = dp_optimal_point_sampling_Both(c1,c2,alpha,beta,window_size,sample_points); % first curve optimal sampling solution c1_r = c1; c1_r.points = Tools.normal_points(c1.points(opt_index(:,1),:)); c1_r = curve_rep(c1_r); % second curve optimal sampling solution c2_r = c2; c2_r.points = Tools.normal_points(c2.points(opt_index(:,2),:)); c2_r = curve_rep(c2_r); end end function plot_opt_paths(cost,index1,index2,index3) % Description: Visualizes the optimal solution and the % search space defined by the window size. % % INPUT : cost - (m,n) or (m,m,n) dimensional array of % : index1 - (n,1) vector, solution based on % deformation only. % : index2 - (n,1) vector, solution based on % area only. % : index3 - (n,1) vector, solution based on % constrained objective functional. R = cost; sample_size = size(R,3); figure; if sample_size == 1 % heat plot of cost and solution paths imagesc(R); hold on; set(gca,'XAxisLocation','top'); xllhand = get(gca,'xlabel'); yllhand = get(gca,'ylabel'); set(xllhand,'string','Index of sampled points: [1,z]','fontsize',15); set(yllhand,'string','Index of shape points','fontsize',15); colormap jet; hold on; %solution paths plot(index1,'Linewidth',2,'Color','green'); hold on; % deformation plot(index2,'Linewidth',2,'color','red');hold on; % area plot(index3,'Linewidth',2,'color','yellow'); % constrained legend('Deformation ONLY','Area preservation ONLY','Combined'); else % a sliced visualization of the cost space and the solution path slices = 6; l = ceil(sample_size/slices); Sz = 1:l:sample_size; h = slice(R,[],[],Sz); set(h,'FaceColor','interp','EdgeColor','none'); alpha 0.25; contourslice(R,[],[],Sz); colormap jet; hold on; f_inds = (1:1:sample_size)'; % index of the subfunctions line(index1(:,1),index1(:,2),f_inds,'DisplayName','Deformation ONLY','Linewidth',2,'Color','green'); hold on; % unconstrained line(index2(:,1),index2(:,2),f_inds,'Linewidth',2,'color','red'); hold on; % uniform sampling line(index3(:,1),index3(:,2),f_inds,'Linewidth',2,'color','yellow'); hold on; % constrained %legend('','Area preservation ONLY','Combined'); ax = gca; ax.BoxStyle = 'full'; box on; hold on; grid off; hold on; set(gca,'XAxisLocation','top'); xllhand = get(gca,'xlabel'); yllhand = get(gca,'ylabel'); zllhand = get(gca,'zlabel'); set(xllhand,'string','Curve-1','fontsize',10); set(yllhand,'string','Curve-2','fontsize',10); set(zllhand,'string','Sub-functions index [1-z]','fontsize',10); hold on; view([-37,32]); end title('Solution paths'); hold off; end end end
{ "content_hash": "c8acf34eb3d7fbc16b08524cf400f840", "timestamp": "", "source": "github", "line_count": 288, "max_line_length": 141, "avg_line_length": 43.239583333333336, "alnum_prop": 0.45250140528386734, "repo_name": "DemisseG/Curved_shape_representation", "id": "765f16a6402818c3fc42f5cdbf49c605155e8fce", "size": "12455", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Classes/Tools.m", "mode": "33188", "license": "mit", "language": [ { "name": "Matlab", "bytes": "72388" } ], "symlink_target": "" }
package org.objectstyle.graphql.test.cayenne; import org.objectstyle.graphql.test.cayenne.auto._E1; public class E1 extends _E1 { private static final long serialVersionUID = 1L; }
{ "content_hash": "1bd79a6ee0d6615bbca1bbcde5153179", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 53, "avg_line_length": 21.11111111111111, "alnum_prop": 0.7631578947368421, "repo_name": "objectstyle/graphql", "id": "812e774032a99875934dd07928827760ab5e60a4", "size": "190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "26342" }, { "name": "HTML", "bytes": "3268" }, { "name": "Java", "bytes": "113269" }, { "name": "JavaScript", "bytes": "911699" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "b4c49e40c8d917efb77491dc76a46758", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "53b7db78fc7ee1debc82e6813632a9c7626e7c09", "size": "198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Heterotheca/Heterotheca villosa/ Syn. Chrysopsis villosa villosa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/** * This package contains a set of predefined aggregation implementations */ package com.hazelcast.mapreduce.aggregation.impl;
{ "content_hash": "0667aebf0de6fd92898461367e43e247", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 72, "avg_line_length": 22.166666666666668, "alnum_prop": 0.7819548872180451, "repo_name": "lmjacksoniii/hazelcast", "id": "2809fa8e4fa16cf06ac06fb7a7c6d3a32055e5fe", "size": "758", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/impl/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "948" }, { "name": "Java", "bytes": "28952463" }, { "name": "Shell", "bytes": "13259" } ], "symlink_target": "" }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Medallion.Tools.InlineNuGet.Tests { public class CSharp6SyntaxRewriterTest { private readonly ITestOutputHelper output; public CSharp6SyntaxRewriterTest(ITestOutputHelper output) { this.output = output; } [Fact] public void SimpleTest() { var compilationUnit = SyntaxFactory.ParseCompilationUnit(@" namespace Foo { public class A { public string X(int a) { return nameof(a) + $""_{a, 1:0.0}_"" + $@""_{100}_{200, 0}abc"" + $""xyz""; } public void Y() { } public void Z() => this.Y(); public int Val() => 2; public int Q => 100; } }" ); var compilation = CSharpCompilation.Create("Foo", new[] { compilationUnit.SyntaxTree }, new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }); var model = compilation.GetSemanticModel(compilationUnit.SyntaxTree); var rewriter = new CSharp6SyntaxRewriter(model); var visited = rewriter.Visit(compilationUnit); this.output.WriteLine(visited.ToFullString()); var parsed = SyntaxFactory.ParseCompilationUnit(visited.ToFullString(), options: new CSharpParseOptions(LanguageVersion.CSharp5)); Assert.Equal(actual: parsed.ContainsDiagnostics, expected: false); } } }
{ "content_hash": "edf7e8aa807ad891a2a4fa847476c44e", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 178, "avg_line_length": 33.67307692307692, "alnum_prop": 0.5933752141633353, "repo_name": "madelson/MedallionUtilities", "id": "1753af13f2aff08ab103dcca4448dddcc54845da", "size": "1753", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "InlineNuGet.Tests/CSharp6SyntaxRewriterTest.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "698724" } ], "symlink_target": "" }
{% extends 'kore.html' %} {% load static compress %} {% block title %}LouerSansCom {{ block.super }}{% endblock %} {% block media %} {% compress css %} <link type="text/less" rel="stylesheet" href="{{ STATIC_URL }}less/louersanscom.less" /> {% endcompress %} {{ block.super }} {% endblock %}
{ "content_hash": "b825f5f67a51c323484050b35a468fe9", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 92, "avg_line_length": 21.928571428571427, "alnum_prop": 0.6026058631921825, "repo_name": "ouhouhsami/louersanscom", "id": "f063309fe2c64921bd9aede459cd1cab4053d195", "size": "307", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "louersanscom/templates/kore.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.linecorp.armeria.common; import static com.google.common.base.MoreObjects.firstNonNull; import java.io.IOException; import java.util.Iterator; import java.util.Map.Entry; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.node.ObjectNode; import com.linecorp.armeria.common.annotation.Nullable; import io.netty.util.AsciiString; /** * Jackson {@link JsonDeserializer} for {@link HttpHeaders} and its subtypes. */ abstract class AbstractHttpHeadersJsonDeserializer<T extends HttpHeaders> extends StdDeserializer<T> { private static final long serialVersionUID = 6308506823069217145L; /** * Creates a new instance. */ AbstractHttpHeadersJsonDeserializer(Class<T> type) { super(type); } @Nullable @Override public final T deserialize(JsonParser p, DeserializationContext ctx) throws IOException { final JsonNode tree = p.getCodec().readTree(p); if (!tree.isObject()) { ctx.reportInputMismatch(HttpHeaders.class, "HTTP headers must be an object."); return null; } final ObjectNode obj = (ObjectNode) tree; final HttpHeadersBuilder builder = newBuilder(); for (final Iterator<Entry<String, JsonNode>> i = obj.fields(); i.hasNext();) { final Entry<String, JsonNode> e = i.next(); final AsciiString name = HttpHeaderNames.of(e.getKey()); final JsonNode values = e.getValue(); if (!values.isArray()) { // Values is a single item, so add it directly. addHeader(ctx, builder, name, values); } else { final int numValues = values.size(); for (int j = 0; j < numValues; j++) { final JsonNode v = values.get(j); addHeader(ctx, builder, name, v); } } } try { @SuppressWarnings("unchecked") final T headers = (T) builder.build(); return headers; } catch (IllegalStateException e) { return ctx.reportInputMismatch(handledType(), firstNonNull(e.getMessage(), "Required headers are missing.")); } } private void addHeader(DeserializationContext ctx, HttpHeadersBuilder builder, AsciiString name, JsonNode valueNode) throws JsonMappingException { if (valueNode.isTextual()) { builder.add(name, valueNode.asText()); } else { ctx.reportInputMismatch(handledType(), "HTTP header '%s' contains %s (%s); only strings are allowed.", name, valueNode.getNodeType(), valueNode); } } abstract HttpHeadersBuilder newBuilder(); }
{ "content_hash": "6128ccaa0abc9123f13b90f73d7224f7", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 106, "avg_line_length": 36.195402298850574, "alnum_prop": 0.6259129882502382, "repo_name": "trustin/armeria", "id": "fbf527a43db3884ee3decab74a183650aeb89509", "size": "3782", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "core/src/main/java/com/linecorp/armeria/common/AbstractHttpHeadersJsonDeserializer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7197" }, { "name": "HTML", "bytes": "1222" }, { "name": "Java", "bytes": "17111554" }, { "name": "JavaScript", "bytes": "26583" }, { "name": "Kotlin", "bytes": "95340" }, { "name": "Less", "bytes": "35092" }, { "name": "Scala", "bytes": "230968" }, { "name": "Shell", "bytes": "2062" }, { "name": "Thrift", "bytes": "252456" }, { "name": "TypeScript", "bytes": "255034" } ], "symlink_target": "" }
SCRIPT_DIR="${BASH_SOURCE%/*}" if [[ ! -d "$SCRIPT_DIR" ]]; then SCRIPT_DIR="$PWD"; fi source "${SCRIPT_DIR}/../library.sh" function initial_setup() { progress "Upgrading system..." && \ sudo yum install -y epel-release && \ sudo yum -y upgrade } function install_guest_additions() { installed=$( lsmod | grep vboxguest ) if [[ "${installed}" != "" ]] then warning "Guest Additions already installed. \n\tSkipping..." else progress "Installing Guest Additions..." && \ sudo yum install -y gcc kernel-devel kernel-headers dkms make bzip2 perl && \ sudo mount /dev/sr0 /mnt && \ sudo sh /mnt/VBoxLinuxAdditions.run && \ sudo umount /mnt fi } function install_misc_utilities() { installed=$( yum list installed | grep "expect" ) if [[ "${installed}" = "" ]] then progress "Updating misc packages" && \ sudo yum groupinstall -y "Development Tools" && \ sudo yum install -y expect yum-utils else warning "Misc packages already installed. \n\tSkipping..." fi } function misc_configuration() { # Turn off SElinux target_string='^(SELINUX=)enforcing$' substitute='disabled' config_path="/etc/selinux/config" sudo sed -i -r "s|${target_string}|\1${substitute}|w ${SED_LOG}" ${config_path} if [[ -s ${SED_LOG} ]] then modified=$( cat ${SED_LOG} ) progress "Changed config patterned [${target_string}] to [${modified}] in ${config_path}." sudo setenforce 0 else warning "Could not find config pattern [${target_string}] in ${config_path}. \n\tSkipping..." fi # Clean up old kernel versions and keep only 2 most recent kernels progress "Cleaning up old kernels..." limit=$(grep -e 'installonly_limit=2' /etc/yum.conf) if [[ "${limit}" = "" ]] then sudo package-cleanup --oldkernels --count=2 && \ sudo sed -ri 's/(installonly_limit)=5/\1=2/' /etc/yum.conf && \ progress "Kernel limit set to 2." else warning "Old kernel limit already set. \n\tSkipping..." fi } script_started initial_setup install_guest_additions install_misc_utilities misc_configuration script_ended
{ "content_hash": "652f3db8df9e3f380b2204f0bd98d90b", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 97, "avg_line_length": 29.375, "alnum_prop": 0.6453900709219859, "repo_name": "justinmoh/mockingj", "id": "d9eaf9a63be8e561ea91e0ad88d519694ec1de36", "size": "2211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BoxManagement/install/01-initial.sh", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "6450" }, { "name": "Ruby", "bytes": "7334" }, { "name": "Shell", "bytes": "41951" } ], "symlink_target": "" }
package lila.app package templating import lila.api.Context import lila.app.ui.ScalatagsTemplate._ trait FlashHelper { self: I18nHelper => def standardFlash(modifiers: Modifier*)(implicit ctx: Context): Option[Frag] = successFlash(modifiers) orElse warningFlash(modifiers) orElse failureFlash(modifiers) def successFlash(modifiers: Seq[Modifier])(implicit ctx: Context): Option[Frag] = ctx.flash("success").map { msg => flashMessage(modifiers ++ Seq(cls := "flash-success"))( if (msg.isEmpty) trans.success() else msg ) } def warningFlash(modifiers: Seq[Modifier])(implicit ctx: Context): Option[Frag] = ctx.flash("warning").map { msg => flashMessage(modifiers ++ Seq(cls := "flash-warning"))( if (msg.isEmpty) "Warning" else msg ) } def failureFlash(modifiers: Seq[Modifier])(implicit ctx: Context): Option[Frag] = ctx.flash("failure").map { msg => flashMessage(modifiers ++ Seq(cls := "flash-failure"))( if (msg.isEmpty) "Failure" else msg ) } def flashMessage(modifiers: Seq[Modifier])(msg: Frag): Frag = flashMessage(modifiers: _*)(msg) def flashMessage(modifiers: Modifier*)(contentModifiers: Modifier*): Frag = div(modifiers)(cls := "flash")( div(cls := "flash__content")(contentModifiers) ) }
{ "content_hash": "a9d4f0780896cebc09256b0adf638cd9", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 89, "avg_line_length": 33.15, "alnum_prop": 0.667420814479638, "repo_name": "luanlv/lila", "id": "dfe31d70333f04102756321894c17608f5060b67", "size": "1326", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "app/templating/FlashHelper.scala", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "849" }, { "name": "CSS", "bytes": "228239" }, { "name": "Cycript", "bytes": "3701" }, { "name": "Emacs Lisp", "bytes": "31342" }, { "name": "Erlang", "bytes": "19825" }, { "name": "Fancy", "bytes": "119" }, { "name": "GAP", "bytes": "11334" }, { "name": "GLSL", "bytes": "2434" }, { "name": "HTML", "bytes": "332219" }, { "name": "Hy", "bytes": "20591" }, { "name": "Io", "bytes": "4943" }, { "name": "Java", "bytes": "21183" }, { "name": "JavaScript", "bytes": "434326" }, { "name": "Makefile", "bytes": "15207" }, { "name": "Mathematica", "bytes": "18454" }, { "name": "NewLisp", "bytes": "19130" }, { "name": "OCaml", "bytes": "1709" }, { "name": "Perl6", "bytes": "19794" }, { "name": "PostScript", "bytes": "2604" }, { "name": "Python", "bytes": "1959" }, { "name": "Ruby", "bytes": "31020" }, { "name": "Scala", "bytes": "1673987" }, { "name": "Shell", "bytes": "9946" }, { "name": "Slash", "bytes": "18065" }, { "name": "Smalltalk", "bytes": "18999" }, { "name": "SystemVerilog", "bytes": "17827" } ], "symlink_target": "" }
import Immutable from 'seamless-immutable'; import { stringify } from 'qs'; import { gameEntity } from '../../schemas/adminSchemas'; import { generateComponent } from '../../ducks/domain'; import { getDataAuth, submitDataAuth } from '../../actions/fetchAndSave'; const componentName = 'GamesTable'; const component = generateComponent(componentName); const route = '/api/admin/games'; export function fetchGames() { return (dispatch) => { const query = dispatch(component.getState()).query; return dispatch(getDataAuth(`${route}?${stringify(query)}`)) .normalize([gameEntity]) .save() .asJson() .exec(component); }; } export function deleteGame(id) { return dispatch => dispatch(submitDataAuth(`${route}/${id}`)).delete().json({}).exec(); } export function changeOrder(id, order) { return dispatch => dispatch(submitDataAuth(`${route}/${id}?action=swaporder`)).patch().json({ order }).exec(); } const defaultState = Immutable({ query: { sort: 'order', }, }); export default { defaultState, };
{ "content_hash": "3e02e9e00be269f456bb51e0b9dd7f30", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 95, "avg_line_length": 25.804878048780488, "alnum_prop": 0.6644612476370511, "repo_name": "2fort/touhou-test-next", "id": "428eecfa873476b039ed9c9bd332cb524dc962c1", "size": "1058", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/src/js/containers-admin/Games/GamesTable.duck.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1822" }, { "name": "JavaScript", "bytes": "223092" } ], "symlink_target": "" }
package com.taobao.weex.ui.action; public class GraphicPosition { private float mLeft; private float mTop; private float mRight; private float mBottom; public GraphicPosition(float left, float top, float right, float bottom) { this.mLeft = left; this.mTop = top; this.mRight = right; this.mBottom = bottom; } public float getLeft() { return mLeft; } public void setLeft(float left) { this.mLeft = left; } public float getTop() { return mTop; } public void setTop(float top) { this.mTop = top; } public float getRight() { return mRight; } public void setRight(float right) { this.mRight = right; } public float getBottom() { return mBottom; } public void setBottom(float bottom) { this.mBottom = bottom; } }
{ "content_hash": "e453bd3d8208d145cbb7ccfe1905602c", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 76, "avg_line_length": 16.551020408163264, "alnum_prop": 0.6448828606658447, "repo_name": "cxfeng1/incubator-weex", "id": "9cb0e2dcad5bbf22b61d22385243a41d1cc688ae", "size": "1619", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/sdk/src/main/java/com/taobao/weex/ui/action/GraphicPosition.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1100" }, { "name": "C", "bytes": "54245" }, { "name": "HTML", "bytes": "3207" }, { "name": "Java", "bytes": "5012936" }, { "name": "JavaScript", "bytes": "4083613" }, { "name": "Objective-C", "bytes": "1606353" }, { "name": "Objective-C++", "bytes": "48153" }, { "name": "Ruby", "bytes": "5297" }, { "name": "Shell", "bytes": "20622" }, { "name": "Vue", "bytes": "110901" } ], "symlink_target": "" }
using PIM.Database.TO; using PIM.Service.Services; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PIM.Desktop { public partial class frmCadastrarOcorrencia : Form { public frmCadastrarOcorrencia() { InitializeComponent(); } private void btnCancelarOco_Click(object sender, EventArgs e) { this.Close(); } private void btnSalvarOco_Click(object sender, EventArgs e) { string erro = String.Empty; if (!ValidarCampos(out erro)) { MessageBox.Show(erro, "Atenção"); } OcorrenciaTO ocorrenciaTO = new OcorrenciaTO(); ocorrenciaTO.IdMorador = Convert.ToInt32(txtCodMorCadOco.Text); ocorrenciaTO.DataOcorrencia = Convert.ToDateTime(txtDataCadOco.Text); ocorrenciaTO.Motivo = txtMotivoCadOco.Text; ocorrenciaTO.Descricao = rtxtDescricaoOco.Text; OcorrenciaService.Criar(ocorrenciaTO); if (!ocorrenciaTO.Valido) { MessageBox.Show(ocorrenciaTO.Mensagem, "Atenção"); return; } this.Close(); } private bool ValidarCampos(out string erro) { string msgErro = string.Empty; erro = string.Empty; if (string.IsNullOrEmpty(txtCodMorCadOco.Text)) { msgErro += "Preenchimento do Código obrigatório\n"; } if (string.IsNullOrEmpty(txtDataCadOco.Text)) { msgErro += "Preenchimento da data obrigatório\n"; } if (string.IsNullOrEmpty(txtMotivoCadOco.Text)) { msgErro += "Preenchimento do Motivo obrigatório\n"; } if (string.IsNullOrEmpty(rtxtDescricaoOco.Text)) { msgErro += "Preenchimento da Descrição obrigatório\n"; } if (!string.IsNullOrEmpty(msgErro)) { erro = msgErro; return false; } else { return true; } } } }
{ "content_hash": "9097e8aff7cc23548c215694db711f54", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 81, "avg_line_length": 26.21978021978022, "alnum_prop": 0.5477787091366303, "repo_name": "LucasMonteiroi/pim-condominio", "id": "959e3f7643c6cc676f48ac5dbc491e1561816840", "size": "2399", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "01_Desenvolvimento/project/PIM/PIM.Desktop/frmCadastrarOcorrencia.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "196" }, { "name": "C#", "bytes": "894870" }, { "name": "CSS", "bytes": "1056832" }, { "name": "JavaScript", "bytes": "6742288" }, { "name": "PowerShell", "bytes": "169189" } ], "symlink_target": "" }
.jslider { display: block; width: 100%; height: 1em; position: relative; top: 0.6em; font-family: Arial, sans-serif; } .jslider table { width: 100%; border-collapse: collapse; border: 0; } .jslider td, .jslider th { padding: 0; vertical-align: top; text-align: left; border: 0; } .jslider table, .jslider table tr, .jslider table tr td { width: 100%; vertical-align: top; } .jslider .jslider-bg { position: relative; z-index:0;} .jslider .jslider-bg i { height: 5px; position: absolute; font-size: 0; top: 0; } .jslider .jslider-bg .l { width: 50%; left: 0;background: #31BABA; z-index: 0;} .jslider .jslider-bg .r { width: 50%; left: 50%; background: #d90000;z-index: 0} .jslider .jslider-bg .v { position: absolute; width: 60%; left: 20%; top: 0; height: 5px; background: #FF7F00;z-index: 3} .bar_color .jslider .jslider-bg .l { width: 80%; left: 0;background: #31BABA; z-index: 0;} .bar_color .jslider .jslider-bg .r { width: 0%; left: 80%; background: #085e5d;z-index: 0} .bar_color .jslider .jslider-bg .v { display:block;position: absolute; width: 20%; left: 80%; top: 0; height: 5px; background: #058d8d;z-index: 3} .bar_color2 .jslider .jslider-bg .r { background: #31BABA;} #addMonitorPanel .jslider-bg .l ,#editMonitorConfigWindow .jslider-bg .l{ width: 80%; left: 0;} #addMonitorPanel .jslider-bg .r ,#editMonitorConfigWindow .jslider-bg .r{ width: 20%; left: 80%; background: #058d8d;} .jslider .jslider-bg i i{ display: block; width: 100%; position: relative; top: 6px; text-align: center; height: 20px; color: #999; font-size:12px; font-style: normal; } #editMonitorConfigWindow .jslider-bg i i{ display : none; } .jslider .jslider-pointer { width: 17px; height: 17px; position: absolute; left: 20%; top: -6px; margin-left: -8px; background: #fff; border-radius: 50%; border: 1px solid #ccc; cursor: pointer; -z-index: 10!important; } .jslider .jslider-pointer-hover { background-position: -20px -40px; } .jslider .jslider-pointer-to { left: 80%; } .jslider .jslider-label { font-size: 9px; line-height: 12px; color: black; opacity: 0.4; white-space: nowrap; padding: 0px 2px; position: absolute; top: -18px; left: 0px; } .jslider .jslider-label-to { left: auto; right: 0; } .jslider .jslider-value { font-size: 12px; white-space: nowrap; padding: 1px 5px ; position: absolute; top: -19px; left: 20%; background: none; line-height: 12px; -moz-border-radius: 2px; -webkit-border-radius: 2px; -o-border-radius: 2px; border-radius: 2px; } .jslider .jslider-value-to { left: 80%; } .jslider .jslider-label small, .jslider .jslider-value small { position: relative; top: -0.4em; } .jslider .jslider-scale { position: relative; top: 9px; } .jslider .jslider-scale span { position: absolute; height: 5px; border-left: 1px solid #999; font-size: 0; } .jslider .jslider-scale ins { font-size: 9px; text-decoration: none; position: absolute; left: 0px; top: 5px; color: #999; } .jslider-single .jslider-pointer-to, .jslider-single .jslider-value-to, .jslider-single .jslider-bg .v, .jslider-limitless .jslider-label { display: none; } .jslider .jslider-pointer { }
{ "content_hash": "36275d9fecbbf2231db2791bf7cd3d1e", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 260, "avg_line_length": 45.79710144927536, "alnum_prop": 0.6806962025316455, "repo_name": "xiaolds/tomcat7", "id": "4d5925a3159dba6e817850413adcbcc9ef4985de", "size": "3160", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webapps/ROOT/css/jslider.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "765506" }, { "name": "HTML", "bytes": "1118525" }, { "name": "Java", "bytes": "19582353" }, { "name": "JavaScript", "bytes": "6461051" }, { "name": "NSIS", "bytes": "40066" }, { "name": "Perl", "bytes": "13860" }, { "name": "XSLT", "bytes": "37302" } ], "symlink_target": "" }
package org.jimmutable.cloud.storage; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.jimmutable.cloud.CloudExecutionEnvironment; import org.jimmutable.cloud.IntegrationTest; import org.jimmutable.cloud.storage.s3.RegionSpecificAmazonS3ClientFactory; import org.jimmutable.cloud.storage.s3.StorageS3; import org.jimmutable.core.exceptions.ValidationException; import org.jimmutable.core.utils.FileUtils; import org.jimmutable.core.utils.Validator; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.CreateBucketRequest; import com.amazonaws.services.s3.model.ListVersionsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.model.S3VersionSummary; import com.amazonaws.services.s3.model.VersionListing; public class StorageS3IT extends IntegrationTest { // We need a flag to prevent deleteBucket() from running when an exception is thrown from setUp() static private boolean bucket_created = false; static private StorageS3 storage; /********************** * Setup/Teardown * *********************/ @BeforeClass static public void setup() { setupEnvironment(); checkCredentials(); // Okay, we're good. Proceed. storage = new StorageS3(RegionSpecificAmazonS3ClientFactory.defaultFactory(), CloudExecutionEnvironment.getSimpleCurrent().getSimpleApplicationId(), false); createBucket(); } static private void checkCredentials() { try { DefaultAWSCredentialsProviderChain.getInstance().getCredentials(); } catch (com.amazonaws.SdkClientException e) { String message = "Must provide AWS credentials, as per DefaultAWSCredentialsProviderChain.\n" + "For EC2 instances, this will be provided by the Role assigned when the instance launched.\n" + "For dev environments, this should be provided by -Daws.accessKeyId and -Daws.secretKey. These values can be found in your IAM account."; System.err.println(message); throw e; } } static private void createBucket() { AmazonS3Client client = RegionSpecificAmazonS3ClientFactory.defaultFactory().create(); if (client.doesBucketExist(storage.getSimpleBucketName())) { String message = "The unit test bucket - " + storage.getSimpleBucketName() + " - must NOT already exist.\n" + "This is to provide a clean environment for the integration test.\n" + "It might also be an indication that this test is running on another instance somewhere.\n" + "Please ensure that the test bucket is deleted and try running this test again."; System.err.println(message); throw new ValidationException(); } CreateBucketRequest request = new CreateBucketRequest(storage.getSimpleBucketName(), RegionSpecificAmazonS3ClientFactory.DEFAULT_REGION); client.createBucket(request); bucket_created = true; } @AfterClass static public void tearDown() { if (bucket_created) { deleteBucket(); } } static private void deleteAllObjects() { AmazonS3Client client = RegionSpecificAmazonS3ClientFactory.defaultFactory().create(); ObjectListing listing = client.listObjects(storage.getSimpleBucketName()); for (S3ObjectSummary object : listing.getObjectSummaries()) { try { client.deleteObject(object.getBucketName(), object.getKey()); } catch (Exception e) { e.printStackTrace(); } } } static private void deleteAllObjectVersions() { AmazonS3Client client = RegionSpecificAmazonS3ClientFactory.defaultFactory().create(); VersionListing versions = client.listVersions(new ListVersionsRequest().withBucketName(storage.getSimpleBucketName())); for (S3VersionSummary version : versions.getVersionSummaries()) { try { client.deleteVersion(version.getBucketName(), version.getKey(), version.getVersionId()); } catch (Exception e) { e.printStackTrace(); } } } static private void deleteBucket() { // First, delete all objects deleteAllObjects(); // Second, delete all object versions deleteAllObjectVersions(); // Finally, delete the bucket itself AmazonS3Client client = RegionSpecificAmazonS3ClientFactory.defaultFactory().create(); client.deleteBucket(storage.getSimpleBucketName()); } /************* * Tests ************/ @Test public void testUpsertAndGet() throws IOException { // Basic put { StorageKey test_key = new GenericStorageKey("s3-test-upsert/put.txt"); // Put assertTrue(storage.upsert(test_key, "arstarstarst".getBytes(), false)); byte[] test_value = storage.getCurrentVersion(test_key, new byte[0]); assertArrayEquals(test_value, "arstarstarst".getBytes()); // Update assertTrue(storage.upsert(test_key, "oineoienoienoien".getBytes(), false)); test_value = storage.getCurrentVersion(test_key, new byte[0]); assertArrayEquals(test_value, "oineoienoienoien".getBytes()); } // Fail if byte[] > 25 MB { byte[] large_value = new byte[StorageS3.MAX_TRANSFER_BYTES_IN_BYTES + 1]; Arrays.fill(large_value, (byte) 3); try { storage.upsert(new GenericStorageKey("s3-test-upsert/too_big.txt"), large_value, false); fail("Expected ValidationException"); } catch (ValidationException e) { // Expected } } // Upsert w/ stream { File temp_source = File.createTempFile("s3_test_upsert_source_", ".txt"); File temp_dest = File.createTempFile("s3_test_upsert_dest_", ".txt"); temp_source.deleteOnExit(); temp_dest.deleteOnExit(); // Put FileUtils.quietWriteFile(temp_source, "Over the river and through the woods"); StorageKey stream_key = new GenericStorageKey("s3-test-upsert/stream.txt"); try (InputStream fin = new FileInputStream(temp_source)) { assertTrue(storage.upsertStreaming(stream_key, fin, false)); } try (OutputStream fout = new FileOutputStream(temp_dest)) { assertTrue(storage.getCurrentVersionStreaming(stream_key, fout)); } String test_value = FileUtils.getComplexFileContentsAsString(temp_dest, null); assertEquals(test_value, "Over the river and through the woods"); // Update FileUtils.quietWriteFile(temp_source, "Victoria Falls is really, really high"); try (InputStream fin = new FileInputStream(temp_source)) { assertTrue(storage.upsertStreaming(stream_key, fin, false)); } try (OutputStream fout = new FileOutputStream(temp_dest)) { assertTrue(storage.getCurrentVersionStreaming(stream_key, fout)); } test_value = FileUtils.getComplexFileContentsAsString(temp_dest, null); assertEquals(test_value, "Victoria Falls is really, really high"); } } @Test public void testExists() { // Generic keys { StorageKey generic_not_exist = new GenericStorageKey("s3-test-exists/imaginary.txt"); assertFalse(storage.exists(generic_not_exist, false)); StorageKey generic_exists = new GenericStorageKey("s3-test-exists/exists.txt"); assertTrue(storage.upsert(generic_exists, "I'm a real boy!".getBytes(), false)); assertTrue(storage.exists(generic_exists, false)); } // ObjectId's { StorageKey object_id_not_exist = new ObjectIdStorageKey("s3-test-exists/0x7fff-ffff-ffff-ffff.txt"); assertFalse(storage.exists(object_id_not_exist, false)); StorageKey object_id_exists = new ObjectIdStorageKey("s3-test-exists/1111-1111-1111-1111.txt"); assertTrue(storage.upsert(object_id_exists, "I think I can... I think I can... I think I can...".getBytes(), false)); assertTrue(storage.exists(object_id_exists, false)); } } @Test public void testDelete() { StorageKey test_key = new GenericStorageKey("s3-test-delete/delete_me.txt"); assertFalse(storage.exists(test_key, false)); assertTrue(storage.upsert(test_key, "qwfpqwfpqwfpqwpf".getBytes(), false)); assertTrue(storage.exists(test_key, false)); assertTrue(storage.delete(test_key)); assertFalse(storage.exists(test_key, false)); } @Test public void testDeleteAll() { //TODO } @Test public void testGetMetadata() { StorageKey test_key = new GenericStorageKey("s3-test-metadata/metadata.txt"); assertNull(storage.getObjectMetadata(test_key, null)); assertTrue(storage.upsert(test_key, ".,mka.srntkoiylakrvoscyuanvo".getBytes(), false)); long after_upsert = System.currentTimeMillis(); StorageMetadata metadata = storage.getObjectMetadata(test_key, null); assertNotNull(metadata); assertEquals(".,mka.srntkoiylakrvoscyuanvo".length(), metadata.getSimpleSize()); assertTrue(Math.abs(metadata.getSimpleLastModified() - after_upsert) < 1000); // Within 1 sec of after_upsert, since S3 can record the "modified" time slightly differently than us assertNotNull(metadata.getSimpleEtag()); // No way to know what this will be assertNull(storage.getObjectMetadata(new GenericStorageKey("s3-test-metadata/does_not_exist.txt"), null)); } private class ConcurrencyTest implements Runnable { private final StorageKey key; public ConcurrencyTest(final StorageKey key) { Validator.notNull(key); this.key = key; } @Override public void run() { try { final String contents1 = String.valueOf(key.hashCode()); final String contents2 = String.valueOf(3.14 * key.hashCode()); long after_upsert = 0L; assertFalse(storage.exists(key, false)); // Basic put { // Put assertTrue(storage.upsert(key, contents1.getBytes(), false)); after_upsert = System.currentTimeMillis(); assertTrue(storage.exists(key, false)); byte[] test_value = storage.getCurrentVersion(key, new byte[0]); assertArrayEquals(test_value, contents1.getBytes()); // Update assertTrue(storage.upsert(key, contents2.getBytes(), false)); after_upsert = System.currentTimeMillis(); assertTrue(storage.exists(key, false)); test_value = storage.getCurrentVersion(key, new byte[0]); assertArrayEquals(test_value, contents2.getBytes()); } // Upsert w/ stream { File temp_source = File.createTempFile("s3_test_concurrency_source_", ".txt"); File temp_dest = File.createTempFile("s3_test_concurrency_dest_", ".txt"); temp_source.deleteOnExit(); temp_dest.deleteOnExit(); // Put FileUtils.quietWriteFile(temp_source, contents1); try (InputStream fin = new FileInputStream(temp_source)) { assertTrue(storage.upsertStreaming(key, fin, false)); after_upsert = System.currentTimeMillis(); } try (OutputStream fout = new FileOutputStream(temp_dest)) { assertTrue(storage.getCurrentVersionStreaming(key, fout)); } String test_value = FileUtils.getComplexFileContentsAsString(temp_dest, null); assertEquals(test_value, contents1); // Update FileUtils.quietWriteFile(temp_source, contents2); try (InputStream fin = new FileInputStream(temp_source)) { assertTrue(storage.upsertStreaming(key, fin, false)); after_upsert = System.currentTimeMillis(); } try (OutputStream fout = new FileOutputStream(temp_dest)) { assertTrue(storage.getCurrentVersionStreaming(key, fout)); } test_value = FileUtils.getComplexFileContentsAsString(temp_dest, null); assertEquals(test_value, contents2); } // Metadata { StorageMetadata metadata = storage.getObjectMetadata(key, null); assertNotNull(metadata); assertEquals(contents2.length(), metadata.getSimpleSize()); assertTrue(Math.abs(metadata.getSimpleLastModified() - after_upsert) < 1000); // Within 1 sec of after_upsert, since S3 can record the "modified" time slightly differently than us assertNotNull(metadata.getSimpleEtag()); // No way to know what this will be } // Delete { assertTrue(storage.exists(key, false)); assertTrue(storage.delete(key)); assertFalse(storage.exists(key, false)); assertNull(storage.getObjectMetadata(key, null)); } } catch (Exception e) { // Fail for any exception fail(e.getMessage()); } } } @Test public void testMultithreadedUsage() throws Throwable { ExecutorService worker_pool = Executors.newFixedThreadPool(5); List<Future<?>> futures = new ArrayList<>(); futures.add(worker_pool.submit(new ConcurrencyTest(new GenericStorageKey("s3-test-concurrency/one.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new ObjectIdStorageKey("s3-test-concurrency/0x1111-1111-1111-1111.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new GenericStorageKey("s3-test-concurrency/two.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new ObjectIdStorageKey("s3-test-concurrency/0x2222-2222-2222-2222.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new GenericStorageKey("s3-test-concurrency/three.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new ObjectIdStorageKey("s3-test-concurrency/0x3333-3333-3333-3333.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new GenericStorageKey("s3-test-concurrency/four.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new ObjectIdStorageKey("s3-test-concurrency/0x4444-4444-4444-4444.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new GenericStorageKey("s3-test-concurrency/five.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new ObjectIdStorageKey("s3-test-concurrency/0x5555-5555-5555-5555.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new GenericStorageKey("s3-test-concurrency/six.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new ObjectIdStorageKey("s3-test-concurrency/0x6666-6666-6666-6666.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new GenericStorageKey("s3-test-concurrency/seven.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new ObjectIdStorageKey("s3-test-concurrency/0x7777-7777-7777-7777.txt")))); futures.add(worker_pool.submit(new ConcurrencyTest(new GenericStorageKey("s3-test-concurrency/eight.txt")))); worker_pool.shutdown(); // Wait for all futures to finish for (Future<?> future : futures) { try { future.get(); } catch (ExecutionException e) { // If the Future threw an exception, so do we throw e.getCause(); } } } }
{ "content_hash": "983c1e3f1c7a88e5374bcb283f486957", "timestamp": "", "source": "github", "line_count": 468, "max_line_length": 199, "avg_line_length": 41.21153846153846, "alnum_prop": 0.5701768030279463, "repo_name": "jimmutable/core", "id": "e7ec30201e8d6b0280d5ffc36b1d21fd3c744f7d", "size": "19287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cloud/src/test/java/org/jimmutable/cloud/storage/StorageS3IT.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "2185" }, { "name": "Java", "bytes": "1632103" } ], "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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.contentwarehouse.v1.model; /** * Value is derived from previous task state (go/taskstates). * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState extends com.google.api.client.json.GenericJson { /** * Argument names in the DialogIntentState that the argument corresponds to. This is repeated so * it can handle complex argument update paths. (ordered from outermost argument to innermost * argument) * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> argumentName; /** * The span(s) in the current query (if any) used to resolve the previous query's DIS. Example: U: * Barack Obama G: Do you want his age or his height? U: The first one. G: Age(/m/obama) In this * example, the intent is derived from the previous query's DIS, but also needs to be resolved in * the current query since the user was presented with multiple options. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<NlpSemanticParsingAnnotationEvalData> currentQueryEvalData; /** * The id of the specific DialogIntentState instance that the argument corresponds to. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String dialogIntentStateId; /** * Intent name of the DialogIntentState that the argument corresponds to. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String intentName; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskStateListCandidate listCandidate; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskStatePreviousFunctionCall previousFunctionCall; /** * Argument names in the DialogIntentState that the argument corresponds to. This is repeated so * it can handle complex argument update paths. (ordered from outermost argument to innermost * argument) * @return value or {@code null} for none */ public java.util.List<java.lang.String> getArgumentName() { return argumentName; } /** * Argument names in the DialogIntentState that the argument corresponds to. This is repeated so * it can handle complex argument update paths. (ordered from outermost argument to innermost * argument) * @param argumentName argumentName or {@code null} for none */ public KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState setArgumentName(java.util.List<java.lang.String> argumentName) { this.argumentName = argumentName; return this; } /** * The span(s) in the current query (if any) used to resolve the previous query's DIS. Example: U: * Barack Obama G: Do you want his age or his height? U: The first one. G: Age(/m/obama) In this * example, the intent is derived from the previous query's DIS, but also needs to be resolved in * the current query since the user was presented with multiple options. * @return value or {@code null} for none */ public java.util.List<NlpSemanticParsingAnnotationEvalData> getCurrentQueryEvalData() { return currentQueryEvalData; } /** * The span(s) in the current query (if any) used to resolve the previous query's DIS. Example: U: * Barack Obama G: Do you want his age or his height? U: The first one. G: Age(/m/obama) In this * example, the intent is derived from the previous query's DIS, but also needs to be resolved in * the current query since the user was presented with multiple options. * @param currentQueryEvalData currentQueryEvalData or {@code null} for none */ public KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState setCurrentQueryEvalData(java.util.List<NlpSemanticParsingAnnotationEvalData> currentQueryEvalData) { this.currentQueryEvalData = currentQueryEvalData; return this; } /** * The id of the specific DialogIntentState instance that the argument corresponds to. * @return value or {@code null} for none */ public java.lang.String getDialogIntentStateId() { return dialogIntentStateId; } /** * The id of the specific DialogIntentState instance that the argument corresponds to. * @param dialogIntentStateId dialogIntentStateId or {@code null} for none */ public KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState setDialogIntentStateId(java.lang.String dialogIntentStateId) { this.dialogIntentStateId = dialogIntentStateId; return this; } /** * Intent name of the DialogIntentState that the argument corresponds to. * @return value or {@code null} for none */ public java.lang.String getIntentName() { return intentName; } /** * Intent name of the DialogIntentState that the argument corresponds to. * @param intentName intentName or {@code null} for none */ public KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState setIntentName(java.lang.String intentName) { this.intentName = intentName; return this; } /** * @return value or {@code null} for none */ public KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskStateListCandidate getListCandidate() { return listCandidate; } /** * @param listCandidate listCandidate or {@code null} for none */ public KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState setListCandidate(KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskStateListCandidate listCandidate) { this.listCandidate = listCandidate; return this; } /** * @return value or {@code null} for none */ public KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskStatePreviousFunctionCall getPreviousFunctionCall() { return previousFunctionCall; } /** * @param previousFunctionCall previousFunctionCall or {@code null} for none */ public KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState setPreviousFunctionCall(KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskStatePreviousFunctionCall previousFunctionCall) { this.previousFunctionCall = previousFunctionCall; return this; } @Override public KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState set(String fieldName, Object value) { return (KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState) super.set(fieldName, value); } @Override public KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState clone() { return (KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState) super.clone(); } }
{ "content_hash": "63d05fdb36a6105e504afaefed92ca70", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 202, "avg_line_length": 40.35897435897436, "alnum_prop": 0.7560355781448539, "repo_name": "googleapis/google-api-java-client-services", "id": "da01b6bef6d6aea182e19c6bd9c209de4d60d358", "size": "7870", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "clients/google-api-services-contentwarehouse/v1/2.0.0/com/google/api/services/contentwarehouse/v1/model/KnowledgeAnswersIntentQueryArgumentProvenancePreviousTaskState.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#ifndef __RENDER_TEXT_HPP__ #define __RENDER_TEXT_HPP__ #include <string> #include <memory> class RenderContext; class RenderMaterial; class RenderFont; class RenderText { typedef std::shared_ptr<RenderMaterial> RenderMaterialPtrT; typedef std::shared_ptr<RenderFont> RenderFontPtrT; public: RenderText(); ~RenderText(); void render(RenderContext& ctx); private: void renderGlyph(char ch); private: RenderMaterialPtrT material; RenderFontPtrT font; std::string data; }; #endif /* __RENDER_TEXT_HPP__ */
{ "content_hash": "da3b70875002be7f83c3106c3487f0f3", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 63, "avg_line_length": 16.176470588235293, "alnum_prop": 0.7036363636363636, "repo_name": "lastcolour/AIProject", "id": "14077cafb41f7d3156cdef9264f21e3401d28f37", "size": "550", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sources/Code/Servers/Render/RenderText.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "366856" }, { "name": "CMake", "bytes": "16395" }, { "name": "GLSL", "bytes": "323" }, { "name": "Python", "bytes": "29636" } ], "symlink_target": "" }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; namespace Bunashibu.Kikan { public class Skill : Photon.MonoBehaviour { [PunRPC] protected void SyncInitRPC(int viewID) { _skillUserObj = PhotonView.Find(viewID).gameObject; _skillUserViewID = viewID; } public void SyncInit(int viewID) { Assert.IsTrue(photonView.isMine); photonView.RPC("SyncInitRPC", PhotonTargets.All, viewID); } public int viewID => photonView.viewID; protected GameObject _skillUserObj; protected int _skillUserViewID; } }
{ "content_hash": "50d226f894afba65c0c9d39272d76c27", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 63, "avg_line_length": 23.846153846153847, "alnum_prop": 0.714516129032258, "repo_name": "bunashibu/kikan", "id": "1c4a4209549010bcf9269d4d638e08aaa3d68525", "size": "622", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/Skill/Skill.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "340641" }, { "name": "HLSL", "bytes": "13994" }, { "name": "ShaderLab", "bytes": "80492" } ], "symlink_target": "" }
from copy import deepcopy from functools import partial from gzip import GzipFile import os import os.path as op import numpy as np from scipy import sparse, linalg from .io.constants import FIFF from .io.meas_info import create_info from .io.tree import dir_tree_find from .io.tag import find_tag, read_tag from .io.open import fiff_open from .io.write import (start_block, end_block, write_int, write_float_sparse_rcs, write_string, write_float_matrix, write_int_matrix, write_coord_trans, start_file, end_file, write_id) from .bem import read_bem_surfaces, ConductorModel from .surface import (read_surface, _create_surf_spacing, _get_ico_surface, _tessellate_sphere_surf, _get_surf_neighbors, _normalize_vectors, _get_solids, _triangle_neighbors, complete_surface_info, _compute_nearest, fast_cross_3d, mesh_dist) from .utils import (get_subjects_dir, run_subprocess, has_freesurfer, has_nibabel, check_fname, logger, verbose, _ensure_int, check_version, _get_call_line, warn, _check_fname) from .parallel import parallel_func, check_n_jobs from .transforms import (invert_transform, apply_trans, _print_coord_trans, combine_transforms, _get_trans, _coord_frame_name, Transform, _str_to_frame, _ensure_trans, _read_fs_xfm) def _get_lut(): """Get the FreeSurfer LUT.""" data_dir = op.join(op.dirname(__file__), 'data') lut_fname = op.join(data_dir, 'FreeSurferColorLUT.txt') dtype = [('id', '<i8'), ('name', 'U47'), ('R', '<i8'), ('G', '<i8'), ('B', '<i8'), ('A', '<i8')] return np.genfromtxt(lut_fname, dtype=dtype) def _get_lut_id(lut, label, use_lut): """Convert a label to a LUT ID number.""" if not use_lut: return 1 assert isinstance(label, str) mask = (lut['name'] == label) assert mask.sum() == 1 return lut['id'][mask] _src_kind_dict = { 'vol': 'volume', 'surf': 'surface', 'discrete': 'discrete', } class SourceSpaces(list): """Represent a list of source space. Currently implemented as a list of dictionaries containing the source space information Parameters ---------- source_spaces : list A list of dictionaries containing the source space information. info : dict Dictionary with information about the creation of the source space file. Has keys 'working_dir' and 'command_line'. Attributes ---------- info : dict Dictionary with information about the creation of the source space file. Has keys 'working_dir' and 'command_line'. """ def __init__(self, source_spaces, info=None): # noqa: D102 super(SourceSpaces, self).__init__(source_spaces) if info is None: self.info = dict() else: self.info = dict(info) @verbose def plot(self, head=False, brain=None, skull=None, subjects_dir=None, trans=None, verbose=None): """Plot the source space. Parameters ---------- head : bool If True, show head surface. brain : bool | str If True, show the brain surfaces. Can also be a str for surface type (e.g., 'pial', same as True). Default is None, which means 'white' for surface source spaces and False otherwise. skull : bool | str | list of str | list of dict | None Whether to plot skull surface. If string, common choices would be 'inner_skull', or 'outer_skull'. Can also be a list to plot multiple skull surfaces. If a list of dicts, each dict must contain the complete surface info (such as you get from :func:`mne.make_bem_model`). True is an alias of 'outer_skull'. The subjects bem and bem/flash folders are searched for the 'surf' files. Defaults to None, which is False for surface source spaces, and True otherwise. subjects_dir : string, or None Path to SUBJECTS_DIR if it is not set in the environment. trans : str | 'auto' | dict | None The full path to the head<->MRI transform ``*-trans.fif`` file produced during coregistration. If trans is None, an identity matrix is assumed. This is only needed when the source space is in head coordinates. %(verbose_meth)s Returns ------- fig : instance of mayavi.mlab.Figure The figure. """ from .viz import plot_alignment surfaces = list() bem = None if brain is None: brain = 'white' if any(ss['type'] == 'surf' for ss in self) else False if isinstance(brain, str): surfaces.append(brain) elif brain: surfaces.append('brain') if skull is None: skull = False if self.kind == 'surface' else True if isinstance(skull, str): surfaces.append(skull) elif skull is True: surfaces.append('outer_skull') elif skull is not False: # list if isinstance(skull[0], dict): # bem skull_map = {FIFF.FIFFV_BEM_SURF_ID_BRAIN: 'inner_skull', FIFF.FIFFV_BEM_SURF_ID_SKULL: 'outer_skull', FIFF.FIFFV_BEM_SURF_ID_HEAD: 'outer_skin'} for this_skull in skull: surfaces.append(skull_map[this_skull['id']]) bem = skull else: # list of str for surf in skull: surfaces.append(surf) if head: surfaces.append('head') if self[0]['coord_frame'] == FIFF.FIFFV_COORD_HEAD: coord_frame = 'head' if trans is None: raise ValueError('Source space is in head coordinates, but no ' 'head<->MRI transform was given. Please ' 'specify the full path to the appropriate ' '*-trans.fif file as the "trans" parameter.') else: coord_frame = 'mri' info = create_info(0, 1000., 'eeg') return plot_alignment( info, trans=trans, subject=self[0]['subject_his_id'], subjects_dir=subjects_dir, surfaces=surfaces, coord_frame=coord_frame, meg=(), eeg=False, dig=False, ecog=False, bem=bem, src=self ) def __repr__(self): # noqa: D105 ss_repr = [] for ss in self: ss_type = ss['type'] r = _src_kind_dict[ss_type] if ss_type == 'vol': if 'seg_name' in ss: r += " (%s)" % (ss['seg_name'],) else: r += ", shape=%s" % (ss['shape'],) elif ss_type == 'surf': r += (" (%s), n_vertices=%i" % (_get_hemi(ss)[0], ss['np'])) r += (', n_used=%i, coordinate_frame=%s' % (ss['nuse'], _coord_frame_name(int(ss['coord_frame'])))) ss_repr.append('<%s>' % r) return "<SourceSpaces: [%s]>" % ', '.join(ss_repr) @property def kind(self): """The kind of source space (surface, volume, discrete, mixed).""" ss_types = list({ss['type'] for ss in self}) if len(ss_types) != 1: return 'mixed' return _src_kind_dict[ss_types[0]] def __add__(self, other): """Combine source spaces.""" return SourceSpaces(list.__add__(self, other)) def copy(self): """Make a copy of the source spaces. Returns ------- src : instance of SourceSpaces The copied source spaces. """ src = deepcopy(self) return src def save(self, fname, overwrite=False): """Save the source spaces to a fif file. Parameters ---------- fname : str File to write. overwrite : bool If True, the destination file (if it exists) will be overwritten. If False (default), an error will be raised if the file exists. """ write_source_spaces(fname, self, overwrite) @verbose def export_volume(self, fname, include_surfaces=True, include_discrete=True, dest='mri', trans=None, mri_resolution=False, use_lut=True, verbose=None): """Export source spaces to nifti or mgz file. Parameters ---------- fname : str Name of nifti or mgz file to write. include_surfaces : bool If True, include surface source spaces. include_discrete : bool If True, include discrete source spaces. dest : 'mri' | 'surf' If 'mri' the volume is defined in the coordinate system of the original T1 image. If 'surf' the coordinate system of the FreeSurfer surface is used (Surface RAS). trans : dict, str, or None Either a transformation filename (usually made using mne_analyze) or an info dict (usually opened using read_trans()). If string, an ending of `.fif` or `.fif.gz` will be assumed to be in FIF format, any other ending will be assumed to be a text file with a 4x4 transformation matrix (like the `--trans` MNE-C option. Must be provided if source spaces are in head coordinates and include_surfaces and mri_resolution are True. mri_resolution : bool If True, the image is saved in MRI resolution (e.g. 256 x 256 x 256). use_lut : bool If True, assigns a numeric value to each source space that corresponds to a color on the freesurfer lookup table. %(verbose_meth)s Notes ----- This method requires nibabel. """ # import nibabel or raise error try: import nibabel as nib except ImportError: raise ImportError('This function requires nibabel.') # Check coordinate frames of each source space coord_frames = np.array([s['coord_frame'] for s in self]) # Raise error if trans is not provided when head coordinates are used # and mri_resolution and include_surfaces are true if (coord_frames == FIFF.FIFFV_COORD_HEAD).all(): coords = 'head' # all sources in head coordinates if mri_resolution and include_surfaces: if trans is None: raise ValueError('trans containing mri to head transform ' 'must be provided if mri_resolution and ' 'include_surfaces are true and surfaces ' 'are in head coordinates') elif trans is not None: logger.info('trans is not needed and will not be used unless ' 'include_surfaces and mri_resolution are True.') elif (coord_frames == FIFF.FIFFV_COORD_MRI).all(): coords = 'mri' # all sources in mri coordinates if trans is not None: logger.info('trans is not needed and will not be used unless ' 'sources are in head coordinates.') # Raise error if all sources are not in the same space, or sources are # not in mri or head coordinates else: raise ValueError('All sources must be in head coordinates or all ' 'sources must be in mri coordinates.') # use lookup table to assign values to source spaces logger.info('Reading FreeSurfer lookup table') # read the lookup table lut = _get_lut() # Setup a dictionary of source types src_types = dict(volume=[], surface=[], discrete=[]) # Populate dictionary of source types for src in self: # volume sources if src['type'] == 'vol': src_types['volume'].append(src) # surface sources elif src['type'] == 'surf': src_types['surface'].append(src) # discrete sources elif src['type'] == 'discrete': src_types['discrete'].append(src) # raise an error if dealing with source type other than volume # surface or discrete else: raise ValueError('Unrecognized source type: %s.' % src['type']) # Get shape, inuse array and interpolation matrix from volume sources inuse = 0 for ii, vs in enumerate(src_types['volume']): # read the lookup table value for segmented volume if 'seg_name' not in vs: raise ValueError('Volume sources should be segments, ' 'not the entire volume.') # find the color value for this volume id_ = _get_lut_id(lut, vs['seg_name'], use_lut) if ii == 0: # get the inuse array if mri_resolution: # read the mri file used to generate volumes aseg_data = nib.load(vs['mri_file']).get_data() # get the voxel space shape shape3d = (vs['mri_height'], vs['mri_depth'], vs['mri_width']) else: # get the volume source space shape # read the shape in reverse order # (otherwise results are scrambled) shape3d = vs['shape'][2::-1] if mri_resolution: # get the values for this volume use = id_ * (aseg_data == id_).astype(int).ravel('F') else: use = id_ * vs['inuse'] inuse += use # Raise error if there are no volume source spaces if np.array(inuse).ndim == 0: raise ValueError('Source spaces must contain at least one volume.') # create 3d grid in the MRI_VOXEL coordinate frame # len of inuse array should match shape regardless of mri_resolution assert len(inuse) == np.prod(shape3d) # setup the image in 3d space img = inuse.reshape(shape3d).T # include surface and/or discrete source spaces if include_surfaces or include_discrete: # setup affine transform for source spaces if mri_resolution: # get the MRI to MRI_VOXEL transform affine = invert_transform(vs['vox_mri_t']) else: # get the MRI to SOURCE (MRI_VOXEL) transform affine = invert_transform(vs['src_mri_t']) # modify affine if in head coordinates if coords == 'head': # read mri -> head transformation mri_head_t = _get_trans(trans)[0] # get the HEAD to MRI transform head_mri_t = invert_transform(mri_head_t) # combine transforms, from HEAD to MRI_VOXEL affine = combine_transforms(head_mri_t, affine, 'head', 'mri_voxel') # loop through the surface source spaces if include_surfaces: # get the surface names (assumes left, right order. may want # to add these names during source space generation surf_names = ['Left-Cerebral-Cortex', 'Right-Cerebral-Cortex'] for i, surf in enumerate(src_types['surface']): # convert vertex positions from their native space # (either HEAD or MRI) to MRI_VOXEL space srf_rr = apply_trans(affine['trans'], surf['rr']) # convert to numeric indices ix_orig, iy_orig, iz_orig = srf_rr.T.round().astype(int) # clip indices outside of volume space ix_clip = np.maximum(np.minimum(ix_orig, shape3d[2] - 1), 0) iy_clip = np.maximum(np.minimum(iy_orig, shape3d[1] - 1), 0) iz_clip = np.maximum(np.minimum(iz_orig, shape3d[0] - 1), 0) # compare original and clipped indices n_diff = np.array((ix_orig != ix_clip, iy_orig != iy_clip, iz_orig != iz_clip)).any(0).sum() # generate use warnings for clipping if n_diff > 0: warn('%s surface vertices lay outside of volume space.' ' Consider using a larger volume space.' % n_diff) # get surface id or use default value i = _get_lut_id(lut, surf_names[i], use_lut) # update image to include surface voxels img[ix_clip, iy_clip, iz_clip] = i # loop through discrete source spaces if include_discrete: for i, disc in enumerate(src_types['discrete']): # convert vertex positions from their native space # (either HEAD or MRI) to MRI_VOXEL space disc_rr = apply_trans(affine['trans'], disc['rr']) # convert to numeric indices ix_orig, iy_orig, iz_orig = disc_rr.T.astype(int) # clip indices outside of volume space ix_clip = np.maximum(np.minimum(ix_orig, shape3d[2] - 1), 0) iy_clip = np.maximum(np.minimum(iy_orig, shape3d[1] - 1), 0) iz_clip = np.maximum(np.minimum(iz_orig, shape3d[0] - 1), 0) # compare original and clipped indices n_diff = np.array((ix_orig != ix_clip, iy_orig != iy_clip, iz_orig != iz_clip)).any(0).sum() # generate use warnings for clipping if n_diff > 0: warn('%s discrete vertices lay outside of volume ' 'space. Consider using a larger volume space.' % n_diff) # set default value img[ix_clip, iy_clip, iz_clip] = 1 if use_lut: logger.info('Discrete sources do not have values on ' 'the lookup table. Defaulting to 1.') # calculate affine transform for image (MRI_VOXEL to RAS) if mri_resolution: # MRI_VOXEL to MRI transform transform = vs['vox_mri_t'].copy() else: # MRI_VOXEL to MRI transform # NOTE: 'src' indicates downsampled version of MRI_VOXEL transform = vs['src_mri_t'].copy() if dest == 'mri': # combine with MRI to RAS transform transform = combine_transforms(transform, vs['mri_ras_t'], transform['from'], vs['mri_ras_t']['to']) # now setup the affine for volume image affine = transform['trans'] # make sure affine converts from m to mm affine[:3] *= 1e3 # save volume data # setup image for file if fname.endswith(('.nii', '.nii.gz')): # save as nifit # setup the nifti header hdr = nib.Nifti1Header() hdr.set_xyzt_units('mm') # save the nifti image img = nib.Nifti1Image(img, affine, header=hdr) elif fname.endswith('.mgz'): # save as mgh # convert to float32 (float64 not currently supported) img = img.astype('float32') # save the mgh image img = nib.freesurfer.mghformat.MGHImage(img, affine) else: raise(ValueError('Unrecognized file extension')) # write image to file nib.save(img, fname) def _add_patch_info(s): """Patch information in a source space. Generate the patch information from the 'nearest' vector in a source space. For vertex in the source space it provides the list of neighboring vertices in the high resolution triangulation. Parameters ---------- s : dict The source space. """ nearest = s['nearest'] if nearest is None: s['pinfo'] = None s['patch_inds'] = None return logger.info(' Computing patch statistics...') indn = np.argsort(nearest) nearest_sorted = nearest[indn] steps = np.where(nearest_sorted[1:] != nearest_sorted[:-1])[0] + 1 starti = np.r_[[0], steps] stopi = np.r_[steps, [len(nearest)]] pinfo = list() for start, stop in zip(starti, stopi): pinfo.append(np.sort(indn[start:stop])) s['pinfo'] = pinfo # compute patch indices of the in-use source space vertices patch_verts = nearest_sorted[steps - 1] s['patch_inds'] = np.searchsorted(patch_verts, s['vertno']) logger.info(' Patch information added...') @verbose def _read_source_spaces_from_tree(fid, tree, patch_stats=False, verbose=None): """Read the source spaces from a FIF file. Parameters ---------- fid : file descriptor An open file descriptor. tree : dict The FIF tree structure if source is a file id. patch_stats : bool, optional (default False) Calculate and add cortical patch statistics to the surfaces. %(verbose)s Returns ------- src : SourceSpaces The source spaces. """ # Find all source spaces spaces = dir_tree_find(tree, FIFF.FIFFB_MNE_SOURCE_SPACE) if len(spaces) == 0: raise ValueError('No source spaces found') src = list() for s in spaces: logger.info(' Reading a source space...') this = _read_one_source_space(fid, s) logger.info(' [done]') if patch_stats: _complete_source_space_info(this) src.append(this) logger.info(' %d source spaces read' % len(spaces)) return SourceSpaces(src) @verbose def read_source_spaces(fname, patch_stats=False, verbose=None): """Read the source spaces from a FIF file. Parameters ---------- fname : str The name of the file, which should end with -src.fif or -src.fif.gz. patch_stats : bool, optional (default False) Calculate and add cortical patch statistics to the surfaces. %(verbose)s Returns ------- src : SourceSpaces The source spaces. See Also -------- write_source_spaces, setup_source_space, setup_volume_source_space """ # be more permissive on read than write (fwd/inv can contain src) check_fname(fname, 'source space', ('-src.fif', '-src.fif.gz', '_src.fif', '_src.fif.gz', '-fwd.fif', '-fwd.fif.gz', '_fwd.fif', '_fwd.fif.gz', '-inv.fif', '-inv.fif.gz', '_inv.fif', '_inv.fif.gz')) ff, tree, _ = fiff_open(fname) with ff as fid: src = _read_source_spaces_from_tree(fid, tree, patch_stats=patch_stats, verbose=verbose) src.info['fname'] = fname node = dir_tree_find(tree, FIFF.FIFFB_MNE_ENV) if node: node = node[0] for p in range(node['nent']): kind = node['directory'][p].kind pos = node['directory'][p].pos tag = read_tag(fid, pos) if kind == FIFF.FIFF_MNE_ENV_WORKING_DIR: src.info['working_dir'] = tag.data elif kind == FIFF.FIFF_MNE_ENV_COMMAND_LINE: src.info['command_line'] = tag.data return src @verbose def _read_one_source_space(fid, this, verbose=None): """Read one source space.""" FIFF_BEM_SURF_NTRI = 3104 FIFF_BEM_SURF_TRIANGLES = 3106 res = dict() tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_ID) if tag is None: res['id'] = int(FIFF.FIFFV_MNE_SURF_UNKNOWN) else: res['id'] = int(tag.data) tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_TYPE) if tag is None: raise ValueError('Unknown source space type') else: src_type = int(tag.data) if src_type == FIFF.FIFFV_MNE_SPACE_SURFACE: res['type'] = 'surf' elif src_type == FIFF.FIFFV_MNE_SPACE_VOLUME: res['type'] = 'vol' elif src_type == FIFF.FIFFV_MNE_SPACE_DISCRETE: res['type'] = 'discrete' else: raise ValueError('Unknown source space type (%d)' % src_type) if res['type'] == 'vol': tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_VOXEL_DIMS) if tag is not None: res['shape'] = tuple(tag.data) tag = find_tag(fid, this, FIFF.FIFF_COORD_TRANS) if tag is not None: res['src_mri_t'] = tag.data parent_mri = dir_tree_find(this, FIFF.FIFFB_MNE_PARENT_MRI_FILE) if len(parent_mri) == 0: # MNE 2.7.3 (and earlier) didn't store necessary information # about volume coordinate translations. Although there is a # FFIF_COORD_TRANS in the higher level of the FIFF file, this # doesn't contain all the info we need. Safer to return an # error unless a user really wants us to add backward compat. raise ValueError('Can not find parent MRI location. The volume ' 'source space may have been made with an MNE ' 'version that is too old (<= 2.7.3). Consider ' 'updating and regenerating the inverse.') mri = parent_mri[0] for d in mri['directory']: if d.kind == FIFF.FIFF_COORD_TRANS: tag = read_tag(fid, d.pos) trans = tag.data if trans['from'] == FIFF.FIFFV_MNE_COORD_MRI_VOXEL: res['vox_mri_t'] = tag.data if trans['to'] == FIFF.FIFFV_MNE_COORD_RAS: res['mri_ras_t'] = tag.data tag = find_tag(fid, mri, FIFF.FIFF_MNE_SOURCE_SPACE_INTERPOLATOR) if tag is not None: res['interpolator'] = tag.data else: logger.info("Interpolation matrix for MRI not found.") tag = find_tag(fid, mri, FIFF.FIFF_MNE_SOURCE_SPACE_MRI_FILE) if tag is not None: res['mri_file'] = tag.data tag = find_tag(fid, mri, FIFF.FIFF_MRI_WIDTH) if tag is not None: res['mri_width'] = int(tag.data) tag = find_tag(fid, mri, FIFF.FIFF_MRI_HEIGHT) if tag is not None: res['mri_height'] = int(tag.data) tag = find_tag(fid, mri, FIFF.FIFF_MRI_DEPTH) if tag is not None: res['mri_depth'] = int(tag.data) tag = find_tag(fid, mri, FIFF.FIFF_MNE_FILE_NAME) if tag is not None: res['mri_volume_name'] = tag.data tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NNEIGHBORS) if tag is not None: nneighbors = tag.data tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NEIGHBORS) offset = 0 neighbors = [] for n in nneighbors: neighbors.append(tag.data[offset:offset + n]) offset += n res['neighbor_vert'] = neighbors tag = find_tag(fid, this, FIFF.FIFF_COMMENT) if tag is not None: res['seg_name'] = tag.data tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NPOINTS) if tag is None: raise ValueError('Number of vertices not found') res['np'] = int(tag.data) tag = find_tag(fid, this, FIFF_BEM_SURF_NTRI) if tag is None: tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NTRI) if tag is None: res['ntri'] = 0 else: res['ntri'] = int(tag.data) else: res['ntri'] = tag.data tag = find_tag(fid, this, FIFF.FIFF_MNE_COORD_FRAME) if tag is None: raise ValueError('Coordinate frame information not found') res['coord_frame'] = tag.data[0] # Vertices, normals, and triangles tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_POINTS) if tag is None: raise ValueError('Vertex data not found') res['rr'] = tag.data.astype(np.float) # double precision for mayavi if res['rr'].shape[0] != res['np']: raise ValueError('Vertex information is incorrect') tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NORMALS) if tag is None: raise ValueError('Vertex normals not found') res['nn'] = tag.data.copy() if res['nn'].shape[0] != res['np']: raise ValueError('Vertex normal information is incorrect') if res['ntri'] > 0: tag = find_tag(fid, this, FIFF_BEM_SURF_TRIANGLES) if tag is None: tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_TRIANGLES) if tag is None: raise ValueError('Triangulation not found') else: res['tris'] = tag.data - 1 # index start at 0 in Python else: res['tris'] = tag.data - 1 # index start at 0 in Python if res['tris'].shape[0] != res['ntri']: raise ValueError('Triangulation information is incorrect') else: res['tris'] = None # Which vertices are active tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NUSE) if tag is None: res['nuse'] = 0 res['inuse'] = np.zeros(res['nuse'], dtype=np.int) res['vertno'] = None else: res['nuse'] = int(tag.data) tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_SELECTION) if tag is None: raise ValueError('Source selection information missing') res['inuse'] = tag.data.astype(np.int).T if len(res['inuse']) != res['np']: raise ValueError('Incorrect number of entries in source space ' 'selection') res['vertno'] = np.where(res['inuse'])[0] # Use triangulation tag1 = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NUSE_TRI) tag2 = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_USE_TRIANGLES) if tag1 is None or tag2 is None: res['nuse_tri'] = 0 res['use_tris'] = None else: res['nuse_tri'] = tag1.data res['use_tris'] = tag2.data - 1 # index start at 0 in Python # Patch-related information tag1 = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NEAREST) tag2 = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NEAREST_DIST) if tag1 is None or tag2 is None: res['nearest'] = None res['nearest_dist'] = None else: res['nearest'] = tag1.data res['nearest_dist'] = tag2.data.T _add_patch_info(res) # Distances tag1 = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_DIST) tag2 = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_DIST_LIMIT) if tag1 is None or tag2 is None: res['dist'] = None res['dist_limit'] = None else: res['dist'] = tag1.data res['dist_limit'] = tag2.data # Add the upper triangle res['dist'] = res['dist'] + res['dist'].T if (res['dist'] is not None): logger.info(' Distance information added...') tag = find_tag(fid, this, FIFF.FIFF_SUBJ_HIS_ID) if tag is None: res['subject_his_id'] = None else: res['subject_his_id'] = tag.data return res @verbose def _complete_source_space_info(this, verbose=None): """Add more info on surface.""" # Main triangulation logger.info(' Completing triangulation info...') this['tri_area'] = np.zeros(this['ntri']) r1 = this['rr'][this['tris'][:, 0], :] r2 = this['rr'][this['tris'][:, 1], :] r3 = this['rr'][this['tris'][:, 2], :] this['tri_cent'] = (r1 + r2 + r3) / 3.0 this['tri_nn'] = fast_cross_3d((r2 - r1), (r3 - r1)) this['tri_area'] = _normalize_vectors(this['tri_nn']) / 2.0 logger.info('[done]') # Selected triangles logger.info(' Completing selection triangulation info...') if this['nuse_tri'] > 0: r1 = this['rr'][this['use_tris'][:, 0], :] r2 = this['rr'][this['use_tris'][:, 1], :] r3 = this['rr'][this['use_tris'][:, 2], :] this['use_tri_cent'] = (r1 + r2 + r3) / 3.0 this['use_tri_nn'] = fast_cross_3d((r2 - r1), (r3 - r1)) this['use_tri_area'] = np.linalg.norm(this['use_tri_nn'], axis=1) / 2. logger.info('[done]') def find_source_space_hemi(src): """Return the hemisphere id for a source space. Parameters ---------- src : dict The source space to investigate Returns ------- hemi : int Deduced hemisphere id """ xave = src['rr'][:, 0].sum() if xave < 0: hemi = int(FIFF.FIFFV_MNE_SURF_LEFT_HEMI) else: hemi = int(FIFF.FIFFV_MNE_SURF_RIGHT_HEMI) return hemi def label_src_vertno_sel(label, src): """Find vertex numbers and indices from label. Parameters ---------- label : Label Source space label src : dict Source space Returns ------- vertices : list of length 2 Vertex numbers for lh and rh src_sel : array of int (len(idx) = len(vertices[0]) + len(vertices[1])) Indices of the selected vertices in sourse space """ if src[0]['type'] != 'surf': return Exception('Labels are only supported with surface source ' 'spaces') vertno = [src[0]['vertno'], src[1]['vertno']] if label.hemi == 'lh': vertno_sel = np.intersect1d(vertno[0], label.vertices) src_sel = np.searchsorted(vertno[0], vertno_sel) vertno[0] = vertno_sel vertno[1] = np.array([], int) elif label.hemi == 'rh': vertno_sel = np.intersect1d(vertno[1], label.vertices) src_sel = np.searchsorted(vertno[1], vertno_sel) + len(vertno[0]) vertno[0] = np.array([], int) vertno[1] = vertno_sel elif label.hemi == 'both': vertno_sel_lh = np.intersect1d(vertno[0], label.lh.vertices) src_sel_lh = np.searchsorted(vertno[0], vertno_sel_lh) vertno_sel_rh = np.intersect1d(vertno[1], label.rh.vertices) src_sel_rh = np.searchsorted(vertno[1], vertno_sel_rh) + len(vertno[0]) src_sel = np.hstack((src_sel_lh, src_sel_rh)) vertno = [vertno_sel_lh, vertno_sel_rh] else: raise Exception("Unknown hemisphere type") return vertno, src_sel def _get_vertno(src): return [s['vertno'] for s in src] ############################################################################### # Write routines @verbose def _write_source_spaces_to_fid(fid, src, verbose=None): """Write the source spaces to a FIF file. Parameters ---------- fid : file descriptor An open file descriptor. src : list The list of source spaces. %(verbose)s """ for s in src: logger.info(' Write a source space...') start_block(fid, FIFF.FIFFB_MNE_SOURCE_SPACE) _write_one_source_space(fid, s, verbose) end_block(fid, FIFF.FIFFB_MNE_SOURCE_SPACE) logger.info(' [done]') logger.info(' %d source spaces written' % len(src)) @verbose def write_source_spaces(fname, src, overwrite=False, verbose=None): """Write source spaces to a file. Parameters ---------- fname : str The name of the file, which should end with -src.fif or -src.fif.gz. src : SourceSpaces The source spaces (as returned by read_source_spaces). overwrite : bool If True, the destination file (if it exists) will be overwritten. If False (default), an error will be raised if the file exists. %(verbose)s See Also -------- read_source_spaces """ check_fname(fname, 'source space', ('-src.fif', '-src.fif.gz', '_src.fif', '_src.fif.gz')) _check_fname(fname, overwrite=overwrite) fid = start_file(fname) start_block(fid, FIFF.FIFFB_MNE) if src.info: start_block(fid, FIFF.FIFFB_MNE_ENV) write_id(fid, FIFF.FIFF_BLOCK_ID) data = src.info.get('working_dir', None) if data: write_string(fid, FIFF.FIFF_MNE_ENV_WORKING_DIR, data) data = src.info.get('command_line', None) if data: write_string(fid, FIFF.FIFF_MNE_ENV_COMMAND_LINE, data) end_block(fid, FIFF.FIFFB_MNE_ENV) _write_source_spaces_to_fid(fid, src, verbose) end_block(fid, FIFF.FIFFB_MNE) end_file(fid) def _write_one_source_space(fid, this, verbose=None): """Write one source space.""" if this['type'] == 'surf': src_type = FIFF.FIFFV_MNE_SPACE_SURFACE elif this['type'] == 'vol': src_type = FIFF.FIFFV_MNE_SPACE_VOLUME elif this['type'] == 'discrete': src_type = FIFF.FIFFV_MNE_SPACE_DISCRETE else: raise ValueError('Unknown source space type (%s)' % this['type']) write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_TYPE, src_type) if this['id'] >= 0: write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_ID, this['id']) data = this.get('subject_his_id', None) if data: write_string(fid, FIFF.FIFF_SUBJ_HIS_ID, data) write_int(fid, FIFF.FIFF_MNE_COORD_FRAME, this['coord_frame']) write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NPOINTS, this['np']) write_float_matrix(fid, FIFF.FIFF_MNE_SOURCE_SPACE_POINTS, this['rr']) write_float_matrix(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NORMALS, this['nn']) # Which vertices are active write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_SELECTION, this['inuse']) write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NUSE, this['nuse']) if this['ntri'] > 0: write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NTRI, this['ntri']) write_int_matrix(fid, FIFF.FIFF_MNE_SOURCE_SPACE_TRIANGLES, this['tris'] + 1) if this['type'] != 'vol' and this['use_tris'] is not None: # Use triangulation write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NUSE_TRI, this['nuse_tri']) write_int_matrix(fid, FIFF.FIFF_MNE_SOURCE_SPACE_USE_TRIANGLES, this['use_tris'] + 1) if this['type'] == 'vol': neighbor_vert = this.get('neighbor_vert', None) if neighbor_vert is not None: nneighbors = np.array([len(n) for n in neighbor_vert]) neighbors = np.concatenate(neighbor_vert) write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NNEIGHBORS, nneighbors) write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NEIGHBORS, neighbors) write_coord_trans(fid, this['src_mri_t']) write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_VOXEL_DIMS, this['shape']) start_block(fid, FIFF.FIFFB_MNE_PARENT_MRI_FILE) write_coord_trans(fid, this['mri_ras_t']) write_coord_trans(fid, this['vox_mri_t']) mri_volume_name = this.get('mri_volume_name', None) if mri_volume_name is not None: write_string(fid, FIFF.FIFF_MNE_FILE_NAME, mri_volume_name) write_float_sparse_rcs(fid, FIFF.FIFF_MNE_SOURCE_SPACE_INTERPOLATOR, this['interpolator']) if 'mri_file' in this and this['mri_file'] is not None: write_string(fid, FIFF.FIFF_MNE_SOURCE_SPACE_MRI_FILE, this['mri_file']) write_int(fid, FIFF.FIFF_MRI_WIDTH, this['mri_width']) write_int(fid, FIFF.FIFF_MRI_HEIGHT, this['mri_height']) write_int(fid, FIFF.FIFF_MRI_DEPTH, this['mri_depth']) end_block(fid, FIFF.FIFFB_MNE_PARENT_MRI_FILE) # Patch-related information if this['nearest'] is not None: write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NEAREST, this['nearest']) write_float_matrix(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NEAREST_DIST, this['nearest_dist']) # Distances if this['dist'] is not None: # Save only upper triangular portion of the matrix dists = this['dist'].copy() dists = sparse.triu(dists, format=dists.format) write_float_sparse_rcs(fid, FIFF.FIFF_MNE_SOURCE_SPACE_DIST, dists) write_float_matrix(fid, FIFF.FIFF_MNE_SOURCE_SPACE_DIST_LIMIT, this['dist_limit']) # Segmentation data if this['type'] == 'vol' and ('seg_name' in this): # Save the name of the segment write_string(fid, FIFF.FIFF_COMMENT, this['seg_name']) ############################################################################## # Head to MRI volume conversion @verbose def head_to_mri(pos, subject, mri_head_t, subjects_dir=None, verbose=None): """Convert pos from head coordinate system to MRI ones. This function converts to MRI RAS coordinates and not to surface RAS. Parameters ---------- pos : array, shape (n_pos, 3) The coordinates (in m) in head coordinate system subject : string Name of the subject. mri_head_t: instance of Transform MRI<->Head coordinate transformation subjects_dir : string, or None Path to SUBJECTS_DIR if it is not set in the environment. %(verbose)s Returns ------- coordinates : array, shape (n_pos, 3) The MNI coordinates (in mm) of pos Notes ----- This function requires either nibabel (in Python) or Freesurfer (with utility "mri_info") to be correctly installed. """ import nibabel as nib subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) t1_fname = op.join(subjects_dir, subject, 'mri', 'T1.mgz') head_mri_t = _ensure_trans(mri_head_t, 'head', 'mri') mri_pos = apply_trans(head_mri_t, pos) * 1e3 t1 = nib.load(t1_fname) vox2ras_tkr = t1.header.get_vox2ras_tkr() ras2vox_tkr = linalg.inv(vox2ras_tkr) vox2ras = t1.header.get_vox2ras() mri_pos = apply_trans(ras2vox_tkr, mri_pos) # in vox mri_pos = apply_trans(vox2ras, mri_pos) # in RAS return mri_pos ############################################################################## # Surface to MNI conversion @verbose def vertex_to_mni(vertices, hemis, subject, subjects_dir=None, mode=None, verbose=None): """Convert the array of vertices for a hemisphere to MNI coordinates. Parameters ---------- vertices : int, or list of int Vertex number(s) to convert hemis : int, or list of int Hemisphere(s) the vertices belong to subject : string Name of the subject to load surfaces from. subjects_dir : string, or None Path to SUBJECTS_DIR if it is not set in the environment. mode : string | None Either 'nibabel' or 'freesurfer' for the software to use to obtain the transforms. If None, 'nibabel' is tried first, falling back to 'freesurfer' if it fails. Results should be equivalent with either option, but nibabel may be quicker (and more pythonic). %(verbose)s Returns ------- coordinates : array, shape (n_vertices, 3) The MNI coordinates (in mm) of the vertices Notes ----- This function requires either nibabel (in Python) or Freesurfer (with utility "mri_info") to be correctly installed. """ if not has_freesurfer() and not has_nibabel(): raise RuntimeError('NiBabel (Python) or Freesurfer (Unix) must be ' 'correctly installed and accessible from Python') if not isinstance(vertices, list) and not isinstance(vertices, np.ndarray): vertices = [vertices] if not isinstance(hemis, list) and not isinstance(hemis, np.ndarray): hemis = [hemis] * len(vertices) if not len(hemis) == len(vertices): raise ValueError('hemi and vertices must match in length') subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) surfs = [op.join(subjects_dir, subject, 'surf', '%s.white' % h) for h in ['lh', 'rh']] # read surface locations in MRI space rr = [read_surface(s)[0] for s in surfs] # take point locations in MRI space and convert to MNI coordinates xfm = _read_talxfm(subject, subjects_dir, mode) data = np.array([rr[h][v, :] for h, v in zip(hemis, vertices)]) return apply_trans(xfm['trans'], data) ############################################################################## # Volume to MNI conversion @verbose def head_to_mni(pos, subject, mri_head_t, subjects_dir=None, verbose=None): """Convert pos from head coordinate system to MNI ones. Parameters ---------- pos : array, shape (n_pos, 3) The coordinates (in m) in head coordinate system subject : string Name of the subject. mri_head_t: instance of Transform MRI<->Head coordinate transformation subjects_dir : string, or None Path to SUBJECTS_DIR if it is not set in the environment. %(verbose)s Returns ------- coordinates : array, shape (n_pos, 3) The MNI coordinates (in mm) of pos Notes ----- This function requires either nibabel (in Python) or Freesurfer (with utility "mri_info") to be correctly installed. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) # before we go from head to MRI (surface RAS) head_mri_t = _ensure_trans(mri_head_t, 'head', 'mri') coo_MRI_RAS = apply_trans(head_mri_t, pos) # convert to MNI coordinates xfm = _read_talxfm(subject, subjects_dir) return apply_trans(xfm['trans'], coo_MRI_RAS * 1000) @verbose def _read_talxfm(subject, subjects_dir, mode=None, verbose=None): """Read MNI transform from FreeSurfer talairach.xfm file. Adapted from freesurfer m-files. Altered to deal with Norig and Torig correctly. """ if mode is not None and mode not in ['nibabel', 'freesurfer']: raise ValueError('mode must be "nibabel" or "freesurfer"') fname = op.join(subjects_dir, subject, 'mri', 'transforms', 'talairach.xfm') # Setup the RAS to MNI transform ras_mni_t = Transform('ras', 'mni_tal', _read_fs_xfm(fname)[0]) # We want to get from Freesurfer surface RAS ('mri') to MNI ('mni_tal'). # This file only gives us RAS (non-zero origin) ('ras') to MNI ('mni_tal'). # Se we need to get the ras->mri transform from the MRI headers. # To do this, we get Norig and Torig # (i.e. vox_ras_t and vox_mri_t, respectively) path = op.join(subjects_dir, subject, 'mri', 'orig.mgz') if not op.isfile(path): path = op.join(subjects_dir, subject, 'mri', 'T1.mgz') if not op.isfile(path): raise IOError('mri not found: %s' % path) if has_nibabel(): use_nibabel = True else: use_nibabel = False if mode == 'nibabel': raise ImportError('Tried to import nibabel but failed, try using ' 'mode=None or mode=Freesurfer') # note that if mode == None, then we default to using nibabel if use_nibabel is True and mode == 'freesurfer': use_nibabel = False if use_nibabel: hdr = _get_mri_header(path) n_orig = hdr.get_vox2ras() t_orig = hdr.get_vox2ras_tkr() else: nt_orig = list() for conv in ['--vox2ras', '--vox2ras-tkr']: stdout, stderr = run_subprocess(['mri_info', conv, path]) stdout = np.fromstring(stdout, sep=' ').astype(float) if not stdout.size == 16: raise ValueError('Could not parse Freesurfer mri_info output') nt_orig.append(stdout.reshape(4, 4)) n_orig, t_orig = nt_orig # extract the MRI_VOXEL to RAS (non-zero origin) transform vox_ras_t = Transform('mri_voxel', 'ras', n_orig) # extract the MRI_VOXEL to MRI transform vox_mri_t = Transform('mri_voxel', 'mri', t_orig) # construct the MRI to RAS (non-zero origin) transform mri_ras_t = combine_transforms( invert_transform(vox_mri_t), vox_ras_t, 'mri', 'ras') # construct the MRI to MNI transform mri_mni_t = combine_transforms(mri_ras_t, ras_mni_t, 'mri', 'mni_tal') return mri_mni_t ############################################################################### # Creation and decimation @verbose def _check_spacing(spacing, verbose=None): """Check spacing parameter.""" # check to make sure our parameters are good, parse 'spacing' types = ('a string with values "ico#", "oct#", "all", or an int >= 2') space_err = '"spacing" must be ' + types if isinstance(spacing, str): if spacing == 'all': stype = 'all' sval = '' elif isinstance(spacing, str) and spacing[:3] in ('ico', 'oct'): stype = spacing[:3] sval = spacing[3:] try: sval = int(sval) except Exception: raise ValueError('ico and oct numbers must be integers, got %r' % (sval,)) else: raise ValueError(space_err) else: stype = 'spacing' sval = _ensure_int(spacing, 'spacing', types) if sval < 2: raise ValueError('spacing must be >= 2, got %d' % (sval,)) if stype == 'all': logger.info('Include all vertices') ico_surf = None src_type_str = 'all' else: src_type_str = '%s = %s' % (stype, sval) if stype == 'ico': logger.info('Icosahedron subdivision grade %s' % sval) ico_surf = _get_ico_surface(sval) elif stype == 'oct': logger.info('Octahedron subdivision grade %s' % sval) ico_surf = _tessellate_sphere_surf(sval) else: assert stype == 'spacing' logger.info('Approximate spacing %s mm' % sval) ico_surf = sval return stype, sval, ico_surf, src_type_str @verbose def setup_source_space(subject, spacing='oct6', surface='white', subjects_dir=None, add_dist=True, n_jobs=1, verbose=None): """Set up bilateral hemisphere surface-based source space with subsampling. Parameters ---------- subject : str Subject to process. spacing : str The spacing to use. Can be ``'ico#'`` for a recursively subdivided icosahedron, ``'oct#'`` for a recursively subdivided octahedron, ``'all'`` for all points, or an integer to use appoximate distance-based spacing (in mm). .. versionchanged:: 0.18 Support for integers for distance-based spacing. surface : str The surface to use. subjects_dir : string, or None Path to SUBJECTS_DIR if it is not set in the environment. add_dist : bool Add distance and patch information to the source space. This takes some time so precomputing it is recommended. n_jobs : int Number of jobs to run in parallel. Will use at most 2 jobs (one for each hemisphere). %(verbose)s Returns ------- src : SourceSpaces The source space for each hemisphere. See Also -------- setup_volume_source_space """ cmd = ('setup_source_space(%s, spacing=%s, surface=%s, ' 'subjects_dir=%s, add_dist=%s, verbose=%s)' % (subject, spacing, surface, subjects_dir, add_dist, verbose)) subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) surfs = [op.join(subjects_dir, subject, 'surf', hemi + surface) for hemi in ['lh.', 'rh.']] for surf, hemi in zip(surfs, ['LH', 'RH']): if surf is not None and not op.isfile(surf): raise IOError('Could not find the %s surface %s' % (hemi, surf)) logger.info('Setting up the source space with the following parameters:\n') logger.info('SUBJECTS_DIR = %s' % subjects_dir) logger.info('Subject = %s' % subject) logger.info('Surface = %s' % surface) stype, sval, ico_surf, src_type_str = _check_spacing(spacing) logger.info('') del spacing logger.info('>>> 1. Creating the source space...\n') # mne_make_source_space ... actually make the source spaces src = [] # pre-load ico/oct surf (once) for speed, if necessary if stype not in ('spacing', 'all'): logger.info('Doing the %shedral vertex picking...' % (dict(ico='icosa', oct='octa')[stype],)) for hemi, surf in zip(['lh', 'rh'], surfs): logger.info('Loading %s...' % surf) # Setup the surface spacing in the MRI coord frame if stype != 'all': logger.info('Mapping %s %s -> %s (%d) ...' % (hemi, subject, stype, sval)) s = _create_surf_spacing(surf, hemi, subject, stype, ico_surf, subjects_dir) logger.info('loaded %s %d/%d selected to source space (%s)' % (op.split(surf)[1], s['nuse'], s['np'], src_type_str)) src.append(s) logger.info('') # newline after both subject types are run # Fill in source space info hemi_ids = [FIFF.FIFFV_MNE_SURF_LEFT_HEMI, FIFF.FIFFV_MNE_SURF_RIGHT_HEMI] for s, s_id in zip(src, hemi_ids): # Add missing fields s.update(dict(dist=None, dist_limit=None, nearest=None, type='surf', nearest_dist=None, pinfo=None, patch_inds=None, id=s_id, coord_frame=FIFF.FIFFV_COORD_MRI)) s['rr'] /= 1000.0 del s['tri_area'] del s['tri_cent'] del s['tri_nn'] del s['neighbor_tri'] # upconvert to object format from lists src = SourceSpaces(src, dict(working_dir=os.getcwd(), command_line=cmd)) if add_dist: add_source_space_distances(src, n_jobs=n_jobs, verbose=verbose) # write out if requested, then return the data logger.info('You are now one step closer to computing the gain matrix') return src @verbose def setup_volume_source_space(subject=None, pos=5.0, mri=None, sphere=(0.0, 0.0, 0.0, 90.0), bem=None, surface=None, mindist=5.0, exclude=0.0, subjects_dir=None, volume_label=None, add_interpolator=True, verbose=None): """Set up a volume source space with grid spacing or discrete source space. Parameters ---------- subject : str | None Subject to process. If None, the path to the MRI volume must be absolute to get a volume source space. If a subject name is provided the T1.mgz file will be found automatically. Defaults to None. pos : float | dict Positions to use for sources. If float, a grid will be constructed with the spacing given by `pos` in mm, generating a volume source space. If dict, pos['rr'] and pos['nn'] will be used as the source space locations (in meters) and normals, respectively, creating a discrete source space. NOTE: For a discrete source space (`pos` is a dict), `mri` must be None. mri : str | None The filename of an MRI volume (mgh or mgz) to create the interpolation matrix over. Source estimates obtained in the volume source space can then be morphed onto the MRI volume using this interpolator. If pos is a dict, this cannot be None. If subject name is provided, `pos` is a float or `volume_label` are not provided then the `mri` parameter will default to 'T1.mgz' else it will stay None. sphere : ndarray, shape (4,) | ConductorModel Define spherical source space bounds using origin and radius given by (ox, oy, oz, rad) in mm. Only used if ``bem`` and ``surface`` are both None. Can also be a spherical ConductorModel, which will use the origin and radius. bem : str | None | ConductorModel Define source space bounds using a BEM file (specifically the inner skull surface) or a ConductorModel for a 1-layer of 3-layers BEM. surface : str | dict | None Define source space bounds using a FreeSurfer surface file. Can also be a dictionary with entries `'rr'` and `'tris'`, such as those returned by :func:`mne.read_surface`. mindist : float Exclude points closer than this distance (mm) to the bounding surface. exclude : float Exclude points closer than this distance (mm) from the center of mass of the bounding surface. subjects_dir : string, or None Path to SUBJECTS_DIR if it is not set in the environment. volume_label : str | list | None Region of interest corresponding with freesurfer lookup table. add_interpolator : bool If True and ``mri`` is not None, then an interpolation matrix will be produced. %(verbose)s Returns ------- src : SourceSpaces A :class:`SourceSpaces` object containing one source space for each entry of ``volume_labels``, or a single source space if ``volume_labels`` was not specified. See Also -------- setup_source_space Notes ----- Volume source spaces are related to an MRI image such as T1 and allow to visualize source estimates overlaid on MRIs and to morph estimates to a template brain for group analysis. Discrete source spaces don't allow this. If you provide a subject name the T1 MRI will be used by default. When you work with a source space formed from a grid you need to specify the domain in which the grid will be defined. There are three ways of specifying this: (i) sphere, (ii) bem model, and (iii) surface. The default behavior is to use sphere model (``sphere=(0.0, 0.0, 0.0, 90.0)``) if ``bem`` or ``surface`` is not ``None`` then ``sphere`` is ignored. If you're going to use a BEM conductor model for forward model it is recommended to pass it here. To create a discrete source space, `pos` must be a dict, 'mri' must be None, and 'volume_label' must be None. To create a whole brain volume source space, `pos` must be a float and 'mri' must be provided. To create a volume source space from label, 'pos' must be a float, 'volume_label' must be provided, and 'mri' must refer to a .mgh or .mgz file with values corresponding to the freesurfer lookup-table (typically aseg.mgz). """ subjects_dir = get_subjects_dir(subjects_dir) if bem is not None and surface is not None: raise ValueError('Only one of "bem" and "surface" should be ' 'specified') if (mri is None and subject is not None and volume_label is None and isinstance(pos, (float, int))): mri = 'T1.mgz' if volume_label is not None and mri == 'T1.mgz': raise RuntimeError('Cannot use T1.mgz with some volume_label.') if mri is not None: if not op.isfile(mri): if subject is None: raise IOError('mri file "%s" not found' % mri) mri = op.join(subjects_dir, subject, 'mri', mri) if not op.isfile(mri): raise IOError('mri file "%s" not found' % mri) if isinstance(pos, dict): raise ValueError('Cannot create interpolation matrix for ' 'discrete source space, mri must be None if ' 'pos is a dict') if volume_label is not None: if mri is None: raise RuntimeError('"mri" must be provided if "volume_label" is ' 'not None') if not isinstance(volume_label, list): volume_label = [volume_label] # Check that volume label is found in .mgz file volume_labels = get_volume_labels_from_aseg(mri) for label in volume_label: if label not in volume_labels: raise ValueError('Volume %s not found in file %s. Double ' 'check freesurfer lookup table.' % (label, mri)) if isinstance(sphere, ConductorModel): if not sphere['is_sphere'] or len(sphere['layers']) == 0: raise ValueError('sphere, if a ConductorModel, must be spherical ' 'with multiple layers, not a BEM or single-layer ' 'sphere (got %s)' % (sphere,)) sphere = tuple(1000 * sphere['r0']) + (1000 * sphere['layers'][0]['rad'],) sphere = np.asarray(sphere, dtype=float) if sphere.size != 4: raise ValueError('"sphere" must be array_like with 4 elements, got: %s' % (sphere,)) # triage bounding argument if bem is not None: logger.info('BEM : %s', bem) elif surface is not None: if isinstance(surface, dict): if not all(key in surface for key in ['rr', 'tris']): raise KeyError('surface, if dict, must have entries "rr" ' 'and "tris"') # let's make sure we have geom info complete_surface_info(surface, copy=False, verbose=False) surf_extra = 'dict()' elif isinstance(surface, str): if not op.isfile(surface): raise IOError('surface file "%s" not found' % surface) surf_extra = surface logger.info('Boundary surface file : %s', surf_extra) else: logger.info('Sphere : origin at (%.1f %.1f %.1f) mm' % (sphere[0], sphere[1], sphere[2])) logger.info(' radius : %.1f mm' % sphere[3]) # triage pos argument if isinstance(pos, dict): if not all(key in pos for key in ['rr', 'nn']): raise KeyError('pos, if dict, must contain "rr" and "nn"') pos_extra = 'dict()' else: # pos should be float-like try: pos = float(pos) except (TypeError, ValueError): raise ValueError('pos must be a dict, or something that can be ' 'cast to float()') if not isinstance(pos, float): logger.info('Source location file : %s', pos_extra) logger.info('Assuming input in millimeters') logger.info('Assuming input in MRI coordinates') if isinstance(pos, float): logger.info('grid : %.1f mm' % pos) logger.info('mindist : %.1f mm' % mindist) pos /= 1000.0 # convert pos from m to mm if exclude > 0.0: logger.info('Exclude : %.1f mm' % exclude) if mri is not None: logger.info('MRI volume : %s' % mri) exclude /= 1000.0 # convert exclude from m to mm logger.info('') # Explicit list of points if not isinstance(pos, float): # Make the grid of sources sp = _make_discrete_source_space(pos) else: # Load the brain surface as a template if isinstance(bem, str): # read bem surface in the MRI coordinate frame surf = read_bem_surfaces(bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN, verbose=False) logger.info('Loaded inner skull from %s (%d nodes)' % (bem, surf['np'])) elif bem is not None and bem.get('is_sphere') is False: # read bem surface in the MRI coordinate frame surf = bem['surfs'][0] assert surf['id'] == FIFF.FIFFV_BEM_SURF_ID_BRAIN logger.info('Taking inner skull from %s' % bem) elif surface is not None: if isinstance(surface, str): # read the surface in the MRI coordinate frame surf = read_surface(surface, return_dict=True)[-1] else: surf = surface logger.info('Loaded bounding surface from %s (%d nodes)' % (surface, surf['np'])) surf = deepcopy(surf) surf['rr'] *= 1e-3 # must be converted to meters else: # Load an icosahedron and use that as the surface logger.info('Setting up the sphere...') surf = dict(R=sphere[3] / 1000., r0=sphere[:3] / 1000.) # Make the grid of sources in MRI space if volume_label is not None: sp = [] for label in volume_label: vol_sp = _make_volume_source_space(surf, pos, exclude, mindist, mri, label) sp.append(vol_sp) else: sp = _make_volume_source_space(surf, pos, exclude, mindist, mri, volume_label) # Compute an interpolation matrix to show data in MRI_VOXEL coord frame if not isinstance(sp, list): sp = [sp] if mri is not None: for s in sp: _add_interpolator(s, mri, add_interpolator) elif sp[0]['type'] == 'vol': # If there is no interpolator, it's actually a discrete source space sp[0]['type'] = 'discrete' for s in sp: if 'vol_dims' in s: del s['vol_dims'] # Save it for s in sp: s.update(dict(nearest=None, dist=None, use_tris=None, patch_inds=None, dist_limit=None, pinfo=None, ntri=0, nearest_dist=None, nuse_tri=0, tris=None, subject_his_id=subject)) sp = SourceSpaces(sp, dict(working_dir=os.getcwd(), command_line='None')) return sp def _make_voxel_ras_trans(move, ras, voxel_size): """Make a transformation from MRI_VOXEL to MRI surface RAS (i.e. MRI).""" assert voxel_size.ndim == 1 assert voxel_size.size == 3 rot = ras.T * voxel_size[np.newaxis, :] assert rot.ndim == 2 assert rot.shape[0] == 3 assert rot.shape[1] == 3 trans = np.c_[np.r_[rot, np.zeros((1, 3))], np.r_[move, 1.0]] t = Transform('mri_voxel', 'mri', trans) return t def _make_discrete_source_space(pos, coord_frame='mri'): """Use a discrete set of source locs/oris to make src space. Parameters ---------- pos : dict Must have entries "rr" and "nn". Data should be in meters. coord_frame : str The coordinate frame in which the positions are given; default: 'mri'. The frame must be one defined in transforms.py:_str_to_frame Returns ------- src : dict The source space. """ # Check that coordinate frame is valid if coord_frame not in _str_to_frame: # will fail if coord_frame not string raise KeyError('coord_frame must be one of %s, not "%s"' % (list(_str_to_frame.keys()), coord_frame)) coord_frame = _str_to_frame[coord_frame] # now an int # process points (copy and cast) rr = np.array(pos['rr'], float) nn = np.array(pos['nn'], float) if not (rr.ndim == nn.ndim == 2 and nn.shape[0] == nn.shape[0] and rr.shape[1] == nn.shape[1]): raise RuntimeError('"rr" and "nn" must both be 2D arrays with ' 'the same number of rows and 3 columns') npts = rr.shape[0] _normalize_vectors(nn) nz = np.sum(np.sum(nn * nn, axis=1) == 0) if nz != 0: raise RuntimeError('%d sources have zero length normal' % nz) logger.info('Positions (in meters) and orientations') logger.info('%d sources' % npts) # Ready to make the source space sp = dict(coord_frame=coord_frame, type='discrete', nuse=npts, np=npts, inuse=np.ones(npts, int), vertno=np.arange(npts), rr=rr, nn=nn, id=-1) return sp def _make_volume_source_space(surf, grid, exclude, mindist, mri=None, volume_label=None, do_neighbors=True, n_jobs=1): """Make a source space which covers the volume bounded by surf.""" # Figure out the grid size in the MRI coordinate frame if 'rr' in surf: mins = np.min(surf['rr'], axis=0) maxs = np.max(surf['rr'], axis=0) cm = np.mean(surf['rr'], axis=0) # center of mass maxdist = np.linalg.norm(surf['rr'] - cm, axis=1).max() else: mins = surf['r0'] - surf['R'] maxs = surf['r0'] + surf['R'] cm = surf['r0'].copy() maxdist = surf['R'] # Define the sphere which fits the surface logger.info('Surface CM = (%6.1f %6.1f %6.1f) mm' % (1000 * cm[0], 1000 * cm[1], 1000 * cm[2])) logger.info('Surface fits inside a sphere with radius %6.1f mm' % (1000 * maxdist)) logger.info('Surface extent:') for c, mi, ma in zip('xyz', mins, maxs): logger.info(' %s = %6.1f ... %6.1f mm' % (c, 1000 * mi, 1000 * ma)) maxn = np.array([np.floor(np.abs(m) / grid) + 1 if m > 0 else - np.floor(np.abs(m) / grid) - 1 for m in maxs], int) minn = np.array([np.floor(np.abs(m) / grid) + 1 if m > 0 else - np.floor(np.abs(m) / grid) - 1 for m in mins], int) logger.info('Grid extent:') for c, mi, ma in zip('xyz', minn, maxn): logger.info(' %s = %6.1f ... %6.1f mm' % (c, 1000 * mi * grid, 1000 * ma * grid)) # Now make the initial grid ns = maxn - minn + 1 npts = np.prod(ns) nrow = ns[0] ncol = ns[1] nplane = nrow * ncol # x varies fastest, then y, then z (can use unravel to do this) rr = np.meshgrid(np.arange(minn[2], maxn[2] + 1), np.arange(minn[1], maxn[1] + 1), np.arange(minn[0], maxn[0] + 1), indexing='ij') x, y, z = rr[2].ravel(), rr[1].ravel(), rr[0].ravel() rr = np.array([x * grid, y * grid, z * grid]).T sp = dict(np=npts, nn=np.zeros((npts, 3)), rr=rr, inuse=np.ones(npts, int), type='vol', nuse=npts, coord_frame=FIFF.FIFFV_COORD_MRI, id=-1, shape=ns) sp['nn'][:, 2] = 1.0 assert sp['rr'].shape[0] == npts logger.info('%d sources before omitting any.', sp['nuse']) # Exclude infeasible points dists = np.linalg.norm(sp['rr'] - cm, axis=1) bads = np.where(np.logical_or(dists < exclude, dists > maxdist))[0] sp['inuse'][bads] = False sp['nuse'] -= len(bads) logger.info('%d sources after omitting infeasible sources.', sp['nuse']) if 'rr' in surf: _filter_source_spaces(surf, mindist, None, [sp], n_jobs) else: # sphere vertno = np.where(sp['inuse'])[0] bads = (np.linalg.norm(sp['rr'][vertno] - surf['r0'], axis=-1) >= surf['R'] - mindist / 1000.) sp['nuse'] -= bads.sum() sp['inuse'][vertno[bads]] = False sp['vertno'] = np.where(sp['inuse'])[0] del vertno del surf logger.info('%d sources remaining after excluding the sources outside ' 'the surface and less than %6.1f mm inside.' % (sp['nuse'], mindist)) if not do_neighbors: if volume_label is not None: raise RuntimeError('volume_label cannot be None unless ' 'do_neighbors is True') return sp k = np.arange(npts) neigh = np.empty((26, npts), int) neigh.fill(-1) # Figure out each neighborhood: # 6-neighborhood first idxs = [z > minn[2], x < maxn[0], y < maxn[1], x > minn[0], y > minn[1], z < maxn[2]] offsets = [-nplane, 1, nrow, -1, -nrow, nplane] for n, idx, offset in zip(neigh[:6], idxs, offsets): n[idx] = k[idx] + offset # Then the rest to complete the 26-neighborhood # First the plane below idx1 = z > minn[2] idx2 = np.logical_and(idx1, x < maxn[0]) neigh[6, idx2] = k[idx2] + 1 - nplane idx3 = np.logical_and(idx2, y < maxn[1]) neigh[7, idx3] = k[idx3] + 1 + nrow - nplane idx2 = np.logical_and(idx1, y < maxn[1]) neigh[8, idx2] = k[idx2] + nrow - nplane idx2 = np.logical_and(idx1, x > minn[0]) idx3 = np.logical_and(idx2, y < maxn[1]) neigh[9, idx3] = k[idx3] - 1 + nrow - nplane neigh[10, idx2] = k[idx2] - 1 - nplane idx3 = np.logical_and(idx2, y > minn[1]) neigh[11, idx3] = k[idx3] - 1 - nrow - nplane idx2 = np.logical_and(idx1, y > minn[1]) neigh[12, idx2] = k[idx2] - nrow - nplane idx3 = np.logical_and(idx2, x < maxn[0]) neigh[13, idx3] = k[idx3] + 1 - nrow - nplane # Then the same plane idx1 = np.logical_and(x < maxn[0], y < maxn[1]) neigh[14, idx1] = k[idx1] + 1 + nrow idx1 = x > minn[0] idx2 = np.logical_and(idx1, y < maxn[1]) neigh[15, idx2] = k[idx2] - 1 + nrow idx2 = np.logical_and(idx1, y > minn[1]) neigh[16, idx2] = k[idx2] - 1 - nrow idx1 = np.logical_and(y > minn[1], x < maxn[0]) neigh[17, idx1] = k[idx1] + 1 - nrow - nplane # Finally one plane above idx1 = z < maxn[2] idx2 = np.logical_and(idx1, x < maxn[0]) neigh[18, idx2] = k[idx2] + 1 + nplane idx3 = np.logical_and(idx2, y < maxn[1]) neigh[19, idx3] = k[idx3] + 1 + nrow + nplane idx2 = np.logical_and(idx1, y < maxn[1]) neigh[20, idx2] = k[idx2] + nrow + nplane idx2 = np.logical_and(idx1, x > minn[0]) idx3 = np.logical_and(idx2, y < maxn[1]) neigh[21, idx3] = k[idx3] - 1 + nrow + nplane neigh[22, idx2] = k[idx2] - 1 + nplane idx3 = np.logical_and(idx2, y > minn[1]) neigh[23, idx3] = k[idx3] - 1 - nrow + nplane idx2 = np.logical_and(idx1, y > minn[1]) neigh[24, idx2] = k[idx2] - nrow + nplane idx3 = np.logical_and(idx2, x < maxn[0]) neigh[25, idx3] = k[idx3] + 1 - nrow + nplane # Restrict sources to volume of interest if volume_label is not None: try: import nibabel as nib except ImportError: raise ImportError("nibabel is required to read segmentation file.") logger.info('Selecting voxels from %s' % volume_label) # Read the segmentation data using nibabel mgz = nib.load(mri) mgz_data = mgz.get_data() # Get the numeric index for this volume label lut = _get_lut() vol_id = _get_lut_id(lut, volume_label, True) # Get indices for this volume label in voxel space vox_bool = mgz_data == vol_id # Get the 3 dimensional indices in voxel space vox_xyz = np.array(np.where(vox_bool)).T # Transform to RAS coordinates # (use tkr normalization or volume won't align with surface sources) trans = _get_mgz_header(mri)['vox2ras_tkr'] # Convert transform from mm to m trans[:3] /= 1000. rr_voi = apply_trans(trans, vox_xyz) # positions of VOI in RAS space # Filter out points too far from volume region voxels dists = _compute_nearest(rr_voi, sp['rr'], return_dists=True)[1] # Maximum distance from center of mass of a voxel to any of its corners maxdist = linalg.norm(trans[:3, :3].sum(0) / 2.) bads = np.where(dists > maxdist)[0] # Update source info sp['inuse'][bads] = False sp['vertno'] = np.where(sp['inuse'] > 0)[0] sp['nuse'] = len(sp['vertno']) sp['seg_name'] = volume_label sp['mri_file'] = mri # Update log logger.info('%d sources remaining after excluding sources too far ' 'from VOI voxels', sp['nuse']) # Omit unused vertices from the neighborhoods logger.info('Adjusting the neighborhood info...') # remove non source-space points log_inuse = sp['inuse'] > 0 neigh[:, np.logical_not(log_inuse)] = -1 # remove these points from neigh vertno = np.where(log_inuse)[0] sp['vertno'] = vertno old_shape = neigh.shape neigh = neigh.ravel() checks = np.where(neigh >= 0)[0] removes = np.logical_not(np.in1d(checks, vertno)) neigh[checks[removes]] = -1 neigh.shape = old_shape neigh = neigh.T # Thought we would need this, but C code keeps -1 vertices, so we will: # neigh = [n[n >= 0] for n in enumerate(neigh[vertno])] sp['neighbor_vert'] = neigh # Set up the volume data (needed for creating the interpolation matrix) r0 = minn * grid voxel_size = grid * np.ones(3) ras = np.eye(3) sp['src_mri_t'] = _make_voxel_ras_trans(r0, ras, voxel_size) sp['vol_dims'] = maxn - minn + 1 return sp def _vol_vertex(width, height, jj, kk, pp): return jj + width * kk + pp * (width * height) def _get_mri_header(fname): """Get MRI header using nibabel.""" import nibabel as nib img = nib.load(fname) try: return img.header except AttributeError: # old nibabel return img.get_header() def _get_mgz_header(fname): """Adapted from nibabel to quickly extract header info.""" if not fname.endswith('.mgz'): raise IOError('Filename must end with .mgz') header_dtd = [('version', '>i4'), ('dims', '>i4', (4,)), ('type', '>i4'), ('dof', '>i4'), ('goodRASFlag', '>i2'), ('delta', '>f4', (3,)), ('Mdc', '>f4', (3, 3)), ('Pxyz_c', '>f4', (3,))] header_dtype = np.dtype(header_dtd) with GzipFile(fname, 'rb') as fid: hdr_str = fid.read(header_dtype.itemsize) header = np.ndarray(shape=(), dtype=header_dtype, buffer=hdr_str) # dims dims = header['dims'].astype(int) dims = dims[:3] if len(dims) == 4 else dims # vox2ras_tkr delta = header['delta'] ds = np.array(delta, float) ns = np.array(dims * ds) / 2.0 v2rtkr = np.array([[-ds[0], 0, 0, ns[0]], [0, 0, ds[2], -ns[2]], [0, -ds[1], 0, ns[1]], [0, 0, 0, 1]], dtype=np.float32) # ras2vox d = np.diag(delta) pcrs_c = dims / 2.0 Mdc = header['Mdc'].T pxyz_0 = header['Pxyz_c'] - np.dot(Mdc, np.dot(d, pcrs_c)) M = np.eye(4, 4) M[0:3, 0:3] = np.dot(Mdc, d) M[0:3, 3] = pxyz_0.T M = linalg.inv(M) header = dict(dims=dims, vox2ras_tkr=v2rtkr, ras2vox=M) return header def _add_interpolator(s, mri_name, add_interpolator): """Compute a sparse matrix to interpolate the data into an MRI volume.""" # extract transformation information from mri logger.info('Reading %s...' % mri_name) header = _get_mgz_header(mri_name) mri_width, mri_height, mri_depth = header['dims'] s.update(dict(mri_width=mri_width, mri_height=mri_height, mri_depth=mri_depth)) trans = header['vox2ras_tkr'].copy() trans[:3, :] /= 1000.0 s['vox_mri_t'] = Transform('mri_voxel', 'mri', trans) # ras_tkr trans = linalg.inv(np.dot(header['vox2ras_tkr'], header['ras2vox'])) trans[:3, 3] /= 1000.0 s['mri_ras_t'] = Transform('mri', 'ras', trans) # ras s['mri_volume_name'] = mri_name nvox = mri_width * mri_height * mri_depth if not add_interpolator: s['interpolator'] = sparse.csr_matrix((nvox, s['np'])) return _print_coord_trans(s['src_mri_t'], 'Source space : ') _print_coord_trans(s['vox_mri_t'], 'MRI volume : ') _print_coord_trans(s['mri_ras_t'], 'MRI volume : ') # # Convert MRI voxels from destination (MRI volume) to source (volume # source space subset) coordinates # combo_trans = combine_transforms(s['vox_mri_t'], invert_transform(s['src_mri_t']), 'mri_voxel', 'mri_voxel') combo_trans['trans'] = combo_trans['trans'].astype(np.float32) logger.info('Setting up interpolation...') # Loop over slices to save (lots of) memory # Note that it is the slowest incrementing index # This is equivalent to using mgrid and reshaping, but faster data = [] indices = [] indptr = np.zeros(nvox + 1, np.int32) for p in range(mri_depth): js = np.arange(mri_width, dtype=np.float32) js = np.tile(js[np.newaxis, :], (mri_height, 1)).ravel() ks = np.arange(mri_height, dtype=np.float32) ks = np.tile(ks[:, np.newaxis], (1, mri_width)).ravel() ps = np.empty((mri_height, mri_width), np.float32).ravel() ps.fill(p) r0 = np.c_[js, ks, ps] del js, ks, ps # Transform our vertices from their MRI space into our source space's # frame (this is labeled as FIFFV_MNE_COORD_MRI_VOXEL, but it's # really a subset of the entire volume!) r0 = apply_trans(combo_trans['trans'], r0) rn = np.floor(r0).astype(int) maxs = (s['vol_dims'] - 1)[np.newaxis, :] good = np.where(np.logical_and(np.all(rn >= 0, axis=1), np.all(rn < maxs, axis=1)))[0] rn = rn[good] r0 = r0[good] # now we take each MRI voxel *in this space*, and figure out how # to make its value the weighted sum of voxels in the volume source # space. This is a 3D weighting scheme based (presumably) on the # fact that we know we're interpolating from one volumetric grid # into another. jj = rn[:, 0] kk = rn[:, 1] pp = rn[:, 2] vss = np.empty((len(jj), 8), np.int32) width = s['vol_dims'][0] height = s['vol_dims'][1] jjp1 = jj + 1 kkp1 = kk + 1 ppp1 = pp + 1 vss[:, 0] = _vol_vertex(width, height, jj, kk, pp) vss[:, 1] = _vol_vertex(width, height, jjp1, kk, pp) vss[:, 2] = _vol_vertex(width, height, jjp1, kkp1, pp) vss[:, 3] = _vol_vertex(width, height, jj, kkp1, pp) vss[:, 4] = _vol_vertex(width, height, jj, kk, ppp1) vss[:, 5] = _vol_vertex(width, height, jjp1, kk, ppp1) vss[:, 6] = _vol_vertex(width, height, jjp1, kkp1, ppp1) vss[:, 7] = _vol_vertex(width, height, jj, kkp1, ppp1) del jj, kk, pp, jjp1, kkp1, ppp1 uses = np.any(s['inuse'][vss], axis=1) if uses.size == 0: continue vss = vss[uses].ravel() # vertex (col) numbers in csr matrix indices.append(vss) indptr[good[uses] + p * mri_height * mri_width + 1] = 8 del vss # figure out weights for each vertex r0 = r0[uses] rn = rn[uses] del uses, good xf = r0[:, 0] - rn[:, 0].astype(np.float32) yf = r0[:, 1] - rn[:, 1].astype(np.float32) zf = r0[:, 2] - rn[:, 2].astype(np.float32) omxf = 1.0 - xf omyf = 1.0 - yf omzf = 1.0 - zf # each entry in the concatenation corresponds to a row of vss data.append(np.array([omxf * omyf * omzf, xf * omyf * omzf, xf * yf * omzf, omxf * yf * omzf, omxf * omyf * zf, xf * omyf * zf, xf * yf * zf, omxf * yf * zf], order='F').T.ravel()) del xf, yf, zf, omxf, omyf, omzf # Compose the sparse matrix indptr = np.cumsum(indptr, out=indptr) indices = np.concatenate(indices) data = np.concatenate(data) s['interpolator'] = sparse.csr_matrix((data, indices, indptr), shape=(nvox, s['np'])) logger.info(' %d/%d nonzero values [done]' % (len(data), nvox)) @verbose def _filter_source_spaces(surf, limit, mri_head_t, src, n_jobs=1, verbose=None): """Remove all source space points closer than a given limit (in mm).""" if src[0]['coord_frame'] == FIFF.FIFFV_COORD_HEAD and mri_head_t is None: raise RuntimeError('Source spaces are in head coordinates and no ' 'coordinate transform was provided!') # How close are the source points to the surface? out_str = 'Source spaces are in ' if src[0]['coord_frame'] == FIFF.FIFFV_COORD_HEAD: inv_trans = invert_transform(mri_head_t) out_str += 'head coordinates.' elif src[0]['coord_frame'] == FIFF.FIFFV_COORD_MRI: out_str += 'MRI coordinates.' else: out_str += 'unknown (%d) coordinates.' % src[0]['coord_frame'] logger.info(out_str) out_str = 'Checking that the sources are inside the bounding surface' if limit > 0.0: out_str += ' and at least %6.1f mm away' % (limit) logger.info(out_str + ' (will take a few...)') for s in src: vertno = np.where(s['inuse'])[0] # can't trust s['vertno'] this deep # Convert all points here first to save time r1s = s['rr'][vertno] if s['coord_frame'] == FIFF.FIFFV_COORD_HEAD: r1s = apply_trans(inv_trans['trans'], r1s) # Check that the source is inside surface (often the inner skull) outside = _points_outside_surface(r1s, surf, n_jobs) omit_outside = np.sum(outside) # vectorized nearest using BallTree (or cdist) omit = 0 if limit > 0.0: dists = _compute_nearest(surf['rr'], r1s, return_dists=True)[1] close = np.logical_and(dists < limit / 1000.0, np.logical_not(outside)) omit = np.sum(close) outside = np.logical_or(outside, close) s['inuse'][vertno[outside]] = False s['nuse'] -= (omit + omit_outside) s['vertno'] = np.where(s['inuse'])[0] if omit_outside > 0: extras = [omit_outside] extras += ['s', 'they are'] if omit_outside > 1 else ['', 'it is'] logger.info('%d source space point%s omitted because %s ' 'outside the inner skull surface.' % tuple(extras)) if omit > 0: extras = [omit] extras += ['s'] if omit_outside > 1 else [''] extras += [limit] logger.info('%d source space point%s omitted because of the ' '%6.1f-mm distance limit.' % tuple(extras)) # Adjust the patch inds as well if necessary if omit + omit_outside > 0: _adjust_patch_info(s) logger.info('Thank you for waiting.') @verbose def _adjust_patch_info(s, verbose=None): """Adjust patch information in place after vertex omission.""" if s.get('patch_inds') is not None: if s['nearest'] is None: # This shouldn't happen, but if it does, we can probably come # up with a more clever solution raise RuntimeError('Cannot adjust patch information properly, ' 'please contact the mne-python developers') _add_patch_info(s) @verbose def _points_outside_surface(rr, surf, n_jobs=1, verbose=None): """Check whether points are outside a surface. Parameters ---------- rr : ndarray Nx3 array of points to check. surf : dict Surface with entries "rr" and "tris". Returns ------- outside : ndarray 1D logical array of size N for which points are outside the surface. """ rr = np.atleast_2d(rr) assert rr.shape[1] == 3 assert n_jobs > 0 parallel, p_fun, _ = parallel_func(_get_solids, n_jobs) tot_angles = parallel(p_fun(surf['rr'][tris], rr) for tris in np.array_split(surf['tris'], n_jobs)) return np.abs(np.sum(tot_angles, axis=0) / (2 * np.pi) - 1.0) > 1e-5 @verbose def _ensure_src(src, kind=None, verbose=None): """Ensure we have a source space.""" if isinstance(src, str): if not op.isfile(src): raise IOError('Source space file "%s" not found' % src) logger.info('Reading %s...' % src) src = read_source_spaces(src, verbose=False) if not isinstance(src, SourceSpaces): raise ValueError('src must be a string or instance of SourceSpaces') if kind is not None: if kind == 'surf': surf = [s for s in src if s['type'] == 'surf'] if len(surf) != 2 or len(src) != 2: raise ValueError('Source space must contain exactly two ' 'surfaces.') src = surf return src def _ensure_src_subject(src, subject): src_subject = src[0].get('subject_his_id', None) if subject is None: subject = src_subject if subject is None: raise ValueError('source space is too old, subject must be ' 'provided') elif src_subject is not None and subject != src_subject: raise ValueError('Mismatch between provided subject "%s" and subject ' 'name "%s" in the source space' % (subject, src_subject)) return subject _DIST_WARN_LIMIT = 10242 # warn for anything larger than ICO-5 @verbose def add_source_space_distances(src, dist_limit=np.inf, n_jobs=1, verbose=None): """Compute inter-source distances along the cortical surface. This function will also try to add patch info for the source space. It will only occur if the ``dist_limit`` is sufficiently high that all points on the surface are within ``dist_limit`` of a point in the source space. Parameters ---------- src : instance of SourceSpaces The source spaces to compute distances for. dist_limit : float The upper limit of distances to include (in meters). Note: if limit < np.inf, scipy > 0.13 (bleeding edge as of 10/2013) must be installed. n_jobs : int Number of jobs to run in parallel. Will only use (up to) as many cores as there are source spaces. %(verbose)s Returns ------- src : instance of SourceSpaces The original source spaces, with distance information added. The distances are stored in src[n]['dist']. Note: this function operates in-place. Notes ----- This function can be memory- and CPU-intensive. On a high-end machine (2012) running 6 jobs in parallel, an ico-5 (10242 per hemi) source space takes about 10 minutes to compute all distances (`dist_limit = np.inf`). With `dist_limit = 0.007`, computing distances takes about 1 minute. We recommend computing distances once per source space and then saving the source space to disk, as the computed distances will automatically be stored along with the source space data for future use. """ n_jobs = check_n_jobs(n_jobs) src = _ensure_src(src) if not np.isscalar(dist_limit): raise ValueError('limit must be a scalar, got %s' % repr(dist_limit)) if not check_version('scipy', '0.11'): raise RuntimeError('scipy >= 0.11 must be installed (or > 0.13 ' 'if dist_limit < np.inf') if src.kind != 'surface': raise RuntimeError('Currently all source spaces must be of surface ' 'type') parallel, p_fun, _ = parallel_func(_do_src_distances, n_jobs) min_dists = list() min_idxs = list() logger.info('Calculating source space distances (limit=%s mm)...' % (1000 * dist_limit)) max_n = max(s['nuse'] for s in src) if max_n > _DIST_WARN_LIMIT: warn('Computing distances for %d source space points (in one ' 'hemisphere) will be very slow, consider using add_dist=False' % (max_n,)) for s in src: connectivity = mesh_dist(s['tris'], s['rr']) d = parallel(p_fun(connectivity, s['vertno'], r, dist_limit) for r in np.array_split(np.arange(len(s['vertno'])), n_jobs)) # deal with indexing so we can add patch info min_idx = np.array([dd[1] for dd in d]) min_dist = np.array([dd[2] for dd in d]) midx = np.argmin(min_dist, axis=0) range_idx = np.arange(len(s['rr'])) min_dist = min_dist[midx, range_idx] min_idx = min_idx[midx, range_idx] min_dists.append(min_dist) min_idxs.append(min_idx) # now actually deal with distances, convert to sparse representation d = np.concatenate([dd[0] for dd in d]).ravel() # already float32 idx = d > 0 d = d[idx] i, j = np.meshgrid(s['vertno'], s['vertno']) i = i.ravel()[idx] j = j.ravel()[idx] d = sparse.csr_matrix((d, (i, j)), shape=(s['np'], s['np']), dtype=np.float32) s['dist'] = d s['dist_limit'] = np.array([dist_limit], np.float32) # Let's see if our distance was sufficient to allow for patch info if not any(np.any(np.isinf(md)) for md in min_dists): # Patch info can be added! for s, min_dist, min_idx in zip(src, min_dists, min_idxs): s['nearest'] = min_idx s['nearest_dist'] = min_dist _add_patch_info(s) else: logger.info('Not adding patch information, dist_limit too small') return src def _do_src_distances(con, vertno, run_inds, limit): """Compute source space distances in chunks.""" from scipy.sparse.csgraph import dijkstra if limit < np.inf: func = partial(dijkstra, limit=limit) else: func = dijkstra chunk_size = 20 # save memory by chunking (only a little slower) lims = np.r_[np.arange(0, len(run_inds), chunk_size), len(run_inds)] n_chunks = len(lims) - 1 # eventually we want this in float32, so save memory by only storing 32-bit d = np.empty((len(run_inds), len(vertno)), np.float32) min_dist = np.empty((n_chunks, con.shape[0])) min_idx = np.empty((n_chunks, con.shape[0]), np.int32) range_idx = np.arange(con.shape[0]) for li, (l1, l2) in enumerate(zip(lims[:-1], lims[1:])): idx = vertno[run_inds[l1:l2]] out = func(con, indices=idx) midx = np.argmin(out, axis=0) min_idx[li] = idx[midx] min_dist[li] = out[midx, range_idx] d[l1:l2] = out[:, vertno] midx = np.argmin(min_dist, axis=0) min_dist = min_dist[midx, range_idx] min_idx = min_idx[midx, range_idx] d[d == np.inf] = 0 # scipy will give us np.inf for uncalc. distances return d, min_idx, min_dist def get_volume_labels_from_aseg(mgz_fname, return_colors=False): """Return a list of names and colors of segmented volumes. Parameters ---------- mgz_fname : str Filename to read. Typically aseg.mgz or some variant in the freesurfer pipeline. return_colors : bool If True returns also the labels colors Returns ------- label_names : list of str The names of segmented volumes included in this mgz file. label_colors : list of str The RGB colors of the labels included in this mgz file. Notes ----- .. versionadded:: 0.9.0 """ import nibabel as nib # Read the mgz file using nibabel mgz_data = nib.load(mgz_fname).get_data() # Get the unique label names lut = _get_lut() label_names = [lut[lut['id'] == ii]['name'][0] for ii in np.unique(mgz_data)] label_colors = [[lut[lut['id'] == ii]['R'][0], lut[lut['id'] == ii]['G'][0], lut[lut['id'] == ii]['B'][0], lut[lut['id'] == ii]['A'][0]] for ii in np.unique(mgz_data)] order = np.argsort(label_names) label_names = [label_names[k] for k in order] label_colors = [label_colors[k] for k in order] if return_colors: return label_names, label_colors else: return label_names def get_volume_labels_from_src(src, subject, subjects_dir): """Return a list of Label of segmented volumes included in the src space. Parameters ---------- src : instance of SourceSpaces The source space containing the volume regions subject: str Subject name subjects_dir: str Freesurfer folder of the subjects Returns ------- labels_aseg : list of Label List of Label of segmented volumes included in src space. """ from . import Label from . import get_volume_labels_from_aseg # Read the aseg file aseg_fname = op.join(subjects_dir, subject, 'mri', 'aseg.mgz') if not op.isfile(aseg_fname): raise IOError('aseg file "%s" not found' % aseg_fname) all_labels_aseg = get_volume_labels_from_aseg(aseg_fname, return_colors=True) # Create a list of Label if len(src) < 2: raise ValueError('No vol src space in src') if any(np.any(s['type'] != 'vol') for s in src[2:]): raise ValueError('source spaces have to be of vol type') labels_aseg = list() for nr in range(2, len(src)): vertices = src[nr]['vertno'] pos = src[nr]['rr'][src[nr]['vertno'], :] roi_str = src[nr]['seg_name'] try: ind = all_labels_aseg[0].index(roi_str) color = np.array(all_labels_aseg[1][ind]) / 255 except ValueError: pass if 'left' in roi_str.lower(): hemi = 'lh' roi_str = roi_str.replace('Left-', '') + '-lh' elif 'right' in roi_str.lower(): hemi = 'rh' roi_str = roi_str.replace('Right-', '') + '-rh' else: hemi = 'both' label = Label(vertices=vertices, pos=pos, hemi=hemi, name=roi_str, color=color, subject=subject) labels_aseg.append(label) return labels_aseg def _get_hemi(s): """Get a hemisphere from a given source space.""" if s['type'] != 'surf': raise RuntimeError('Only surface source spaces supported') if s['id'] == FIFF.FIFFV_MNE_SURF_LEFT_HEMI: return 'lh', 0, s['id'] elif s['id'] == FIFF.FIFFV_MNE_SURF_RIGHT_HEMI: return 'rh', 1, s['id'] else: raise ValueError('unknown surface ID %s' % s['id']) def _get_vertex_map_nn(fro_src, subject_from, subject_to, hemi, subjects_dir, to_neighbor_tri=None): """Get a nearest-neigbor vertex match for a given hemi src. The to_neighbor_tri can optionally be passed in to avoid recomputation if it's already available. """ # adapted from mne_make_source_space.c, knowing accurate=False (i.e. # nearest-neighbor mode should be used) logger.info('Mapping %s %s -> %s (nearest neighbor)...' % (hemi, subject_from, subject_to)) regs = [op.join(subjects_dir, s, 'surf', '%s.sphere.reg' % hemi) for s in (subject_from, subject_to)] reg_fro, reg_to = [read_surface(r, return_dict=True)[-1] for r in regs] if to_neighbor_tri is not None: reg_to['neighbor_tri'] = to_neighbor_tri if 'neighbor_tri' not in reg_to: reg_to['neighbor_tri'] = _triangle_neighbors(reg_to['tris'], reg_to['np']) morph_inuse = np.zeros(len(reg_to['rr']), bool) best = np.zeros(fro_src['np'], int) ones = _compute_nearest(reg_to['rr'], reg_fro['rr'][fro_src['vertno']]) for v, one in zip(fro_src['vertno'], ones): # if it were actually a proper morph map, we would do this, but since # we know it's nearest neighbor list, we don't need to: # this_mm = mm[v] # one = this_mm.indices[this_mm.data.argmax()] if morph_inuse[one]: # Try the nearest neighbors neigh = _get_surf_neighbors(reg_to, one) # on demand calc was = one one = neigh[np.where(~morph_inuse[neigh])[0]] if len(one) == 0: raise RuntimeError('vertex %d would be used multiple times.' % one) one = one[0] logger.info('Source space vertex moved from %d to %d because of ' 'double occupation.' % (was, one)) best[v] = one morph_inuse[one] = True return best @verbose def morph_source_spaces(src_from, subject_to, surf='white', subject_from=None, subjects_dir=None, verbose=None): """Morph an existing source space to a different subject. .. warning:: This can be used in place of morphing source estimates for multiple subjects, but there may be consequences in terms of dipole topology. Parameters ---------- src_from : instance of SourceSpaces Surface source spaces to morph. subject_to : str The destination subject. surf : str The brain surface to use for the new source space. subject_from : str | None The "from" subject. For most source spaces this shouldn't need to be provided, since it is stored in the source space itself. subjects_dir : str | None Path to SUBJECTS_DIR if it is not set in the environment. %(verbose)s Returns ------- src : instance of SourceSpaces The morphed source spaces. Notes ----- .. versionadded:: 0.10.0 """ # adapted from mne_make_source_space.c src_from = _ensure_src(src_from) subject_from = _ensure_src_subject(src_from, subject_from) subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) src_out = list() for fro in src_from: hemi, idx, id_ = _get_hemi(fro) to = op.join(subjects_dir, subject_to, 'surf', '%s.%s' % (hemi, surf,)) logger.info('Reading destination surface %s' % (to,)) to = read_surface(to, return_dict=True, verbose=False)[-1] complete_surface_info(to, copy=False) # Now we morph the vertices to the destination # The C code does something like this, but with a nearest-neighbor # mapping instead of the weighted one:: # # >>> mm = read_morph_map(subject_from, subject_to, subjects_dir) # # Here we use a direct NN calculation, since picking the max from the # existing morph map (which naively one might expect to be equivalent) # differs for ~3% of vertices. best = _get_vertex_map_nn(fro, subject_from, subject_to, hemi, subjects_dir, to['neighbor_tri']) for key in ('neighbor_tri', 'tri_area', 'tri_cent', 'tri_nn', 'use_tris'): del to[key] to['vertno'] = np.sort(best[fro['vertno']]) to['inuse'] = np.zeros(len(to['rr']), int) to['inuse'][to['vertno']] = True to['use_tris'] = best[fro['use_tris']] to.update(nuse=len(to['vertno']), nuse_tri=len(to['use_tris']), nearest=None, nearest_dist=None, patch_inds=None, pinfo=None, dist=None, id=id_, dist_limit=None, type='surf', coord_frame=FIFF.FIFFV_COORD_MRI, subject_his_id=subject_to, rr=to['rr'] / 1000.) src_out.append(to) logger.info('[done]\n') info = dict(working_dir=os.getcwd(), command_line=_get_call_line(in_verbose=True)) return SourceSpaces(src_out, info=info) @verbose def _get_morph_src_reordering(vertices, src_from, subject_from, subject_to, subjects_dir=None, verbose=None): """Get the reordering indices for a morphed source space. Parameters ---------- vertices : list The vertices for the left and right hemispheres. src_from : instance of SourceSpaces The original source space. subject_from : str The source subject. subject_to : str The destination subject. subjects_dir : string, or None Path to SUBJECTS_DIR if it is not set in the environment. %(verbose)s Returns ------- data_idx : ndarray, shape (n_vertices,) The array used to reshape the data. from_vertices : list The right and left hemisphere vertex numbers for the "from" subject. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) from_vertices = list() data_idxs = list() offset = 0 for ii, hemi in enumerate(('lh', 'rh')): # Get the mapping from the original source space to the destination # subject's surface vertex numbers best = _get_vertex_map_nn(src_from[ii], subject_from, subject_to, hemi, subjects_dir) full_mapping = best[src_from[ii]['vertno']] # Tragically, we might not have all of our vertno left (e.g. because # some are omitted during fwd calc), so we must do some indexing magic: # From all vertices, a subset could be chosen by fwd calc: used_vertices = np.in1d(full_mapping, vertices[ii]) from_vertices.append(src_from[ii]['vertno'][used_vertices]) remaining_mapping = full_mapping[used_vertices] if not np.array_equal(np.sort(remaining_mapping), vertices[ii]) or \ not np.in1d(vertices[ii], full_mapping).all(): raise RuntimeError('Could not map vertices, perhaps the wrong ' 'subject "%s" was provided?' % subject_from) # And our data have been implicitly remapped by the forced ascending # vertno order in source spaces implicit_mapping = np.argsort(remaining_mapping) # happens to data data_idx = np.argsort(implicit_mapping) # to reverse the mapping data_idx += offset # hemisphere offset data_idxs.append(data_idx) offset += len(implicit_mapping) data_idx = np.concatenate(data_idxs) # this one is really just a sanity check for us, should never be violated # by users assert np.array_equal(np.sort(data_idx), np.arange(sum(len(v) for v in vertices))) return data_idx, from_vertices def _compare_source_spaces(src0, src1, mode='exact', nearest=True, dist_tol=1.5e-3): """Compare two source spaces. Note: this function is also used by forward/tests/test_make_forward.py """ from numpy.testing import (assert_allclose, assert_array_equal, assert_equal, assert_) from scipy.spatial.distance import cdist if mode != 'exact' and 'approx' not in mode: # 'nointerp' can be appended raise RuntimeError('unknown mode %s' % mode) for si, (s0, s1) in enumerate(zip(src0, src1)): # first check the keys a, b = set(s0.keys()), set(s1.keys()) assert_equal(a, b, str(a ^ b)) for name in ['nuse', 'ntri', 'np', 'type', 'id']: a, b = s0[name], s1[name] if name == 'id': # workaround for old NumPy bug a, b = int(a), int(b) assert_equal(a, b, name) for name in ['subject_his_id']: if name in s0 or name in s1: assert_equal(s0[name], s1[name], name) for name in ['interpolator']: if name in s0 or name in s1: diffs = (s0['interpolator'] - s1['interpolator']).data if len(diffs) > 0 and 'nointerp' not in mode: # 5% assert_(np.sqrt(np.mean(diffs ** 2)) < 0.10, name) for name in ['nn', 'rr', 'nuse_tri', 'coord_frame', 'tris']: if s0[name] is None: assert_(s1[name] is None, name) else: if mode == 'exact': assert_array_equal(s0[name], s1[name], name) else: # 'approx' in mode atol = 1e-3 if name == 'nn' else 1e-4 assert_allclose(s0[name], s1[name], rtol=1e-3, atol=atol, err_msg=name) for name in ['seg_name']: if name in s0 or name in s1: assert_equal(s0[name], s1[name], name) # these fields will exist if patch info was added if nearest: for name in ['nearest', 'nearest_dist', 'patch_inds']: if s0[name] is None: assert_(s1[name] is None, name) else: assert_array_equal(s0[name], s1[name]) for name in ['pinfo']: if s0[name] is None: assert_(s1[name] is None, name) else: assert_(len(s0[name]) == len(s1[name]), name) for p1, p2 in zip(s0[name], s1[name]): assert_(all(p1 == p2), name) if mode == 'exact': for name in ['inuse', 'vertno', 'use_tris']: assert_array_equal(s0[name], s1[name], err_msg=name) for name in ['dist_limit']: assert_(s0[name] == s1[name], name) for name in ['dist']: if s0[name] is not None: assert_equal(s1[name].shape, s0[name].shape) assert_(len((s0['dist'] - s1['dist']).data) == 0) else: # 'approx' in mode: # deal with vertno, inuse, and use_tris carefully for ii, s in enumerate((s0, s1)): assert_array_equal(s['vertno'], np.where(s['inuse'])[0], 'src%s[%s]["vertno"] != ' 'np.where(src%s[%s]["inuse"])[0]' % (ii, si, ii, si)) assert_equal(len(s0['vertno']), len(s1['vertno'])) agreement = np.mean(s0['inuse'] == s1['inuse']) assert_(agreement >= 0.99, "%s < 0.99" % agreement) if agreement < 1.0: # make sure mismatched vertno are within 1.5mm v0 = np.setdiff1d(s0['vertno'], s1['vertno']) v1 = np.setdiff1d(s1['vertno'], s0['vertno']) dists = cdist(s0['rr'][v0], s1['rr'][v1]) assert_allclose(np.min(dists, axis=1), np.zeros(len(v0)), atol=dist_tol, err_msg='mismatched vertno') if s0['use_tris'] is not None: # for "spacing" assert_array_equal(s0['use_tris'].shape, s1['use_tris'].shape) else: assert_(s1['use_tris'] is None) assert_(np.mean(s0['use_tris'] == s1['use_tris']) > 0.99) # The above "if s0[name] is not None" can be removed once the sample # dataset is updated to have a source space with distance info for name in ['working_dir', 'command_line']: if mode == 'exact': assert_equal(src0.info[name], src1.info[name]) else: # 'approx' in mode: if name in src0.info: assert_(name in src1.info, '"%s" missing' % name) else: assert_(name not in src1.info, '"%s" should not exist' % name) def _set_source_space_vertices(src, vertices): """Reset the list of source space vertices.""" assert len(src) == len(vertices) for s, v in zip(src, vertices): s['inuse'].fill(0) s['nuse'] = len(v) s['vertno'] = np.array(v) s['inuse'][s['vertno']] = 1 s['use_tris'] = np.array([[]], int) s['nuse_tri'] = np.array([0]) # This will fix 'patch_info' and 'pinfo' _adjust_patch_info(s, verbose=False) return src
{ "content_hash": "905ba0eb2419e13a66fb11c6919e027c", "timestamp": "", "source": "github", "line_count": 2883, "max_line_length": 79, "avg_line_length": 38.852930974679154, "alnum_prop": 0.5578459643077143, "repo_name": "adykstra/mne-python", "id": "872be15f84afb13b5b35e10867b8f119418a6825", "size": "112168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mne/source_space.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Csound Document", "bytes": "69806" }, { "name": "Makefile", "bytes": "3928" }, { "name": "Python", "bytes": "6001033" }, { "name": "Shell", "bytes": "936" } ], "symlink_target": "" }
package org.genomalysis.clustalw; import java.io.IOException; import java.io.Serializable; import org.genomalysis.plugin.configuration.annotations.Author; import org.genomalysis.plugin.configuration.annotations.Configurator; import org.genomalysis.plugin.configuration.annotations.Documentation; import org.genomalysis.proteintools.IProteinSequenceFilter; import org.genomalysis.proteintools.InitializationException; import org.genomalysis.proteintools.ProteinSequence; @Documentation("The ClustalW filter uses the ClustalW program to determine how alike proteins are. You can specify how alike proteins must be (to your target protein) by editing the filter configuration.") @Author(EmailAddress = "wolfgangmeyers@gmail.com", Name = "Wolfgang Meyers") @Configurator(ClustalWFilterConfigurator.class) public class ClustalWFilter implements IProteinSequenceFilter, Serializable { private static final long serialVersionUID = 1L; private ClustalWInterface parser; private ClustalWFilterConfiguration config; public ClustalWFilter() { this.parser = new ClustalWInterface(); this.config = new ClustalWFilterConfiguration(); } public void initialize() throws InitializationException { try { ProcessBuilder pb = new ProcessBuilder(new String[] { "clustalo" }); pb.start(); ProteinSequence sequence = ProteinSequence.parse(config .getSequenceData()); if ((sequence.getHeader() == null) || (sequence.getData() == null) || sequence.getData().isEmpty()) throw new InitializationException( new String[] { "ClustalWFilter: Invalid protein sequence" }); } catch (InitializationException ex) { throw ex; } catch (Exception ex) { throw new InitializationException( new String[] { "ClustalWFilter: Could not find ClustalW" }); } } public boolean filterProteinSequence(ProteinSequence sequence) { boolean result; try { result = config.getConjunction() == ClustalWRuleConjunction.OR ? false : true; ProteinSequence criteriaSequence = ProteinSequence.parse(config .getSequenceData()); if (sequence.getName().equals(criteriaSequence.getName())) criteriaSequence.setHeader(">copy_of_" + criteriaSequence.getHeader().replaceAll(">", "")); ClustalWOutput output = this.parser.runClustal(criteriaSequence, sequence); for (ClustalWRule rule : config.getRules()) { result = config.getConjunction() == ClustalWRuleConjunction.OR ? result || rule.testOutput(output) : result && rule.testOutput(output); } return result; } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException("ClustalW failed to run:\n" + ex.getMessage()); } } public ClustalWFilterConfiguration getConfig() { return this.config; } public void setConfig(ClustalWFilterConfiguration config) { this.config = config; } }
{ "content_hash": "6c744492c19929a6faa6f4be3c6d6a7e", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 205, "avg_line_length": 40.81927710843374, "alnum_prop": 0.6304604486422668, "repo_name": "wolfgangmeyers/genomalysis", "id": "51e251e2171301a98826f59d90213179666913b0", "size": "3388", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ClustalWTool/src/main/java/org/genomalysis/clustalw/ClustalWFilter.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "433790" }, { "name": "Scala", "bytes": "2347" } ], "symlink_target": "" }
class MovieController < ApplicationController layout "nmdb" before_filter :setup_or_redirect def index respond_to do |format| format.html format.xml { render :xml => @movie.to_specified_data(:xml, params[:richness]) } format.json { render :json => @movie.to_specified_data(:json, params[:richness]) } end end def episodes @episodes = @movie.episodes_sorted.group_by { |x| x.episode_season || "Unknown" } end def keywords keywords = @movie.keywords strong_keywords = @movie.strong_keywords @keywords = (strong_keywords + (keywords - strong_keywords)).sort_by { |x| x.display } end def movie_connections @mcon = @movie.movie_connections.all(:include => [:movie_connection_type, :linked_movie]).group_by { |x| x.type } @mcon.keys.each do |con| @mcon[con] = @mcon[con].sort_by { |x| x.linked_movie.full_year || "zzzzzzzzzzzz" } end end def technicals @technicals = @movie.technicals.group_by { |x| x.key } end def images @images = @movie.tmdb_images @images.delete("id") end def external_links if WikipediaFetcher.page(@movie) @wikipedia_page = WikipediaFetcher.page(@movie) else @wikipedia_page = @movie.display end end def image @image_url = WikipediaFetcher.image(@movie, true) render :partial => 'image' end def image_new query_id = params[:next_query_id].to_i opensearch_id = params[:next_opensearch_id].to_i @next_query_id = query_id @next_opensearch_id = opensearch_id @movie.wikipedia_purge_all @image_url = nil begin @image_url = WikipediaFetcher.image(@movie, true, { :query => query_id, :opensearch => opensearch_id }) rescue WikipediaFetcher::NoMoreDataException if query_id == -1 @next_query_id = 0 @next_opensearch_id = -1 else @next_query_id = nil @next_opensearch_id = nil end else if query_id == -1 @next_query_id = -1 @next_opensearch_id += 1 else @next_query_id += 1 @next_opensearch_id = -1 end end @image_url = true if !@image_url if @image_url render :partial => 'image_new' else render :text => '' end end def new_title render :text => @movie.display end def reset_externals rc = RCache.keys("movie:#{@movie.id}:*") rc.each do |rc_key| RCache.del(rc_key) end redirect_to params[:bounceback] end private def setup_or_redirect if !params[:id] redirect_to :controller => 'search', :action => 'index' return end @movie = Movie.find(params[:id]) @timer = { :start => Time.now } end end
{ "content_hash": "cab43f15087e28fd6a847ccd3a0a3154", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 93, "avg_line_length": 25.901785714285715, "alnum_prop": 0.5698035160289555, "repo_name": "stefanberndtsson/nmdb3", "id": "de08adb01e84a6effb5cadb4d56e52e412d72f23", "size": "2901", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/movie_controller.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "41380" }, { "name": "Ruby", "bytes": "151442" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct template rebind</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../private_node_allocator_v1.html#idp111932200" title="Description"> <link rel="prev" href="../private_node_allocator_v1.html" title="Class template private_node_allocator_v1"> <link rel="next" href="../../operator___idp27460568.html" title="Function template operator=="> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../private_node_allocator_v1.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../private_node_allocator_v1.html#idp111932200"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../../operator___idp27460568.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.private_node_allocator_v1.rebind"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct template rebind</span></h2> <p>boost::private_node_allocator_v1::rebind</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../interprocess/indexes_reference.html#header.boost.interprocess.allocators.private_node_allocator_hpp" title="Header &lt;boost/interprocess/allocators/private_node_allocator.hpp&gt;">boost/interprocess/allocators/private_node_allocator.hpp</a>&gt; </span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> T2<span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="rebind.html" title="Struct template rebind">rebind</a> <span class="special">{</span> <span class="comment">// types</span> <span class="keyword">typedef</span> <a class="link" href="../private_node_allocator_v1.html" title="Class template private_node_allocator_v1">private_node_allocator_v1</a><span class="special">&lt;</span> <span class="identifier">T2</span><span class="special">,</span> <span class="identifier">SegmentManager</span><span class="special">,</span> <span class="identifier">NodesPerBlock</span> <span class="special">&gt;</span> <a name="boost.private_node_allocator_v1.rebind.other"></a><span class="identifier">other</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2005-2012 Ion Gaztanaga<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../private_node_allocator_v1.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../private_node_allocator_v1.html#idp111932200"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../../operator___idp27460568.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "e48570c592458a543fba033cf2e10df1", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 556, "avg_line_length": 84.79629629629629, "alnum_prop": 0.6735094998908059, "repo_name": "yxcoin/yxcoin", "id": "cb73234cecc4774eee5eb908f3c03c14a0073196", "size": "4579", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/boost_1_55_0/doc/html/boost/private_node_allocator_v1/rebind.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "222528" }, { "name": "Batchfile", "bytes": "26447" }, { "name": "C", "bytes": "2572612" }, { "name": "C#", "bytes": "40804" }, { "name": "C++", "bytes": "151033085" }, { "name": "CMake", "bytes": "1741" }, { "name": "CSS", "bytes": "270134" }, { "name": "Cuda", "bytes": "26749" }, { "name": "Fortran", "bytes": "1387" }, { "name": "HTML", "bytes": "151665458" }, { "name": "IDL", "bytes": "14" }, { "name": "JavaScript", "bytes": "132031" }, { "name": "Lex", "bytes": "1231" }, { "name": "M4", "bytes": "29689" }, { "name": "Makefile", "bytes": "1094300" }, { "name": "Max", "bytes": "36857" }, { "name": "NSIS", "bytes": "6041" }, { "name": "Objective-C", "bytes": "11848" }, { "name": "Objective-C++", "bytes": "3755" }, { "name": "PHP", "bytes": "59030" }, { "name": "Perl", "bytes": "28121" }, { "name": "Perl6", "bytes": "2053" }, { "name": "Python", "bytes": "1720604" }, { "name": "QML", "bytes": "593" }, { "name": "QMake", "bytes": "24083" }, { "name": "Rebol", "bytes": "354" }, { "name": "Roff", "bytes": "8039" }, { "name": "Shell", "bytes": "350488" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "13404" }, { "name": "XSLT", "bytes": "687839" }, { "name": "Yacc", "bytes": "18910" } ], "symlink_target": "" }
class CreateRelationships < ActiveRecord::Migration def self.up create_table :relationships do |t| t.integer :from_id t.integer :to_id t.string :relationship_type t.timestamps end end def self.down drop_table :relationships end end
{ "content_hash": "03136d558ad1e9a171321a38119fc68d", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 51, "avg_line_length": 19.785714285714285, "alnum_prop": 0.6714801444043321, "repo_name": "edendevelopment/cfi", "id": "5e49315f671e2f4d379662ddd388d3f34322ebbc", "size": "277", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "db/migrate/20100526135538_create_relationships.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "61287" }, { "name": "PHP", "bytes": "24024" }, { "name": "Ruby", "bytes": "114310" }, { "name": "Shell", "bytes": "48" } ], "symlink_target": "" }
const debug = require('debug'); const log = debug('nums:build-page'); log.log = console.log.bind(console); const pify = require('pify'); const path = require('path'); const fs = require('fs-jetpack'); const loadJsonFile = require('load-json-file'); const writeJsonFile = require('write-json-file'); const inline = pify(require('inline-source')); const minify = require('html-minifier').minify; const store = require('./store'); const page = require('./page.js'); page.loaderOptions = {noCache: true}; const commonData = require('./common-data.js'); async function buildPage({template='dashboard.html', economy='china', outDir=store.publicDir}={}) { const destFile = `${outDir}/${economy}.html`; debug(`Using data file: ${store.filenameFor(economy)}`); const data = await store.getDataFor(economy); const context = Object.assign(commonData, data); let html = await page.render(template, context); if (process.env.NODE_ENV === 'production') { debug(`Inline js and css`); html = await inline(html, { compress: false, rootpath: path.resolve(__dirname, `../public`) }); debug(`Minify html`); html = minify(html, { collapseBooleanAttributes: true, collapseInlineTagWhitespace: true, collapseWhitespace: true, conservativeCollapse: true, removeComments: true, minifyCSS: true, minifyJS: true }); } debug(`HTML file: ${destFile}`); await fs.writeAsync(destFile, html); } if (require.main === module) { buildPage() .catch(err => { console.log(err); }); } module.exports = buildPage;
{ "content_hash": "880575e703885ed780f80c668060a109", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 99, "avg_line_length": 28.963636363636365, "alnum_prop": 0.6629001883239172, "repo_name": "ftc-editorial/numbers", "id": "b3c79dae44f222e436f6acb0f8b0351b69c28132", "size": "1593", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "utils/build-page.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13417" }, { "name": "HTML", "bytes": "9338" }, { "name": "JavaScript", "bytes": "26454" } ], "symlink_target": "" }
<?php /** * ALIPAY API: alipay.offline.market.leads.qrcode.query request * * @author auto create * @since 1.0, 2016-03-24 11:28:21 */ class AlipayOfflineMarketLeadsQrcodeQueryRequest { /** * 地推小二认领了Leads后申请创建开店二维码,提供给商户扫描开店。 **/ private $bizContent; private $apiParas = array(); private $terminalType; private $terminalInfo; private $prodCode; private $apiVersion="1.0"; private $notifyUrl; private $returnUrl; private $needEncrypt=false; public function setBizContent($bizContent) { $this->bizContent = $bizContent; $this->apiParas["biz_content"] = $bizContent; } public function getBizContent() { return $this->bizContent; } public function getApiMethodName() { return "alipay.offline.market.leads.qrcode.query"; } public function setNotifyUrl($notifyUrl) { $this->notifyUrl=$notifyUrl; } public function getNotifyUrl() { return $this->notifyUrl; } public function setReturnUrl($returnUrl) { $this->returnUrl=$returnUrl; } public function getReturnUrl() { return $this->returnUrl; } public function getApiParas() { return $this->apiParas; } public function getTerminalType() { return $this->terminalType; } public function setTerminalType($terminalType) { $this->terminalType = $terminalType; } public function getTerminalInfo() { return $this->terminalInfo; } public function setTerminalInfo($terminalInfo) { $this->terminalInfo = $terminalInfo; } public function getProdCode() { return $this->prodCode; } public function setProdCode($prodCode) { $this->prodCode = $prodCode; } public function setApiVersion($apiVersion) { $this->apiVersion=$apiVersion; } public function getApiVersion() { return $this->apiVersion; } public function setNeedEncrypt($needEncrypt) { $this->needEncrypt=$needEncrypt; } public function getNeedEncrypt() { return $this->needEncrypt; } }
{ "content_hash": "d054ca59a36e9fa5b04805f76acbd938", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 63, "avg_line_length": 16.35593220338983, "alnum_prop": 0.6989637305699482, "repo_name": "sunxguo/aewebapp", "id": "0869114bddbeb86537995b15e496208e9f83cb4a", "size": "1986", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "application/libraries/alipay/aop/request/AlipayOfflineMarketLeadsQrcodeQueryRequest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "32778" }, { "name": "ApacheConf", "bytes": "402" }, { "name": "C#", "bytes": "16603" }, { "name": "CSS", "bytes": "681786" }, { "name": "HTML", "bytes": "1642798" }, { "name": "Java", "bytes": "138935" }, { "name": "JavaScript", "bytes": "5870048" }, { "name": "PHP", "bytes": "3997582" } ], "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_45) on Fri May 31 12:12:36 WEST 2013 --> <TITLE> Uses of Class net.floodlightcontroller.counter.ConcurrentCounter.CountAtom </TITLE> <META NAME="date" CONTENT="2013-05-31"> <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="Uses of Class net.floodlightcontroller.counter.ConcurrentCounter.CountAtom"; } } </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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../net/floodlightcontroller/counter/ConcurrentCounter.CountAtom.html" title="class in net.floodlightcontroller.counter"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</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-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?net/floodlightcontroller/counter//class-useConcurrentCounter.CountAtom.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ConcurrentCounter.CountAtom.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> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>net.floodlightcontroller.counter.ConcurrentCounter.CountAtom</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../net/floodlightcontroller/counter/ConcurrentCounter.CountAtom.html" title="class in net.floodlightcontroller.counter">ConcurrentCounter.CountAtom</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#net.floodlightcontroller.counter"><B>net.floodlightcontroller.counter</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="net.floodlightcontroller.counter"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../net/floodlightcontroller/counter/ConcurrentCounter.CountAtom.html" title="class in net.floodlightcontroller.counter">ConcurrentCounter.CountAtom</A> in <A HREF="../../../../net/floodlightcontroller/counter/package-summary.html">net.floodlightcontroller.counter</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../net/floodlightcontroller/counter/package-summary.html">net.floodlightcontroller.counter</A> with type parameters of type <A HREF="../../../../net/floodlightcontroller/counter/ConcurrentCounter.CountAtom.html" title="class in net.floodlightcontroller.counter">ConcurrentCounter.CountAtom</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;java.util.Queue&lt;<A HREF="../../../../net/floodlightcontroller/counter/ConcurrentCounter.CountAtom.html" title="class in net.floodlightcontroller.counter">ConcurrentCounter.CountAtom</A>&gt;</CODE></FONT></TD> <TD><CODE><B>ConcurrentCounter.</B><B><A HREF="../../../../net/floodlightcontroller/counter/ConcurrentCounter.html#unprocessedCountBuffer">unprocessedCountBuffer</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../net/floodlightcontroller/counter/ConcurrentCounter.CountAtom.html" title="class in net.floodlightcontroller.counter"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</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-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?net/floodlightcontroller/counter//class-useConcurrentCounter.CountAtom.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ConcurrentCounter.CountAtom.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> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{ "content_hash": "f29bcb75c9362fd8556bf365f8d0c56e", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 362, "avg_line_length": 45.855555555555554, "alnum_prop": 0.6543494063484371, "repo_name": "fbotelho-university-code/poseidon", "id": "eb4bf08b97a7b7c929e7b244844534b2225a4e94", "size": "8254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "target/docs/net/floodlightcontroller/counter/class-use/ConcurrentCounter.CountAtom.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "187413" }, { "name": "Java", "bytes": "3322889" }, { "name": "JavaScript", "bytes": "96959" }, { "name": "Python", "bytes": "42427" }, { "name": "Shell", "bytes": "2816" } ], "symlink_target": "" }
namespace mediapipe { constexpr char kLetterboxPaddingTag[] = "LETTERBOX_PADDING"; constexpr char kDetectionsTag[] = "DETECTIONS"; LocationData CreateRelativeLocationData(double xmin, double ymin, double width, double height) { LocationData location_data; location_data.set_format(LocationData::RELATIVE_BOUNDING_BOX); location_data.mutable_relative_bounding_box()->set_xmin(xmin); location_data.mutable_relative_bounding_box()->set_ymin(ymin); location_data.mutable_relative_bounding_box()->set_width(width); location_data.mutable_relative_bounding_box()->set_height(height); return location_data; } Detection CreateDetection(const std::vector<std::string>& labels, const std::vector<int32>& label_ids, const std::vector<float>& scores, const LocationData& location_data, const std::string& feature_tag) { Detection detection; for (const auto& label : labels) { detection.add_label(label); } for (const auto& label_id : label_ids) { detection.add_label_id(label_id); } for (const auto& score : scores) { detection.add_score(score); } *(detection.mutable_location_data()) = location_data; detection.set_feature_tag(feature_tag); return detection; } CalculatorGraphConfig::Node GetDefaultNode() { return ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb( calculator: "DetectionLetterboxRemovalCalculator" input_stream: "DETECTIONS:detections" input_stream: "LETTERBOX_PADDING:letterbox_padding" output_stream: "DETECTIONS:adjusted_detections" )pb"); } TEST(DetectionLetterboxRemovalCalculatorTest, PaddingLeftRight) { CalculatorRunner runner(GetDefaultNode()); LocationData location_data = CreateRelativeLocationData(0.25f, 0.25f, 0.25f, 0.25f); const std::string label = "detected_object"; auto detections = absl::make_unique<std::vector<Detection>>(); detections->push_back( CreateDetection({label}, {}, {0.3f}, location_data, "feature_tag")); runner.MutableInputs() ->Tag(kDetectionsTag) .packets.push_back( Adopt(detections.release()).At(Timestamp::PostStream())); auto padding = absl::make_unique<std::array<float, 4>>( std::array<float, 4>{0.2f, 0.f, 0.3f, 0.f}); runner.MutableInputs() ->Tag(kLetterboxPaddingTag) .packets.push_back(Adopt(padding.release()).At(Timestamp::PostStream())); MP_ASSERT_OK(runner.Run()) << "Calculator execution failed."; const std::vector<Packet>& output = runner.Outputs().Tag(kDetectionsTag).packets; ASSERT_EQ(1, output.size()); const auto& output_detections = output[0].Get<std::vector<Detection>>(); EXPECT_EQ(output_detections.size(), 1); const auto& output_detection = output_detections[0]; EXPECT_EQ(output_detection.label_size(), 1); EXPECT_EQ(output_detection.label(0), label); EXPECT_EQ(output_detection.label_id_size(), 0); EXPECT_EQ(output_detection.score_size(), 1); EXPECT_EQ(output_detection.score(0), 0.3f); EXPECT_EQ(output_detection.location_data().format(), LocationData::RELATIVE_BOUNDING_BOX); EXPECT_THAT(output_detection.location_data().relative_bounding_box().xmin(), testing::FloatNear(0.1f, 1e-5)); EXPECT_THAT(output_detection.location_data().relative_bounding_box().ymin(), testing::FloatNear(0.25f, 1e-5)); EXPECT_THAT(output_detection.location_data().relative_bounding_box().width(), testing::FloatNear(0.5f, 1e-5)); EXPECT_THAT(output_detection.location_data().relative_bounding_box().height(), testing::FloatNear(0.25f, 1e-5)); } TEST(DetectionLetterboxRemovalCalculatorTest, PaddingTopBottom) { CalculatorRunner runner(GetDefaultNode()); LocationData location_data = CreateRelativeLocationData(0.25f, 0.25f, 0.25f, 0.25f); const std::string label = "detected_object"; auto detections = absl::make_unique<std::vector<Detection>>(); detections->push_back( CreateDetection({label}, {}, {0.3f}, location_data, "feature_tag")); runner.MutableInputs() ->Tag(kDetectionsTag) .packets.push_back( Adopt(detections.release()).At(Timestamp::PostStream())); auto padding = absl::make_unique<std::array<float, 4>>( std::array<float, 4>{0.f, 0.2f, 0.f, 0.3f}); runner.MutableInputs() ->Tag(kLetterboxPaddingTag) .packets.push_back(Adopt(padding.release()).At(Timestamp::PostStream())); MP_ASSERT_OK(runner.Run()) << "Calculator execution failed."; const std::vector<Packet>& output = runner.Outputs().Tag(kDetectionsTag).packets; ASSERT_EQ(1, output.size()); const auto& output_detections = output[0].Get<std::vector<Detection>>(); EXPECT_EQ(output_detections.size(), 1); const auto& output_detection = output_detections[0]; EXPECT_EQ(output_detection.location_data().format(), LocationData::RELATIVE_BOUNDING_BOX); EXPECT_THAT(output_detection.location_data().relative_bounding_box().xmin(), testing::FloatNear(0.25f, 1e-5)); EXPECT_THAT(output_detection.location_data().relative_bounding_box().ymin(), testing::FloatNear(0.1f, 1e-5)); EXPECT_THAT(output_detection.location_data().relative_bounding_box().width(), testing::FloatNear(0.25f, 1e-5)); EXPECT_THAT(output_detection.location_data().relative_bounding_box().height(), testing::FloatNear(0.5f, 1e-5)); } } // namespace mediapipe
{ "content_hash": "de9802d950d34212fe36f9cfd93f091d", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 80, "avg_line_length": 40.55882352941177, "alnum_prop": 0.6792965917331399, "repo_name": "google/mediapipe", "id": "c4f0843634190a6e0bc31cec4d6d67bfc582d879", "size": "6629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mediapipe/calculators/util/detection_letterbox_removal_calculator_test.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "514" }, { "name": "C", "bytes": "76928" }, { "name": "C++", "bytes": "10897312" }, { "name": "Dockerfile", "bytes": "2659" }, { "name": "HTML", "bytes": "4090" }, { "name": "Java", "bytes": "1151252" }, { "name": "JavaScript", "bytes": "6380" }, { "name": "Makefile", "bytes": "1625" }, { "name": "Objective-C", "bytes": "125458" }, { "name": "Objective-C++", "bytes": "131706" }, { "name": "Python", "bytes": "1272093" }, { "name": "Shell", "bytes": "19580" }, { "name": "Starlark", "bytes": "1277085" }, { "name": "TypeScript", "bytes": "169026" } ], "symlink_target": "" }
package org.deepjava.runtime.util; import java.io.IOException; /* Changes: * 04.06.2014 Urs Graf exception added * 01.04.2008 NTB/SP error states added * 28.09.2007 NTB/SP creation */ /** * First in first out <code>byte</code> queue. * The size of the queue should be a multiple of 2 minus one (size = 2^x - 1). */ public class ByteFifo { byte[] data; int head, tail; int size; /** * Creates a new <code>ByteFifo</code> with <code>size</code> entries. * * @param size The size of the queue (size = 2^x - 1) */ public ByteFifo(int size) { data = new byte[size + 1]; this.size = size; } /** * Inserts one <code>byte</code> into the queue. * @param data <code>Byte</code> which will be inserted into the queue */ public void enqueue(byte data) { if (availToWrite() > 0) { this.data[tail] = data; tail = (tail + 1) % this.data.length; } } /** * Removes one <code>byte</code> from the queue. * @return The removed byte. * @throws IOException * if reading from an empty queue. */ public byte dequeue() throws IOException { if (head != tail) { byte c= data[head]; head = (head + 1) % data.length; return c; } else throw new IOException("IOException"); } /** * Clears the queue. */ public void clear() { head = tail; } /** * Reads the available entries in the queue. * * @return The available <code>bytes</code> to read. */ public int availToRead() { int len = tail - head; if(len < 0) return data.length + len; return len; } /** * Reads the available space left in the queue. * * @return The available queue space. */ public int availToWrite() { int len = tail - head; if(len < 0) len = data.length + len; return size - len; } /** * Reads the maximum number of entries in the queue. * * @return The size of the queue. */ public int getSize() { return size; } }
{ "content_hash": "c9eef9f8ac4022bf5eb8c67bbab6c26c", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 78, "avg_line_length": 20.9375, "alnum_prop": 0.5850746268656717, "repo_name": "deepjava/runtime-library", "id": "615a3e7a6323d9fbdb55e3bc005747a10378d27b", "size": "2714", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/deepjava/runtime/util/ByteFifo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1365433" } ], "symlink_target": "" }
package microsoft.exchange.webservices.data; /** * Represents an EmptyFolder request. */ final class EmptyFolderRequest extends DeleteRequest<ServiceResponse> { private FolderIdWrapperList folderIds = new FolderIdWrapperList(); private boolean deleteSubFolders; /** * Initializes a new instance of the EmptyFolderRequest class. * * @param service The service. * @param errorHandlingMode Indicates how errors should be handled. * @throws Exception */ protected EmptyFolderRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode) throws Exception { super(service, errorHandlingMode); } /** * Validates request. * * @throws Exception * @throws ServiceLocalException */ @Override protected void validate() throws ServiceLocalException, Exception { super.validate(); EwsUtilities.validateParam(this.getFolderIds(), "FolderIds"); this.getFolderIds().validate(this.getService(). getRequestedServerVersion()); } /** * Gets the expected response message count. * * @return Number of expected response messages.</returns> */ @Override protected int getExpectedResponseMessageCount() { return this.getFolderIds().getCount(); } /** * Creates the service response. * * @param service The service. * @param responseIndex Index of the response. * @return Service object */ @Override protected ServiceResponse createServiceResponse(ExchangeService service, int responseIndex) { return new ServiceResponse(); } /** * Gets the name of the XML element. * * @return XML element name. */ @Override protected String getXmlElementName() { return XmlElementNames.EmptyFolder; } /** * Gets the name of the response XML element. * * @return XML element name. */ @Override protected String getResponseXmlElementName() { return XmlElementNames.EmptyFolderResponse; } /** * Gets the name of the response message XML element. * * @return XML element name. */ @Override protected String getResponseMessageXmlElementName() { return XmlElementNames.EmptyFolderResponseMessage; } /** * Writes XML elements. * * @param writer The writer. * @throws Exception */ @Override protected void writeElementsToXml(EwsServiceXmlWriter writer) throws Exception { this.getFolderIds().writeToXml( writer, XmlNamespace.Messages, XmlElementNames.FolderIds); } /** * Writes XML attributes. * * @param writer The writer. * @throws ServiceXmlSerializationException */ @Override protected void writeAttributesToXml(EwsServiceXmlWriter writer) throws ServiceXmlSerializationException { super.writeAttributesToXml(writer); writer.writeAttributeValue(XmlAttributeNames.DeleteSubFolders, this.deleteSubFolders); } /** * Gets the request version. * * @return Earliest Exchange version * in which this request is supported. */ @Override protected ExchangeVersion getMinimumRequiredServerVersion() { return ExchangeVersion.Exchange2010_SP1; } /** * Gets the folder ids. * * @return The folder ids. */ protected FolderIdWrapperList getFolderIds() { return this.folderIds; } /** * Gets a value indicating whether empty * folder should also delete sub folders. * * @value true if empty folder should also * delete sub folders, otherwise false. */ protected boolean getDeleteSubFolders() { return deleteSubFolders; } /** * Sets a value indicating whether empty * folder should also delete sub folders. * * @value true if empty folder should also * delete sub folders, otherwise false. */ protected void setDeleteSubFolders(boolean value) { this.deleteSubFolders = value; } }
{ "content_hash": "cec266ba38cf12b94800f250bc5531a1", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 74, "avg_line_length": 23.70731707317073, "alnum_prop": 0.691358024691358, "repo_name": "evpaassen/ews-java-api", "id": "b171427768d9804ffd8f9ce96f06a34126e599b3", "size": "5170", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/microsoft/exchange/webservices/data/EmptyFolderRequest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "3540337" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>Provision Monitor Configuration</title> </head> <body> Provides the capability to deploy and monitor applications.<br> <h2><big> <small><a name="Configuring_ProvisionMonitor"></a>Configuring ProvisionMonitor </small> </big></h2> The ProvisionMonitor package supports the following configuration entries; where each configuration entry name is associated with the component name <span style="font-family: monospace;">org.rioproject.monitor</span><code></code><br> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">initialLookupGroups</span><br style="font-weight: bold; font-family: courier new,courier,monospace;"> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">String[]<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">All groups<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">This entry will be read at initialization by a ProvisionMonitor to determine the initial set of multicast discovery groups the ProvisionMonitor should participate in. Any future changes to the set of discovery groups should be made via ProvisionMonitor 's admin proxy using the <code>JoinAdmin</code> interface. </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">initialLookupLocators</span><br style="font-weight: bold; font-family: courier new,courier,monospace;"> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">LookupLocator[]<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">null<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">This entry will be read at initialization by a ProvisionMonitor to determine the initial set of specific lookup services the ProvisionMonitor should register with. Any future changes to the set of discovery groups should be made via ProvisionMonitor 's admin proxy using the <code>JoinAdmin</code> interface. </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">initialOpStrings</span> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">String[]<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">none<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">An array of OperationalString files. The OperationalString file(s) will be loaded and managed at startup. Example :<br> <span style="font-family: monospace;">&nbsp;String[] getInitialOpStrings() {</span><br style="font-family: monospace;"> <span style="font-family: monospace;">&nbsp;&nbsp;&nbsp; def opstrings = ["../config/system.groovy"]</span><br style="font-family: monospace;"> <span style="font-family: monospace;">&nbsp;&nbsp;&nbsp; return opstrings as String[]</span><br style="font-family: monospace;"> <span style="font-family: monospace;">}</span><br> </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">initialOpStringLoadDelay</span> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">long<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">5 seconds<span style="font-weight: bold;"><br> </span></td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">The amount of time (in milliseconds) to wait to load OperationalString files declared in the initialOpStrings property.<br> </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">deployHandlers</span> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">{@link org.rioproject.monitor.handlers.DeployHandler}<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">new DeployHandler[]{new FileSystemOARDeployHandler(new File("${RIO_HOME}/deploy"))<span style="font-weight: bold;"> </span></td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">This property is read at startup and defines the DeployHandler instances that will be used by the Provision Monitor. DeployHandler instances are polled at fixed intervals to return OperationalStrings to deploy. The default&nbsp;DeployHandler is the FileSystemOARDeployHandler. This DeployHandler is used to enable hot deployment of OARs. The FileSystemOARDeployHandler looks for files with a "oar" extension, installs and unarchives the OAR, and returns configured OperationalStrings for OARs.<br> </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">deployMonitorPeriod</span> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;"><span style="font-weight: bold;">long</span></td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">30 seconds<span style="font-weight: bold;"><br> </span></td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">This property is read at startup and defines the amount of time (in milliseconds) the DeployMonitor will poll {@link org.rioproject.monitor.handlers.DeployHandler} instances for OperationalString deployments. Setting this value to -1 disables hot deployment of OARs. </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">installDir</span> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">String<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">${RIO_HOME}/deploy<span style="font-weight: bold;"><br> </span></td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">This property is read at startup and defines the directory path that is used to install and service deployed OARs and application<br> resources. OARs are installed to a subdirectory (as per the rules of OAR-Name) and extracted. If this directory does not exist it will be created.<br> </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">loginContext</span><br style="font-weight: bold; font-family: courier new,courier,monospace;"> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">LoginContext<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;"> Do not perform JAAS login</td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;"> Specifies the JAAS login context to use for performing a JAAS login and supplying the <code>Subject</code> to use when running the service. If this entry is not specified, no JAAS login is performed. This entry is obtained at service start and restart. </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">logDirectory</span><br style="font-weight: bold; font-family: courier new,courier,monospace;"> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">String<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">none<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">If the a log directory is being used, the value of this entry is the name of the directory that will be used to persist the ProvisionMonitor's state.&nbsp;<br> </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">opStringName</span><br style="font-weight: bold; font-family: courier new,courier,monospace;"> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">String<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">"System-Core"<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">The name of the OperationalString the ProvisionMonitor is a part of<br> </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">opStringManagerExporter</span> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">Exporter</td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">A new <code style="font-family: monospace;">BasicJeriExporter</code><span style="font-family: monospace;"> </span>with <ul> <li>a <code>TcpServerEndpoint</code> created on a random port, </li> <li>a <code>BasicILFactory</code>,</li> <li>distributed garbage collection turned off,</li> <li>keep alive on.</li> </ul> <br> <code></code></td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">The exporter used to export the OpStringManager. The OpStringManager is a remote object which manages OperationalString instances. A new exporter is obtained every time an OpStringManager needs to export itself. </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">serviceComment</span><br style="font-weight: bold; font-family: courier new,courier,monospace;"> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">String<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">null</td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">The comment the ProvisionMonitor will use to construct a Comment Entry<br> </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">serverExporter</span><br style="font-family: courier new,courier,monospace;"> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">Exporter</td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">A new <code>BasicJeriExporter</code> with <ul> <li>a <code>TcpServerEndpoint</code> created on a random port, </li> <li>a <code>BasicILFactory</code>,</li> <li>distributed garbage collection turned off,</li> <li>keep alive on.</li> </ul> <code></code> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">The exporter used to export the server. A new exporter is obtained every time a ProvisionMonitorImpl needs to export itself. </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">serviceName</span><br style="font-weight: bold; font-family: courier new,courier,monospace;"> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">String<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">ProvisionMonitor<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">The name the ProvisionMonitor should use as a Name Entry, and for display purposes<br> </td> </tr> </tbody> </table> </li> </ul> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">serviceResourceSelector<br> </span> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">ServiceResourceSelector</td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">RoundRobinSelector<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">The ServiceResourceSelector provides a mechanism to select Cybernodes in a particular fashion<br> </td> </tr> </tbody> </table> <span style="font-weight: bold;"><br> </span></li> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">instantiatorPreparer</span><br style="font-weight: bold; font-family: courier new,courier,monospace;"> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;">ProxyPreparer<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">An instance of <code>BasicProxyPreparer</code> that does nothing </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;">ProxyPreparer for ServiceInstantiator proxies. The preparer should expect the net.jini.core.event.RemoteEventListener.notify method on the returned proxy. </td> </tr> </tbody> </table> </li> </ul> <span style="font-weight: bold; font-family: courier new,courier,monospace;"></span> <ul> <li><span style="font-weight: bold; font-family: courier new,courier,monospace;">provisioner</span><font style="font-weight: bold;" size="+1"><code>LeasePeriodPolicy</code></font> <table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Type:<br> </td> <td style="vertical-align: top;"> com.sun.jini.landlord.LeasePeriodPolicy </td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Default:<br> </td> <td style="vertical-align: top;">5 minutes<br> A new <code></code>com.sun.jini.landlord.FixedLeasePeriodPolicy that allows leases up to 10 minutes with a default lease grant of 5 minutes<br> <span style="font-weight: bold;"> </span></td> </tr> <tr> <td style="vertical-align: top; text-align: right; font-weight: bold;"> Description:<br> </td> <td style="vertical-align: top;"> Policy used to determine the length of initial grants and renewals of the leases for ServiceInstantiator instances </td> </tr> </tbody> </table> </li> </ul> </body> </html>
{ "content_hash": "0c66a2baf8a4dc0aecd51e23a8ab85df", "timestamp": "", "source": "github", "line_count": 657, "max_line_length": 93, "avg_line_length": 39.63470319634703, "alnum_prop": 0.49078341013824883, "repo_name": "khartig/assimilator", "id": "5a8f7f5fe300286820244b0f6dede14d9abc9871", "size": "26040", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rio-services/monitor/monitor-service/src/main/java/org/rioproject/monitor/package.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8852" }, { "name": "CSS", "bytes": "2456" }, { "name": "Groovy", "bytes": "409606" }, { "name": "HTML", "bytes": "279722" }, { "name": "Java", "bytes": "5257555" }, { "name": "Shell", "bytes": "14035" } ], "symlink_target": "" }
package org.antkar.syn.sample.script.rt.value; import org.antkar.syn.sample.script.rt.SynsException; import org.antkar.syn.sample.script.rt.javacls.TypeMatchPrecision; import org.antkar.syn.sample.script.rt.op.operand.Operand; /** * A value of type <code>long</code>. */ final class LongValue extends RValue { private final long value; LongValue(long value) { this.value = value; } @Override public Operand toOperand() throws SynsException { return Operand.forLong(this, value); } @Override public ValueType getValueType() { return ValueType.LONG; } @Override public Object toJava(Class<?> type, TypeMatchPrecision precision) { if (long.class.equals(type)) { precision.increment(2); return Long.valueOf(value); } else if (float.class.equals(type)) { return Float.valueOf(value); } else if (double.class.equals(type)) { return Double.valueOf(value); } else if (type.isAssignableFrom(Long.class)) { return value; } return INVALID; } }
{ "content_hash": "cc717100e9746bd62bbcca87d41d7cf5", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 71, "avg_line_length": 26.714285714285715, "alnum_prop": 0.6345811051693404, "repo_name": "antkar/syn", "id": "874613a987e73ef7298278b2f9085b3b25803057", "size": "1719", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "syn-sample-script/src/main/java/org/antkar/syn/sample/script/rt/value/LongValue.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "351" }, { "name": "Java", "bytes": "1197844" }, { "name": "Shell", "bytes": "370" } ], "symlink_target": "" }
package org.elasticsearch.test.action.search; import org.apache.logging.log4j.Logger; import org.elasticsearch.action.OriginalIndices; import org.elasticsearch.action.search.SearchPhase; import org.elasticsearch.action.search.SearchPhaseContext; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchShardIterator; import org.elasticsearch.action.search.SearchTask; import org.elasticsearch.action.search.SearchTransportService; import org.elasticsearch.action.search.ShardSearchFailure; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.search.SearchShardTarget; import org.elasticsearch.search.InternalSearchResponse; import org.elasticsearch.search.ShardSearchTransportRequest; import org.elasticsearch.transport.Transport; import org.junit.Assert; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * SearchPhaseContext for tests */ public final class MockSearchPhaseContext implements SearchPhaseContext { private static final Logger logger = Loggers.getLogger(MockSearchPhaseContext.class); public AtomicReference<Throwable> phaseFailure = new AtomicReference<>(); final int numShards; final AtomicInteger numSuccess; List<ShardSearchFailure> failures = Collections.synchronizedList(new ArrayList<>()); SearchTransportService searchTransport; Set<Long> releasedSearchContexts = new HashSet<>(); SearchRequest searchRequest = new SearchRequest(); AtomicInteger phasesExecuted = new AtomicInteger(); public MockSearchPhaseContext(int numShards) { this.numShards = numShards; numSuccess = new AtomicInteger(numShards); } public void assertNoFailure() { if (phaseFailure.get() != null) { throw new AssertionError(phaseFailure.get()); } } @Override public int getNumShards() { return numShards; } @Override public Logger getLogger() { return logger; } @Override public SearchTask getTask() { return new SearchTask(0, "n/a", "n/a", "test", null, Collections.emptyMap()); } @Override public SearchRequest getRequest() { return searchRequest; } @Override public SearchResponse buildSearchResponse(InternalSearchResponse internalSearchResponse, String scrollId) { return new SearchResponse(internalSearchResponse, scrollId, numShards, numSuccess.get(), 0, 0, failures.toArray(new ShardSearchFailure[failures.size()]), SearchResponse.Clusters.EMPTY); } @Override public void onPhaseFailure(SearchPhase phase, String msg, Throwable cause) { phaseFailure.set(cause); } @Override public void onShardFailure(int shardIndex, @Nullable SearchShardTarget shardTarget, Exception e) { failures.add(new ShardSearchFailure(e, shardTarget)); numSuccess.decrementAndGet(); } @Override public Transport.Connection getConnection(String clusterAlias, String nodeId) { return null; // null is ok here for this test } @Override public SearchTransportService getSearchTransport() { Assert.assertNotNull(searchTransport); return searchTransport; } @Override public ShardSearchTransportRequest buildShardSearchRequest(SearchShardIterator shardIt) { Assert.fail("should not be called"); return null; } @Override public void executeNextPhase(SearchPhase currentPhase, SearchPhase nextPhase) { phasesExecuted.incrementAndGet(); try { nextPhase.run(); } catch (Exception e) { onPhaseFailure(nextPhase, "phase failed", e); } } @Override public void execute(Runnable command) { command.run(); } @Override public void onResponse(SearchResponse response) { Assert.fail("should not be called"); } @Override public void onFailure(Exception e) { Assert.fail("should not be called"); } @Override public void sendReleaseSearchContext(long contextId, Transport.Connection connection, OriginalIndices originalIndices) { releasedSearchContexts.add(contextId); } }
{ "content_hash": "2f4eef69bdcbf62fe81b0e8a74016c7a", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 124, "avg_line_length": 32.427536231884055, "alnum_prop": 0.7280446927374302, "repo_name": "jprante/elasticsearch-server", "id": "fe4d81e3f28ecaa3f2538abb7650537ed4e5c651", "size": "5263", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/test/java/org/elasticsearch/test/action/search/MockSearchPhaseContext.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "36898894" }, { "name": "Shell", "bytes": "1939" } ], "symlink_target": "" }
package biz.paluch.spinach.commands.rx; import biz.paluch.spinach.commands.QueueCommandTest; import org.junit.Before; /** * @author Mark Paluch */ public class RxQueueCommandTest extends QueueCommandTest { @Before public void openConnection() throws Exception { disque = RxSyncInvocationHandler.sync(client.connect()); disque.debugFlushall(); } }
{ "content_hash": "9cbb3e412f995eab84e83cd2eabe62c4", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 64, "avg_line_length": 22.41176470588235, "alnum_prop": 0.7270341207349081, "repo_name": "mp911de/spinach", "id": "10d1cd6a4ba01b7e272903c4556e75a953c72af1", "size": "996", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/biz/paluch/spinach/commands/rx/RxQueueCommandTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "390956" }, { "name": "Makefile", "bytes": "3781" } ], "symlink_target": "" }
package de.tudarmstadt.ukp.clarin.webanno.api.annotation.coloring; import java.util.ArrayList; import java.util.List; public class ColoringUtils { public static boolean isTooLight(String aColor, int aThreshold) { // http://24ways.org/2010/calculating-color-contrast/ // http://stackoverflow.com/questions/11867545/change-text-color-based-on-brightness-of-the-covered-background-area int r = Integer.valueOf(aColor.substring(1, 3), 16); int g = Integer.valueOf(aColor.substring(3, 5), 16); int b = Integer.valueOf(aColor.substring(5, 7), 16); int yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000; return yiq > aThreshold; } /** * Filter out too light colors from the palette - those that do not show propely on a ligth * background. The threshold controls what to filter. * * @param aPalette * the palette. * @param aThreshold * the lightness threshold (0 = black, 255 = white) * @return the filtered palette. */ public static String[] filterLightColors(String[] aPalette, int aThreshold) { List<String> filtered = new ArrayList<>(); for (String color : aPalette) { if (!isTooLight(color, aThreshold)) { filtered.add(color); } } return filtered.toArray(new String[filtered.size()]); } }
{ "content_hash": "7eb7a656d2af1a730d77cc4ccd62b4a3", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 123, "avg_line_length": 35.325, "alnum_prop": 0.6171266808209483, "repo_name": "webanno/webanno", "id": "5d9ec634c2efbecbcd5c91b44ef2e05dfa2d04d4", "size": "2208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webanno-api-annotation/src/main/java/de/tudarmstadt/ukp/clarin/webanno/api/annotation/coloring/ColoringUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25786" }, { "name": "Dockerfile", "bytes": "907" }, { "name": "HTML", "bytes": "235442" }, { "name": "Java", "bytes": "4907056" }, { "name": "JavaScript", "bytes": "532072" }, { "name": "SCSS", "bytes": "48472" }, { "name": "Shell", "bytes": "3808" } ], "symlink_target": "" }
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # 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. # __revision__ = "test/DVIPS/PSCOMSTR.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" """ Test that the $PSCOMSTR construction variable allows you to customize the displayed string when is called. """ import TestSCons _python_ = TestSCons._python_ test = TestSCons.TestSCons() test.write('myps.py', """ import sys outfile = open(sys.argv[1], 'wb') for f in sys.argv[2:]: infile = open(f, 'rb') for l in [l for l in infile.readlines() if l != '/*ps*/\\n']: outfile.write(l) sys.exit(0) """) test.write('SConstruct', """ env = Environment(tools=['default', 'dvips'], PSCOM = r'%(_python_)s myps.py $TARGET $SOURCES', PSCOMSTR = 'PostScripting $TARGET from $SOURCE') env.PostScript(target = 'aaa', source = 'aaa.dvi') """ % locals()) test.write('aaa.dvi', "aaa.dvi\n/*ps*/\n") test.run(stdout = test.wrap_stdout("""\ PostScripting aaa.ps from aaa.dvi """)) test.must_match('aaa.ps', "aaa.dvi\n") test.pass_test() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
{ "content_hash": "f8222ad4e24d7dd685d864011141fff0", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 96, "avg_line_length": 30.575342465753426, "alnum_prop": 0.7056451612903226, "repo_name": "EmanueleCannizzaro/scons", "id": "7d100859a79783cd996d29102accda370e4bf37c", "size": "2232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/DVIPS/PSCOMSTR.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2491" }, { "name": "C", "bytes": "659" }, { "name": "C++", "bytes": "598" }, { "name": "CSS", "bytes": "18502" }, { "name": "D", "bytes": "1997" }, { "name": "HTML", "bytes": "817651" }, { "name": "Java", "bytes": "6860" }, { "name": "JavaScript", "bytes": "215495" }, { "name": "Makefile", "bytes": "3795" }, { "name": "Perl", "bytes": "29978" }, { "name": "Python", "bytes": "7510453" }, { "name": "Roff", "bytes": "556545" }, { "name": "Ruby", "bytes": "11074" }, { "name": "Shell", "bytes": "52682" }, { "name": "XSLT", "bytes": "7567242" } ], "symlink_target": "" }
<!doctype html> <html ng-app="demoApp"> <head> <meta charset="utf-8"> <title>demoApp</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <!-- build:css({.tmp/serve,src}) styles/vendor.css --> <!-- bower:css --> <!-- run `gulp inject` to automatically populate bower styles dependencies --> <!-- endbower --> <!-- endbuild --> <!-- build:css({.tmp/serve,src}) styles/app.css --> <!-- inject:css --> <!-- css files will be automatically insert here --> <!-- endinject --> <!-- endbuild --> </head> <body> <!--[if lt IE 10]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <!-- WRAPPER --> <div class="wrapper"> <div ui-view class="main"></div> </div> <!-- build:js(src) scripts/vendor.js --> <!-- bower:js --> <!-- run `gulp inject` to automatically populate bower script dependencies --> <!-- endbower --> <!-- endbuild --> <!-- build:js({.tmp/serve,.tmp/partials,src}) scripts/app.js --> <!-- inject:js --> <!-- js files will be automatically insert here --> <!-- endinject --> <!-- inject:partials --> <!-- angular templates will be automatically converted in js and inserted here --> <!-- endinject --> <!-- endbuild --> <!-- Add the configuration --> <script src="config.js"></script> </body> </html>
{ "content_hash": "f569466a651ce7b20f15ee8acab090c4", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 178, "avg_line_length": 33.183673469387756, "alnum_prop": 0.5738007380073801, "repo_name": "edwinanciani/demo-app", "id": "9932cd6aa6b570bf49a899c27d3beaf68e642361", "size": "1626", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1938" }, { "name": "HTML", "bytes": "9213" }, { "name": "JavaScript", "bytes": "41422" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Schr. naturf. Ges. Leipzig 1: 128 (1822) #### Original name Dematium smilacis Schwein. ### Remarks null
{ "content_hash": "aa0aa2bcb65bd13a780cd20da9c49849", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 40, "avg_line_length": 12.846153846153847, "alnum_prop": 0.7005988023952096, "repo_name": "mdoering/backbone", "id": "c5daaad0832b685793a5835aecc2a8d118e6da7d", "size": "217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dematium/Dematium smilacis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.spring.rest.controllers; import com.spring.core.event.productreview.*; import com.spring.core.service.productreview.ProductReviewEventHandler; import com.spring.rest.resources.ProductReview; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.sql.Date; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; /** * @author vahid hosseinzadeh * @version 1.0 * @since 1.0 **/ @RestController @RequestMapping(value = "/rest/products/{pid}/reviews") public class ProductReviewController { @Autowired private final ProductReviewEventHandler handler; @Autowired public ProductReviewController(ProductReviewEventHandler handler) { this.handler = handler; } /* * Get all reviews of requested product * */ @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Callable<HttpEntity<List<ProductReview>>> getProductReviewsByProduct(@PathVariable final long pid, @PageableDefault(page = 0, size = 10 , sort = "date" , direction = Sort.Direction.DESC) final Pageable pageable) { return new Callable<HttpEntity<List<ProductReview>>>() { @Override public ResponseEntity<List<ProductReview>> call() throws Exception { List<ProductReviewDetails> detailsList = handler.requestAllProductReviewsDetailsByProduct( new RequestAllProductReviewsDetailsByProductEvent(pid, pageable) ).getProductReviewDetailsList(); List<ProductReview> resourceList = new ArrayList<>(); for (ProductReviewDetails details : detailsList) { ProductReview resource = new ProductReview(details); resource.add(linkTo(methodOn(ProductReviewController.class).getProductReviewDetails(pid, details.getId())).withSelfRel()); resource.add(linkTo(methodOn(ProductController.class).getProductDetails(pid,details.getProduct())).withRel("product")); resourceList.add(resource); } return new ResponseEntity<>(resourceList, HttpStatus.OK); } }; } @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, value = "/{id}") public @ResponseBody Callable<HttpEntity<ProductReview>> getProductReviewDetails(@PathVariable final long pid, @PathVariable final long id) { return new Callable<HttpEntity<ProductReview>>() { @Override public ResponseEntity<ProductReview> call() throws Exception { ProductReviewDetails details = handler.requestProductReviewDetails(new RequestProductReviewDetailsEvent(id)).getProductReviewDetails(); ProductReview resource = new ProductReview(details); resource.add(linkTo(methodOn(ProductReviewController.class).getProductReviewDetails(pid, id)).withSelfRel()); resource.add(linkTo(methodOn(ProductController.class).getProductDetails(pid,details.getProduct())).withRel("product")); return new ResponseEntity<>(resource, HttpStatus.OK); } }; } @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Callable<HttpEntity<ProductReview>> createProductReview(@PathVariable final long pid, final @RequestParam(required = true) String review, final @RequestParam(required = true) String name, final @RequestParam(required = true) String email, final @RequestParam(required = true) long product ) { return new Callable<HttpEntity<ProductReview>>() { @Override public ResponseEntity<ProductReview> call() throws Exception { ProductReviewDetails details = new ProductReviewDetails(); DateTime dateTime = new DateTime(); details.setDate((Date) dateTime.toDate()); details.setReview(review); details.setName(name); details.setEmail(email); details.setProduct(product); ProductReviewCreatedEvent customerCreatedEvent = handler.createProductReview(new CreateProductReviewEvent(details)); ProductReview resource = new ProductReview(customerCreatedEvent.getProductReviewDetails()); resource.add(linkTo(methodOn(ProductReviewController.class).getProductReviewDetails(pid, customerCreatedEvent.getProductReviewDetails().getId())).withSelfRel()); resource.add(linkTo(methodOn(ProductController.class).getProductDetails(pid,details.getProduct())).withRel("product")); return new ResponseEntity<>(resource, HttpStatus.OK); } }; } @RequestMapping(method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE, value = "/{id}") public @ResponseBody Callable<HttpEntity<ProductReview>> updateProductReview(final @PathVariable long pid, final @PathVariable long id, final @RequestParam(required = true) String review, final @RequestParam(required = true) String name, final @RequestParam(required = true) String email ) { return new Callable<HttpEntity<ProductReview>>() { @Override public ResponseEntity<ProductReview> call() throws Exception { ProductReviewDetails details = new ProductReviewDetails(); DateTime dateTime = new DateTime(); details.setDate((Date) dateTime.toDate()); details.setId(id); details.setReview(review); details.setName(name); details.setEmail(email); ProductReviewUpdatedEvent customerUpdatedEvent = handler.updateProductReview(new UpdateProductReviewEvent(id, details)); ProductReview resource = new ProductReview(customerUpdatedEvent.getProductReviewDetails()); resource.add(linkTo(methodOn(ProductReviewController.class).getProductReviewDetails(pid, customerUpdatedEvent.getProductReviewDetails().getId())).withSelfRel()); resource.add(linkTo(methodOn(ProductController.class).getProductDetails(pid,details.getProduct())).withRel("product")); return new ResponseEntity<>(resource, HttpStatus.OK); } }; } @RequestMapping(method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE, value = "/{id}") public @ResponseBody Callable<HttpEntity<ProductReview>> deleteProductReview(@PathVariable final long pid, @PathVariable final long id) { return new Callable<HttpEntity<ProductReview>>() { @Override public ResponseEntity<ProductReview> call() throws Exception { ProductReviewDeletedEvent customerDeletedEvent = handler.deleteProductReview(new DeleteProductReviewEvent(id)); ProductReview resource = new ProductReview(customerDeletedEvent.getProductReviewDetails()); resource.add(linkTo(methodOn(ProductReviewController.class).getProductReviewDetails(pid, id)).withSelfRel()); //TODO resource.add(linkTo(methodOn(ProductController.class).getProductDetails(pid,details.getProduct())).withRel("product")); return new ResponseEntity<>(resource, HttpStatus.OK); } }; } }
{ "content_hash": "aa9b051ecb758ff0f623da54ed51f950", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 187, "avg_line_length": 54.47133757961783, "alnum_prop": 0.6535313376987839, "repo_name": "garlos/ORFO", "id": "396a1798674982073d3d6f1cd9d05dcc9f20cd42", "size": "8552", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/spring/rest/controllers/ProductReviewController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "366848" }, { "name": "Java", "bytes": "410594" } ], "symlink_target": "" }
package com.slack.api.methods.request.admin.conversations.whitelist; import com.slack.api.methods.SlackApiRequest; import lombok.Builder; import lombok.Data; /** * https://api.slack.com/methods/admin.conversations.whitelist.listGroupsLinkedToChannel */ @Deprecated @Data @Builder public class AdminConversationsWhitelistListGroupsLinkedToChannelRequest implements SlackApiRequest { /** * Authentication token bearing required scopes. */ private String token; private String channelId; /** * The workspace where the channel exists. * This argument is required for channels only tied to one workspace, * and optional for channels that are shared across an organization. */ private String teamId; }
{ "content_hash": "4a3fd624cf6dd6a0d5b0d02b0f9b1280", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 101, "avg_line_length": 26, "alnum_prop": 0.7506631299734748, "repo_name": "seratch/jslack", "id": "164d2e613f612b67e591481c1b98d5aa3b395bb7", "size": "754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "slack-api-client/src/main/java/com/slack/api/methods/request/admin/conversations/whitelist/AdminConversationsWhitelistListGroupsLinkedToChannelRequest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "3120" }, { "name": "Dockerfile", "bytes": "253" }, { "name": "Java", "bytes": "2053529" }, { "name": "Kotlin", "bytes": "26226" }, { "name": "Ruby", "bytes": "3769" }, { "name": "Shell", "bytes": "1133" } ], "symlink_target": "" }
package de.djuelg.neuronizer.domain.interactors.todolist; import de.djuelg.neuronizer.domain.interactors.base.Interactor; /** * Created by djuelg on 09.07.17. * */ public interface AddHeaderInteractor extends Interactor { interface Callback { void onHeaderAdded(); void onParentNotFound(); } }
{ "content_hash": "70a231b9b7614a92db263c20b57efbf7", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 63, "avg_line_length": 20.375, "alnum_prop": 0.7147239263803681, "repo_name": "djuelg/Neuronizer", "id": "518c31003c57c2291057715960d0041e8fa8b156", "size": "326", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/de/djuelg/neuronizer/domain/interactors/todolist/AddHeaderInteractor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "557" }, { "name": "HTML", "bytes": "6781" }, { "name": "Java", "bytes": "330986" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>fiat-crypto-legacy: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.10.dev / fiat-crypto-legacy - 8.9.dev</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> fiat-crypto-legacy <small> 8.9.dev <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-05-20 19:17:00 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-05-20 19:17:00 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; authors: [ &quot;Andres Erbsen &lt;andreser@mit.edu&gt;&quot; &quot;Google Inc.&quot; &quot;Jade Philipoom &lt;jadep@mit.edu&gt; &lt;jade.philipoom@gmail.com&gt;&quot; &quot;Massachusetts Institute of Technology&quot; ] maintainer: &quot;Jason Gross &lt;jgross@mit.edu&gt;&quot; homepage: &quot;https://github.com/mit-plv/fiat-crypto&quot; bug-reports: &quot;https://github.com/mit-plv/fiat-crypto/issues&quot; license: &quot;MIT&quot; build: [ [&quot;git&quot; &quot;submodule&quot; &quot;update&quot; &quot;--init&quot; &quot;--recursive&quot;] [make &quot;-j%{jobs}%&quot; &quot;coq&quot; &quot;selected-specific-display&quot; &quot;coqprime-all&quot;] ] install: [make &quot;install&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {= &quot;8.9.dev&quot;} &quot;coq-bignums&quot; ] dev-repo: &quot;git+https://github.com/mit-plv/fiat-crypto.git&quot; synopsis: &quot;Cryptographic Primitive Code Generation in Fiat (legacy pipeline).&quot; tags: [&quot;logpath:Crypto&quot;] url { src: &quot;git+https://github.com/mit-plv/fiat-crypto.git#sp2019latest&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-fiat-crypto-legacy.8.9.dev coq.8.10.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.dev). The following dependencies couldn&#39;t be met: - coq-fiat-crypto-legacy -&gt; coq = 8.9.dev Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-fiat-crypto-legacy.8.9.dev</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "2d9497d75df0b9f5f3fc6d19735008f5", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 157, "avg_line_length": 40.464285714285715, "alnum_prop": 0.5406001765225066, "repo_name": "coq-bench/coq-bench.github.io", "id": "b55f21b08354fe0e662c938da719d9c78e42cb82", "size": "6800", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.06.1-2.0.5/extra-dev/8.10.dev/fiat-crypto-legacy/8.9.dev.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
"use strict"; // An SMTP Transaction var config = require('./config'); var Header = require('./mailheader').Header; var body = require('./mailbody'); var utils = require('./utils'); var MessageStream = require('./messagestream'); var trans = exports; function Transaction() { this.uuid = null; this.mail_from = null; this.rcpt_to = []; this.header_lines = []; this.data_lines = []; this.banner = null; this.data_bytes = 0; this.header_pos = 0; this.body = null; this.parse_body = false; this.notes = {}; this.header = new Header(); this.message_stream = null; this.rcpt_count = { accept: 0, tempfail: 0, reject: 0, }; } exports.Transaction = Transaction; exports.createTransaction = function(uuid) { var t = new Transaction(); t.uuid = uuid || utils.uuid(); // Initialize MessageStream here to pass in the UUID t.message_stream = new MessageStream(config.get('smtp.ini'), t.uuid, t.header.header_list); return t; }; Transaction.prototype.add_data = function(line) { this.message_stream.add_line(line); if (typeof line !== 'string') { line = line.toString('binary'); } line = line.replace(/^\./, '').replace(/\r\n$/, '\n'); // check if this is the end of headers line if (this.header_pos === 0 && line[0] === '\n') { this.header.parse(this.header_lines); this.header_pos = this.header_lines.length; if (this.parse_body) { this.body = this.body || new body.Body(this.header, {"banner": this.banner}); } } else if (this.header_pos === 0) { // Build up headers this.header_lines.push(line); } else if (this.header_pos && this.parse_body) { this.body.parse_more(line); } }; Transaction.prototype.end_data = function() { if (this.header_pos && this.parse_body) { var data = this.body.parse_end(); } } Transaction.prototype.add_header = function(key, value) { this.header.add_end(key, value); if (this.header_pos > 0) this.reset_headers(); }; Transaction.prototype.add_leading_header = function(key, value) { this.header.add(key, value); if (this.header_pos > 0) this.reset_headers(); }; Transaction.prototype.reset_headers = function () { var header_lines = this.header.lines(); this.header_pos = header_lines.length; }; Transaction.prototype.remove_header = function (key) { this.header.remove(key); if (this.header_pos > 0) this.reset_headers(); }; Transaction.prototype.attachment_hooks = function (start, data, end) { this.parse_body = 1; this.body = this.body || new body.Body(this.header, {"banner": this.banner}); this.body.on('attachment_start', start); }; Transaction.prototype.set_banner = function (text, html) { throw "transaction.set_banner is currently non-functional"; this.parse_body = true; if (!html) { html = text.replace(/\n/g, '<br/>\n'); } this.banner = [text, html]; }
{ "content_hash": "a1e49d67f6eddc60268b3e0e5c8f42b6", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 95, "avg_line_length": 28.761904761904763, "alnum_prop": 0.6135761589403973, "repo_name": "imstand/Haraka", "id": "d6c4478fed29a75fe7d8c8644f628d77b341c175", "size": "3020", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "transaction.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging import os import select import socket import struct import sys import threading from functools import partial logger = logging.getLogger(__name__) class NailgunSession(object): """Handles a single nailgun command session.""" class ProtocolError(Exception): """Raised if there is an error in the underlying nailgun protocol.""" class TruncatedHeaderError(ProtocolError): """Raised if there is a socket error while reading the header bytes.""" class TruncatedPayloadError(ProtocolError): """Raised if there is a socket error while reading the payload bytes.""" # See: http://www.martiansoftware.com/nailgun/protocol.html HEADER_FMT = b'>Ic' HEADER_LENGTH = 5 BUFF_SIZE = 8096 @classmethod def _send_chunk(cls, sock, command, payload=''): command_str = command.encode() payload_str = payload.encode() header = struct.pack(cls.HEADER_FMT, len(payload_str), command_str) sock.sendall(header + payload_str) def __init__(self, sock, ins, out, err): self._sock = sock self._send_chunk = partial(self._send_chunk, sock) self._input_reader = self._InputReader(ins, self._sock, self.BUFF_SIZE) if ins else None self._out = out self._err = err class _InputReader(threading.Thread): def __init__(self, ins, sock, buff_size): threading.Thread.__init__(self) self.daemon = True self._ins = ins self._sock = sock self._buff_size = buff_size self._send_chunk = partial(NailgunSession._send_chunk, sock) self._stopping = threading.Event() def run(self): while self._should_run(): readable, _, errored = select.select([self._ins], [], [self._ins]) if self._ins in errored: self.stop() if self._should_run() and self._ins in readable: data = os.read(self._ins.fileno(), self._buff_size) if self._should_run(): if data: self._send_chunk('0', data) else: self._send_chunk('.') try: self._sock.shutdown(socket.SHUT_WR) except socket.error: # Can happen if response is quick pass self.stop() def stop(self): self._stopping.set() def _should_run(self): return not self._stopping.is_set() def execute(self, workdir, main_class, *args, **environment): for arg in args: self._send_chunk('A', arg) for k, v in environment.items(): self._send_chunk('E', '{}={}'.format(k, v)) self._send_chunk('D', workdir) self._send_chunk('C', main_class) if self._input_reader: self._input_reader.start() try: return self._read_response() finally: if self._input_reader: self._input_reader.stop() def _read_response(self): buff = b'' while True: command, payload, buff = self._read_chunk(buff) if command == '1': self._out.write(payload) self._out.flush() elif command == '2': self._err.write(payload) self._err.flush() elif command == 'X': self._out.flush() self._err.flush() return int(payload) else: raise self.ProtocolError('Received unexpected chunk {} -> {}'.format(command, payload)) def _read_chunk(self, buff): while len(buff) < self.HEADER_LENGTH: received_bytes = self._sock.recv(self.BUFF_SIZE) if not received_bytes: raise self.TruncatedHeaderError( 'While reading chunk for payload length and command, socket.recv returned no bytes' ' (client shut down). Accumulated buffer was:\n{}\n' .format(buff.decode('utf-8', errors='replace')) ) buff += received_bytes payload_length, command = struct.unpack(self.HEADER_FMT, buff[:self.HEADER_LENGTH]) buff = buff[self.HEADER_LENGTH:] while len(buff) < payload_length: received_bytes = self._sock.recv(self.BUFF_SIZE) if not received_bytes: raise self.TruncatedPayloadError( 'While reading chunk for payload content, socket.recv returned no bytes' ' (client shut down). Accumulated buffer was:\n{}\n' .format(buff.decode('utf-8', errors='replace')) ) buff += received_bytes payload = buff[:payload_length] rest = buff[payload_length:] return command, payload, rest class NailgunClient(object): """A client for the nailgun protocol that allows execution of java binaries within a resident vm. """ class NailgunError(Exception): """Indicates an error interacting with a nailgun server.""" class NailgunConnectionError(NailgunError): """Indicates an error upon initial connect to the nailgun server.""" DEFAULT_NG_HOST = '127.0.0.1' DEFAULT_NG_PORT = 2113 # For backwards compatibility with nails expecting the ng c client special env vars. ENV_DEFAULTS = dict( NAILGUN_FILESEPARATOR=os.sep, NAILGUN_PATHSEPARATOR=os.pathsep ) def __init__(self, host=DEFAULT_NG_HOST, port=DEFAULT_NG_PORT, ins=sys.stdin, out=None, err=None, workdir=None): """Creates a nailgun client that can be used to issue zero or more nailgun commands. :param string host: the nailgun server to contact (defaults to '127.0.0.1') :param int port: the port the nailgun server is listening on (defaults to the default nailgun port: 2113) :param file ins: a file to read command standard input from (defaults to stdin) - can be None in which case no input is read :param file out: a stream to write command standard output to (defaults to stdout) :param file err: a stream to write command standard error to (defaults to stderr) :param string workdir: the default working directory for all nailgun commands (defaults to PWD) """ self._host = host self._port = port self._ins = ins self._out = out or sys.stdout self._err = err or sys.stderr self._workdir = workdir or os.path.abspath(os.path.curdir) self.execute = self.__call__ def try_connect(self): """Creates a socket, connects it to the nailgun and returns the connected socket. :returns: a connected `socket.socket`. :raises: `NailgunClient.NailgunConnectionError` on failure to connect. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((self._host, self._port)) except (socket.error, socket.gaierror) as e: logger.debug('Encountered socket exception {!r} when attempting connect to nailgun'.format(e)) sock.close() raise self.NailgunConnectionError( 'Problem connecting to nailgun server at {}:{}: {!r}'.format(self._host, self._port, e)) else: return sock def __call__(self, main_class, cwd=None, *args, **environment): """Executes the given main_class with any supplied args in the given environment. :param string main_class: the fully qualified class name of the main entrypoint :param string cwd: Set the working directory for this command :param list args: any arguments to pass to the main entrypoint :param dict environment: an environment mapping made available to native nails via the nail context Returns the exit code of the main_class. """ environment = dict(self.ENV_DEFAULTS.items() + environment.items()) cwd = cwd or self._workdir # N.B. This can throw NailgunConnectionError. sock = self.try_connect() session = NailgunSession(sock, self._ins, self._out, self._err) try: return session.execute(cwd, main_class, *args, **environment) except socket.error as e: raise self.NailgunError('Problem communicating with nailgun server at {}:{}: {!r}' .format(self._host, self._port, e)) except session.ProtocolError as e: raise self.NailgunError('Problem in nailgun protocol with nailgun server at {}:{}: {!r}' .format(self._host, self._port, e)) finally: sock.close() def __repr__(self): return 'NailgunClient(host={!r}, port={!r}, workdir={!r})'.format(self._host, self._port, self._workdir)
{ "content_hash": "826af3f1e059ceadbde259db47de418c", "timestamp": "", "source": "github", "line_count": 241, "max_line_length": 100, "avg_line_length": 35.356846473029044, "alnum_prop": 0.6275085083910339, "repo_name": "sameerparekh/pants", "id": "3330a84ca8013a9be1939f25f54c76bf7a0e5a66", "size": "8668", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/python/pants/java/nailgun_client.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "767" }, { "name": "CSS", "bytes": "11442" }, { "name": "GAP", "bytes": "2459" }, { "name": "Go", "bytes": "1437" }, { "name": "HTML", "bytes": "70150" }, { "name": "Java", "bytes": "308102" }, { "name": "JavaScript", "bytes": "25075" }, { "name": "Protocol Buffer", "bytes": "3783" }, { "name": "Python", "bytes": "3862954" }, { "name": "Scala", "bytes": "85437" }, { "name": "Shell", "bytes": "49265" }, { "name": "Thrift", "bytes": "2858" } ], "symlink_target": "" }
define( "dojox/editor/plugins/nls/es/Preview", //begin v1.x content ({ "preview": "Previsualización" }) //end v1.x content );
{ "content_hash": "fde259743e65cb8db619adb281f53a29", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 59, "avg_line_length": 16, "alnum_prop": 0.6796875, "repo_name": "cfxram/grails-dojo", "id": "a51022c981100e30cb73b583bda934cbdfc7d05b", "size": "139", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "web-app/js/dojo/1.7.2/dojox/editor/plugins/nls/es/Preview.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "19954" }, { "name": "CSS", "bytes": "2579518" }, { "name": "Groovy", "bytes": "102829" }, { "name": "JavaScript", "bytes": "18492972" }, { "name": "PHP", "bytes": "38090" }, { "name": "Shell", "bytes": "9076" }, { "name": "XSLT", "bytes": "47380" } ], "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.8"/> <title>Thecallr .NET SDK: Package ThecallrApi.Objects.Sms</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="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Thecallr .NET SDK &#160;<span id="projectnumber">1.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.8 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="namespaces.html"><span>Packages</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="namespaces.html"><span>Packages</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Properties</a></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 id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespace_thecallr_api.html">ThecallrApi</a></li><li class="navelem"><a class="el" href="namespace_thecallr_api_1_1_objects.html">Objects</a></li><li class="navelem"><a class="el" href="namespace_thecallr_api_1_1_objects_1_1_sms.html">Sms</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> </div> <div class="headertitle"> <div class="title">Package ThecallrApi.Objects.Sms</div> </div> </div><!--header--> <div class="contents"> <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="class_thecallr_api_1_1_objects_1_1_sms_1_1_sms.html">Sms</a></td></tr> <tr class="memdesc:"><td class="mdescLeft">&#160;</td><td class="mdescRight">This class represents a SMS text message. <a href="class_thecallr_api_1_1_objects_1_1_sms_1_1_sms.html#details">More...</a><br /></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_thecallr_api_1_1_objects_1_1_sms_1_1_sms_options.html">SmsOptions</a></td></tr> <tr class="memdesc:"><td class="mdescLeft">&#160;</td><td class="mdescRight">This class represents SMS options. <a href="class_thecallr_api_1_1_objects_1_1_sms_1_1_sms_options.html#details">More...</a><br /></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Sep 17 2014 10:42:59 for Thecallr .NET SDK by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.8 </small></address> </body> </html>
{ "content_hash": "1729c8105669abca43becaa55bfe3b62", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 828, "avg_line_length": 55.10909090909091, "alnum_prop": 0.6667766413724844, "repo_name": "THECALLR/sdk-dotnet", "id": "d108d646a7092000f12d6d4510cf05554cb8cda2", "size": "6062", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/html/namespace_thecallr_api_1_1_objects_1_1_sms.html", "mode": "33261", "license": "mit", "language": [ { "name": "C#", "bytes": "247990" } ], "symlink_target": "" }
(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { /*! * jQuery UI Core 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.11.0", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ scrollParent: function() { var position = this.css( "position" ), excludeStaticParent = position === "absolute", scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return (/(auto|scroll)/).test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); }).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: (function() { var uuid = 0; return function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } }); }; })(), removeUniqueId: function() { return this.each(function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), disableSelection: (function() { var eventType = "onselectstart" in document.createElement( "div" ) ? "selectstart" : "mousedown"; return function() { return this.bind( eventType + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }; })(), enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; /*! * jQuery UI Widget 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ var widget_uuid = 0, widget_slice = Array.prototype.slice; $.cleanData = (function( orig ) { return function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } orig( elems ); }; })( $.cleanData ); $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widget_slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = widget_slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widget_uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); var widget = $.widget; /*! * jQuery UI Mouse 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/mouse/ */ var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); var mouse = $.widget("ui.mouse", { version: "1.11.0", options: { cancel: "input,textarea,button,select,option", distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind("mousedown." + this.widgetName, function(event) { return that._mouseDown(event); }) .bind("click." + this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { $.removeData(event.target, that.widgetName + ".preventClickEvent"); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind("." + this.widgetName); if ( this._mouseMoveDelegate ) { this.document .unbind("mousemove." + this.widgetName, this._mouseMoveDelegate) .unbind("mouseup." + this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if ( mouseHandled ) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { $.removeData(event.target, this.widgetName + ".preventClickEvent"); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; this.document .bind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .bind( "mouseup." + this.widgetName, this._mouseUpDelegate ); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { return this._mouseUp(event); // Iframe mouseup check - mouseup occurred in another document } else if ( !event.which ) { return this._mouseUp( event ); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { this.document .unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .unbind( "mouseup." + this.widgetName, this._mouseUpDelegate ); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + ".preventClickEvent", true); } this._mouseStop(event); } mouseHandled = false; return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(/* event */) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(/* event */) {}, _mouseDrag: function(/* event */) {}, _mouseStop: function(/* event */) {}, _mouseCapture: function(/* event */) { return true; } }); /*! * jQuery UI Position 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/position/ */ (function() { $.ui = $.ui || {}; var cachedScrollbarWidth, supportsOffsetFractions, max = Math.max, abs = Math.abs, round = Math.round, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[0]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[0]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[0].clientWidth; } div.remove(); return (cachedScrollbarWidth = w1 - w2); }, getScrollInfo: function( within ) { var overflowX = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[0] ), isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9; return { element: withinElement, isWindow: isWindow, isDocument: isDocument, offset: withinElement.offset() || { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: isWindow ? withinElement.width() : withinElement.outerWidth(), height: isWindow ? withinElement.height() : withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[0].preventDefault ) { // force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; }); // normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each(function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; // if the browser doesn't support fractions, then round for consistent results if ( !supportsOffsetFractions ) { position.left = round( position.left ); position.top = round( position.top ); } collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem: elem }); } }); if ( options.using ) { // adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); }); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // element is wider than within if ( data.collisionWidth > outerWidth ) { // element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // element is taller than within if ( data.collisionHeight > outerHeight ) { // element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; // fraction support test (function() { var testElement, testElementParent, testElementStyle, offsetLeft, i, body = document.getElementsByTagName( "body" )[ 0 ], div = document.createElement( "div" ); //Create a "fake body" for testing based on method used in jQuery.support testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { $.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || document.documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); div.style.cssText = "position: absolute; left: 10.7432222px;"; offsetLeft = $( div ).offset().left; supportsOffsetFractions = offsetLeft > 10 && offsetLeft < 11; testElement.innerHTML = ""; testElementParent.removeChild( testElement ); })(); })(); var position = $.ui.position; /*! * jQuery UI Accordion 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/accordion/ */ var accordion = $.widget( "ui.accordion", { version: "1.11.0", options: { active: 0, animate: {}, collapsible: false, event: "click", header: "> li > :first-child,> :not(li):even", heightStyle: "auto", icons: { activeHeader: "ui-icon-triangle-1-s", header: "ui-icon-triangle-1-e" }, // callbacks activate: null, beforeActivate: null }, hideProps: { borderTopWidth: "hide", borderBottomWidth: "hide", paddingTop: "hide", paddingBottom: "hide", height: "hide" }, showProps: { borderTopWidth: "show", borderBottomWidth: "show", paddingTop: "show", paddingBottom: "show", height: "show" }, _create: function() { var options = this.options; this.prevShow = this.prevHide = $(); this.element.addClass( "ui-accordion ui-widget ui-helper-reset" ) // ARIA .attr( "role", "tablist" ); // don't allow collapsible: false and active: false / null if ( !options.collapsible && (options.active === false || options.active == null) ) { options.active = 0; } this._processPanels(); // handle negative values if ( options.active < 0 ) { options.active += this.headers.length; } this._refresh(); }, _getCreateEventData: function() { return { header: this.active, panel: !this.active.length ? $() : this.active.next() }; }, _createIcons: function() { var icons = this.options.icons; if ( icons ) { $( "<span>" ) .addClass( "ui-accordion-header-icon ui-icon " + icons.header ) .prependTo( this.headers ); this.active.children( ".ui-accordion-header-icon" ) .removeClass( icons.header ) .addClass( icons.activeHeader ); this.headers.addClass( "ui-accordion-icons" ); } }, _destroyIcons: function() { this.headers .removeClass( "ui-accordion-icons" ) .children( ".ui-accordion-header-icon" ) .remove(); }, _destroy: function() { var contents; // clean up main element this.element .removeClass( "ui-accordion ui-widget ui-helper-reset" ) .removeAttr( "role" ); // clean up headers this.headers .removeClass( "ui-accordion-header ui-accordion-header-active ui-state-default " + "ui-corner-all ui-state-active ui-state-disabled ui-corner-top" ) .removeAttr( "role" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-controls" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this._destroyIcons(); // clean up content panels contents = this.headers.next() .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom " + "ui-accordion-content ui-accordion-content-active ui-state-disabled" ) .css( "display", "" ) .removeAttr( "role" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-labelledby" ) .removeUniqueId(); if ( this.options.heightStyle !== "content" ) { contents.css( "height", "" ); } }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "event" ) { if ( this.options.event ) { this._off( this.headers, this.options.event ); } this._setupEvents( value ); } this._super( key, value ); // setting collapsible: false while collapsed; open first panel if ( key === "collapsible" && !value && this.options.active === false ) { this._activate( 0 ); } if ( key === "icons" ) { this._destroyIcons(); if ( value ) { this._createIcons(); } } // #5332 - opacity doesn't cascade to positioned elements in IE // so we need to add the disabled class to the headers and panels if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.headers.add( this.headers.next() ) .toggleClass( "ui-state-disabled", !!value ); } }, _keydown: function( event ) { if ( event.altKey || event.ctrlKey ) { return; } var keyCode = $.ui.keyCode, length = this.headers.length, currentIndex = this.headers.index( event.target ), toFocus = false; switch ( event.keyCode ) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[ ( currentIndex + 1 ) % length ]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; break; case keyCode.SPACE: case keyCode.ENTER: this._eventHandler( event ); break; case keyCode.HOME: toFocus = this.headers[ 0 ]; break; case keyCode.END: toFocus = this.headers[ length - 1 ]; break; } if ( toFocus ) { $( event.target ).attr( "tabIndex", -1 ); $( toFocus ).attr( "tabIndex", 0 ); toFocus.focus(); event.preventDefault(); } }, _panelKeyDown: function( event ) { if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) { $( event.currentTarget ).prev().focus(); } }, refresh: function() { var options = this.options; this._processPanels(); // was collapsed or no panel if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) { options.active = false; this.active = $(); // active false only when collapsible is true } else if ( options.active === false ) { this._activate( 0 ); // was active, but active panel is gone } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { // all remaining panel are disabled if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) { options.active = false; this.active = $(); // activate previous panel } else { this._activate( Math.max( 0, options.active - 1 ) ); } // was active, active panel still exists } else { // make sure active index is correct options.active = this.headers.index( this.active ); } this._destroyIcons(); this._refresh(); }, _processPanels: function() { this.headers = this.element.find( this.options.header ) .addClass( "ui-accordion-header ui-state-default ui-corner-all" ); this.headers.next() .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ) .filter( ":not(.ui-accordion-content-active)" ) .hide(); }, _refresh: function() { var maxHeight, options = this.options, heightStyle = options.heightStyle, parent = this.element.parent(); this.active = this._findActive( options.active ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ) .removeClass( "ui-corner-all" ); this.active.next() .addClass( "ui-accordion-content-active" ) .show(); this.headers .attr( "role", "tab" ) .each(function() { var header = $( this ), headerId = header.uniqueId().attr( "id" ), panel = header.next(), panelId = panel.uniqueId().attr( "id" ); header.attr( "aria-controls", panelId ); panel.attr( "aria-labelledby", headerId ); }) .next() .attr( "role", "tabpanel" ); this.headers .not( this.active ) .attr({ "aria-selected": "false", "aria-expanded": "false", tabIndex: -1 }) .next() .attr({ "aria-hidden": "true" }) .hide(); // make sure at least one header is in the tab order if ( !this.active.length ) { this.headers.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active.attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }) .next() .attr({ "aria-hidden": "false" }); } this._createIcons(); this._setupEvents( options.event ); if ( heightStyle === "fill" ) { maxHeight = parent.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.headers.each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.headers.next() .each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.headers.next() .each(function() { maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() ); }) .height( maxHeight ); } }, _activate: function( index ) { var active = this._findActive( index )[ 0 ]; // trying to activate the already active panel if ( active === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the currently active header active = active || this.active[ 0 ]; this._eventHandler({ target: active, currentTarget: active, preventDefault: $.noop }); }, _findActive: function( selector ) { return typeof selector === "number" ? this.headers.eq( selector ) : $(); }, _setupEvents: function( event ) { var events = { keydown: "_keydown" }; if ( event ) { $.each( event.split( " " ), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.headers.add( this.headers.next() ) ); this._on( this.headers, events ); this._on( this.headers.next(), { keydown: "_panelKeyDown" }); this._hoverable( this.headers ); this._focusable( this.headers ); }, _eventHandler: function( event ) { var options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = { oldHeader: active, oldPanel: toHide, newHeader: collapsing ? $() : clicked, newPanel: toShow }; event.preventDefault(); if ( // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.headers.index( clicked ); // when the call to ._toggle() comes after the class changes // it causes a very odd bug in IE 8 (see #6720) this.active = clickedIsActive ? $() : clicked; this._toggle( eventData ); // switch classes // corner classes on the previously active header stay after the animation active.removeClass( "ui-accordion-header-active ui-state-active" ); if ( options.icons ) { active.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.activeHeader ) .addClass( options.icons.header ); } if ( !clickedIsActive ) { clicked .removeClass( "ui-corner-all" ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ); if ( options.icons ) { clicked.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.header ) .addClass( options.icons.activeHeader ); } clicked .next() .addClass( "ui-accordion-content-active" ); } }, _toggle: function( data ) { var toShow = data.newPanel, toHide = this.prevShow.length ? this.prevShow : data.oldPanel; // handle activating a panel during the animation for another activation this.prevShow.add( this.prevHide ).stop( true, true ); this.prevShow = toShow; this.prevHide = toHide; if ( this.options.animate ) { this._animate( toShow, toHide, data ); } else { toHide.hide(); toShow.show(); this._toggleComplete( data ); } toHide.attr({ "aria-hidden": "true" }); toHide.prev().attr( "aria-selected", "false" ); // if we're switching panels, remove the old header from the tab order // if we're opening from collapsed state, remove the previous header from the tab order // if we're collapsing, then keep the collapsing header in the tab order if ( toShow.length && toHide.length ) { toHide.prev().attr({ "tabIndex": -1, "aria-expanded": "false" }); } else if ( toShow.length ) { this.headers.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow .attr( "aria-hidden", "false" ) .prev() .attr({ "aria-selected": "true", tabIndex: 0, "aria-expanded": "true" }); }, _animate: function( toShow, toHide, data ) { var total, easing, duration, that = this, adjust = 0, down = toShow.length && ( !toHide.length || ( toShow.index() < toHide.index() ) ), animate = this.options.animate || {}, options = down && animate.down || animate, complete = function() { that._toggleComplete( data ); }; if ( typeof options === "number" ) { duration = options; } if ( typeof options === "string" ) { easing = options; } // fall back from options to animation in case of partial down settings easing = easing || options.easing || animate.easing; duration = duration || options.duration || animate.duration; if ( !toHide.length ) { return toShow.animate( this.showProps, duration, easing, complete ); } if ( !toShow.length ) { return toHide.animate( this.hideProps, duration, easing, complete ); } total = toShow.show().outerHeight(); toHide.animate( this.hideProps, { duration: duration, easing: easing, step: function( now, fx ) { fx.now = Math.round( now ); } }); toShow .hide() .animate( this.showProps, { duration: duration, easing: easing, complete: complete, step: function( now, fx ) { fx.now = Math.round( now ); if ( fx.prop !== "height" ) { adjust += fx.now; } else if ( that.options.heightStyle !== "content" ) { fx.now = Math.round( total - toHide.outerHeight() - adjust ); adjust = 0; } } }); }, _toggleComplete: function( data ) { var toHide = data.oldPanel; toHide .removeClass( "ui-accordion-content-active" ) .prev() .removeClass( "ui-corner-top" ) .addClass( "ui-corner-all" ); // Work around for rendering bug in IE (#5421) if ( toHide.length ) { toHide.parent()[ 0 ].className = toHide.parent()[ 0 ].className; } this._trigger( "activate", null, data ); } }); /*! * jQuery UI Menu 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/menu/ */ var menu = $.widget( "ui.menu", { version: "1.11.0", defaultElement: "<ul>", delay: 300, options: { icons: { submenu: "ui-icon-carat-1-e" }, items: "> *", menus: "ul", position: { my: "left-1 top", at: "right top" }, role: "menu", // callbacks blur: null, focus: null, select: null }, _create: function() { this.activeMenu = this.element; // Flag used to prevent firing of the click handler // as the event bubbles up through nested menus this.mouseHandled = false; this.element .uniqueId() .addClass( "ui-menu ui-widget ui-widget-content" ) .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ) .attr({ role: this.options.role, tabIndex: 0 }); if ( this.options.disabled ) { this.element .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } this._on({ // Prevent focus from sticking to links inside menu after clicking // them (focus should always stay on UL during navigation). "mousedown .ui-menu-item": function( event ) { event.preventDefault(); }, "click .ui-menu-item": function( event ) { var target = $( event.target ); if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) { this.select( event ); // Only set the mouseHandled flag if the event will bubble, see #9469. if ( !event.isPropagationStopped() ) { this.mouseHandled = true; } // Open submenu on click if ( target.has( ".ui-menu" ).length ) { this.expand( event ); } else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) { // Redirect focus to the menu this.element.trigger( "focus", [ true ] ); // If the active item is on the top level, let it stay active. // Otherwise, blur the active item since it is no longer visible. if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) { clearTimeout( this.timer ); } } } }, "mouseenter .ui-menu-item": function( event ) { var target = $( event.currentTarget ); // Remove ui-state-active class from siblings of the newly focused menu item // to avoid a jump caused by adjacent elements both having a class with a border target.siblings( ".ui-state-active" ).removeClass( "ui-state-active" ); this.focus( event, target ); }, mouseleave: "collapseAll", "mouseleave .ui-menu": "collapseAll", focus: function( event, keepActiveItem ) { // If there's already an active item, keep it active // If not, activate the first item var item = this.active || this.element.find( this.options.items ).eq( 0 ); if ( !keepActiveItem ) { this.focus( event, item ); } }, blur: function( event ) { this._delay(function() { if ( !$.contains( this.element[0], this.document[0].activeElement ) ) { this.collapseAll( event ); } }); }, keydown: "_keydown" }); this.refresh(); // Clicks outside of a menu collapse any open menus this._on( this.document, { click: function( event ) { if ( this._closeOnDocumentClick( event ) ) { this.collapseAll( event ); } // Reset the mouseHandled flag this.mouseHandled = false; } }); }, _destroy: function() { // Destroy (sub)menus this.element .removeAttr( "aria-activedescendant" ) .find( ".ui-menu" ).addBack() .removeClass( "ui-menu ui-widget ui-widget-content ui-menu-icons ui-front" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-disabled" ) .removeUniqueId() .show(); // Destroy menu items this.element.find( ".ui-menu-item" ) .removeClass( "ui-menu-item" ) .removeAttr( "role" ) .removeAttr( "aria-disabled" ) .removeUniqueId() .removeClass( "ui-state-hover" ) .removeAttr( "tabIndex" ) .removeAttr( "role" ) .removeAttr( "aria-haspopup" ) .children().each( function() { var elem = $( this ); if ( elem.data( "ui-menu-submenu-carat" ) ) { elem.remove(); } }); // Destroy menu dividers this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" ); }, _keydown: function( event ) { var match, prev, character, skip, regex, preventDefault = true; function escape( value ) { return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); } switch ( event.keyCode ) { case $.ui.keyCode.PAGE_UP: this.previousPage( event ); break; case $.ui.keyCode.PAGE_DOWN: this.nextPage( event ); break; case $.ui.keyCode.HOME: this._move( "first", "first", event ); break; case $.ui.keyCode.END: this._move( "last", "last", event ); break; case $.ui.keyCode.UP: this.previous( event ); break; case $.ui.keyCode.DOWN: this.next( event ); break; case $.ui.keyCode.LEFT: this.collapse( event ); break; case $.ui.keyCode.RIGHT: if ( this.active && !this.active.is( ".ui-state-disabled" ) ) { this.expand( event ); } break; case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: this._activate( event ); break; case $.ui.keyCode.ESCAPE: this.collapse( event ); break; default: preventDefault = false; prev = this.previousFilter || ""; character = String.fromCharCode( event.keyCode ); skip = false; clearTimeout( this.filterTimer ); if ( character === prev ) { skip = true; } else { character = prev + character; } regex = new RegExp( "^" + escape( character ), "i" ); match = this.activeMenu.find( this.options.items ).filter(function() { return regex.test( $( this ).text() ); }); match = skip && match.index( this.active.next() ) !== -1 ? this.active.nextAll( ".ui-menu-item" ) : match; // If no matches on the current filter, reset to the last character pressed // to move down the menu to the first item that starts with that character if ( !match.length ) { character = String.fromCharCode( event.keyCode ); regex = new RegExp( "^" + escape( character ), "i" ); match = this.activeMenu.find( this.options.items ).filter(function() { return regex.test( $( this ).text() ); }); } if ( match.length ) { this.focus( event, match ); if ( match.length > 1 ) { this.previousFilter = character; this.filterTimer = this._delay(function() { delete this.previousFilter; }, 1000 ); } else { delete this.previousFilter; } } else { delete this.previousFilter; } } if ( preventDefault ) { event.preventDefault(); } }, _activate: function( event ) { if ( !this.active.is( ".ui-state-disabled" ) ) { if ( this.active.is( "[aria-haspopup='true']" ) ) { this.expand( event ); } else { this.select( event ); } } }, refresh: function() { var menus, items, that = this, icon = this.options.icons.submenu, submenus = this.element.find( this.options.menus ); this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ); // Initialize nested menus submenus.filter( ":not(.ui-menu)" ) .addClass( "ui-menu ui-widget ui-widget-content ui-front" ) .hide() .attr({ role: this.options.role, "aria-hidden": "true", "aria-expanded": "false" }) .each(function() { var menu = $( this ), item = menu.parent(), submenuCarat = $( "<span>" ) .addClass( "ui-menu-icon ui-icon " + icon ) .data( "ui-menu-submenu-carat", true ); item .attr( "aria-haspopup", "true" ) .prepend( submenuCarat ); menu.attr( "aria-labelledby", item.attr( "id" ) ); }); menus = submenus.add( this.element ); items = menus.find( this.options.items ); // Initialize menu-items containing spaces and/or dashes only as dividers items.not( ".ui-menu-item" ).each(function() { var item = $( this ); if ( that._isDivider( item ) ) { item.addClass( "ui-widget-content ui-menu-divider" ); } }); // Don't refresh list items that are already adapted items.not( ".ui-menu-item, .ui-menu-divider" ) .addClass( "ui-menu-item" ) .uniqueId() .attr({ tabIndex: -1, role: this._itemRole() }); // Add aria-disabled attribute to any disabled menu item items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" ); // If the active item has been removed, blur the menu if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { this.blur(); } }, _itemRole: function() { return { menu: "menuitem", listbox: "option" }[ this.options.role ]; }, _setOption: function( key, value ) { if ( key === "icons" ) { this.element.find( ".ui-menu-icon" ) .removeClass( this.options.icons.submenu ) .addClass( value.submenu ); } if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); } this._super( key, value ); }, focus: function( event, item ) { var nested, focused; this.blur( event, event && event.type === "focus" ); this._scrollIntoView( item ); this.active = item.first(); focused = this.active.addClass( "ui-state-focus" ).removeClass( "ui-state-active" ); // Only update aria-activedescendant if there's a role // otherwise we assume focus is managed elsewhere if ( this.options.role ) { this.element.attr( "aria-activedescendant", focused.attr( "id" ) ); } // Highlight active parent menu item, if any this.active .parent() .closest( ".ui-menu-item" ) .addClass( "ui-state-active" ); if ( event && event.type === "keydown" ) { this._close(); } else { this.timer = this._delay(function() { this._close(); }, this.delay ); } nested = item.children( ".ui-menu" ); if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) { this._startOpening(nested); } this.activeMenu = item.parent(); this._trigger( "focus", event, { item: item } ); }, _scrollIntoView: function( item ) { var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight; if ( this._hasScroll() ) { borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0; paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0; offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop; scroll = this.activeMenu.scrollTop(); elementHeight = this.activeMenu.height(); itemHeight = item.outerHeight(); if ( offset < 0 ) { this.activeMenu.scrollTop( scroll + offset ); } else if ( offset + itemHeight > elementHeight ) { this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight ); } } }, blur: function( event, fromFocus ) { if ( !fromFocus ) { clearTimeout( this.timer ); } if ( !this.active ) { return; } this.active.removeClass( "ui-state-focus" ); this.active = null; this._trigger( "blur", event, { item: this.active } ); }, _startOpening: function( submenu ) { clearTimeout( this.timer ); // Don't open if already open fixes a Firefox bug that caused a .5 pixel // shift in the submenu position when mousing over the carat icon if ( submenu.attr( "aria-hidden" ) !== "true" ) { return; } this.timer = this._delay(function() { this._close(); this._open( submenu ); }, this.delay ); }, _open: function( submenu ) { var position = $.extend({ of: this.active }, this.options.position ); clearTimeout( this.timer ); this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) ) .hide() .attr( "aria-hidden", "true" ); submenu .show() .removeAttr( "aria-hidden" ) .attr( "aria-expanded", "true" ) .position( position ); }, collapseAll: function( event, all ) { clearTimeout( this.timer ); this.timer = this._delay(function() { // If we were passed an event, look for the submenu that contains the event var currentMenu = all ? this.element : $( event && event.target ).closest( this.element.find( ".ui-menu" ) ); // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway if ( !currentMenu.length ) { currentMenu = this.element; } this._close( currentMenu ); this.blur( event ); this.activeMenu = currentMenu; }, this.delay ); }, // With no arguments, closes the currently active menu - if nothing is active // it closes all menus. If passed an argument, it will search for menus BELOW _close: function( startMenu ) { if ( !startMenu ) { startMenu = this.active ? this.active.parent() : this.element; } startMenu .find( ".ui-menu" ) .hide() .attr( "aria-hidden", "true" ) .attr( "aria-expanded", "false" ) .end() .find( ".ui-state-active" ).not( ".ui-state-focus" ) .removeClass( "ui-state-active" ); }, _closeOnDocumentClick: function( event ) { return !$( event.target ).closest( ".ui-menu" ).length; }, _isDivider: function( item ) { // Match hyphen, em dash, en dash return !/[^\-\u2014\u2013\s]/.test( item.text() ); }, collapse: function( event ) { var newItem = this.active && this.active.parent().closest( ".ui-menu-item", this.element ); if ( newItem && newItem.length ) { this._close(); this.focus( event, newItem ); } }, expand: function( event ) { var newItem = this.active && this.active .children( ".ui-menu " ) .find( this.options.items ) .first(); if ( newItem && newItem.length ) { this._open( newItem.parent() ); // Delay so Firefox will not hide activedescendant change in expanding submenu from AT this._delay(function() { this.focus( event, newItem ); }); } }, next: function( event ) { this._move( "next", "first", event ); }, previous: function( event ) { this._move( "prev", "last", event ); }, isFirstItem: function() { return this.active && !this.active.prevAll( ".ui-menu-item" ).length; }, isLastItem: function() { return this.active && !this.active.nextAll( ".ui-menu-item" ).length; }, _move: function( direction, filter, event ) { var next; if ( this.active ) { if ( direction === "first" || direction === "last" ) { next = this.active [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" ) .eq( -1 ); } else { next = this.active [ direction + "All" ]( ".ui-menu-item" ) .eq( 0 ); } } if ( !next || !next.length || !this.active ) { next = this.activeMenu.find( this.options.items )[ filter ](); } this.focus( event, next ); }, nextPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isLastItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.nextAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base - height < 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.find( this.options.items ) [ !this.active ? "first" : "last" ]() ); } }, previousPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isFirstItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.prevAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base + height > 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.find( this.options.items ).first() ); } }, _hasScroll: function() { return this.element.outerHeight() < this.element.prop( "scrollHeight" ); }, select: function( event ) { // TODO: It should never be possible to not have an active item at this // point, but the tests don't trigger mouseenter before click. this.active = this.active || $( event.target ).closest( ".ui-menu-item" ); var ui = { item: this.active }; if ( !this.active.has( ".ui-menu" ).length ) { this.collapseAll( event, true ); } this._trigger( "select", event, ui ); } }); /*! * jQuery UI Autocomplete 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/autocomplete/ */ $.widget( "ui.autocomplete", { version: "1.11.0", defaultElement: "<input>", options: { appendTo: null, autoFocus: false, delay: 300, minLength: 1, position: { my: "left top", at: "left bottom", collision: "none" }, source: null, // callbacks change: null, close: null, focus: null, open: null, response: null, search: null, select: null }, requestIndex: 0, pending: 0, _create: function() { // Some browsers only repeat keydown events, not keypress events, // so we use the suppressKeyPress flag to determine if we've already // handled the keydown event. #7269 // Unfortunately the code for & in keypress is the same as the up arrow, // so we use the suppressKeyPressRepeat flag to avoid handling keypress // events when we know the keydown event was used to modify the // search term. #7799 var suppressKeyPress, suppressKeyPressRepeat, suppressInput, nodeName = this.element[ 0 ].nodeName.toLowerCase(), isTextarea = nodeName === "textarea", isInput = nodeName === "input"; this.isMultiLine = // Textareas are always multi-line isTextarea ? true : // Inputs are always single-line, even if inside a contentEditable element // IE also treats inputs as contentEditable isInput ? false : // All other element types are determined by whether or not they're contentEditable this.element.prop( "isContentEditable" ); this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ]; this.isNewMenu = true; this.element .addClass( "ui-autocomplete-input" ) .attr( "autocomplete", "off" ); this._on( this.element, { keydown: function( event ) { if ( this.element.prop( "readOnly" ) ) { suppressKeyPress = true; suppressInput = true; suppressKeyPressRepeat = true; return; } suppressKeyPress = false; suppressInput = false; suppressKeyPressRepeat = false; var keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.PAGE_UP: suppressKeyPress = true; this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: suppressKeyPress = true; this._move( "nextPage", event ); break; case keyCode.UP: suppressKeyPress = true; this._keyEvent( "previous", event ); break; case keyCode.DOWN: suppressKeyPress = true; this._keyEvent( "next", event ); break; case keyCode.ENTER: // when menu is open and has focus if ( this.menu.active ) { // #6055 - Opera still allows the keypress to occur // which causes forms to submit suppressKeyPress = true; event.preventDefault(); this.menu.select( event ); } break; case keyCode.TAB: if ( this.menu.active ) { this.menu.select( event ); } break; case keyCode.ESCAPE: if ( this.menu.element.is( ":visible" ) ) { this._value( this.term ); this.close( event ); // Different browsers have different default behavior for escape // Single press can mean undo or clear // Double press in IE means clear the whole form event.preventDefault(); } break; default: suppressKeyPressRepeat = true; // search timeout should be triggered before the input value is changed this._searchTimeout( event ); break; } }, keypress: function( event ) { if ( suppressKeyPress ) { suppressKeyPress = false; if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { event.preventDefault(); } return; } if ( suppressKeyPressRepeat ) { return; } // replicate some key handlers to allow them to repeat in Firefox and Opera var keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.PAGE_UP: this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: this._move( "nextPage", event ); break; case keyCode.UP: this._keyEvent( "previous", event ); break; case keyCode.DOWN: this._keyEvent( "next", event ); break; } }, input: function( event ) { if ( suppressInput ) { suppressInput = false; event.preventDefault(); return; } this._searchTimeout( event ); }, focus: function() { this.selectedItem = null; this.previous = this._value(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } clearTimeout( this.searching ); this.close( event ); this._change( event ); } }); this._initSource(); this.menu = $( "<ul>" ) .addClass( "ui-autocomplete ui-front" ) .appendTo( this._appendTo() ) .menu({ // disable ARIA support, the live region takes care of that role: null }) .hide() .menu( "instance" ); this._on( this.menu.element, { mousedown: function( event ) { // prevent moving focus out of the text field event.preventDefault(); // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; }); // clicking on the scrollbar causes focus to shift to the body // but we can't detect a mouseup or a click immediately afterward // so we have to track the next mousedown and close the menu if // the user clicks somewhere outside of the autocomplete var menuElement = this.menu.element[ 0 ]; if ( !$( event.target ).closest( ".ui-menu-item" ).length ) { this._delay(function() { var that = this; this.document.one( "mousedown", function( event ) { if ( event.target !== that.element[ 0 ] && event.target !== menuElement && !$.contains( menuElement, event.target ) ) { that.close(); } }); }); } }, menufocus: function( event, ui ) { var label, item; // support: Firefox // Prevent accidental activation of menu items in Firefox (#7024 #9118) if ( this.isNewMenu ) { this.isNewMenu = false; if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) { this.menu.blur(); this.document.one( "mousemove", function() { $( event.target ).trigger( event.originalEvent ); }); return; } } item = ui.item.data( "ui-autocomplete-item" ); if ( false !== this._trigger( "focus", event, { item: item } ) ) { // use value to match what will end up in the input, if it was a key event if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) { this._value( item.value ); } } // Announce the value in the liveRegion label = ui.item.attr( "aria-label" ) || item.value; if ( label && jQuery.trim( label ).length ) { this.liveRegion.children().hide(); $( "<div>" ).text( label ).appendTo( this.liveRegion ); } }, menuselect: function( event, ui ) { var item = ui.item.data( "ui-autocomplete-item" ), previous = this.previous; // only trigger when focus was lost (click on menu) if ( this.element[ 0 ] !== this.document[ 0 ].activeElement ) { this.element.focus(); this.previous = previous; // #6109 - IE triggers two focus events and the second // is asynchronous, so we need to reset the previous // term synchronously and asynchronously :-( this._delay(function() { this.previous = previous; this.selectedItem = item; }); } if ( false !== this._trigger( "select", event, { item: item } ) ) { this._value( item.value ); } // reset the term after the select event // this allows custom select handling to work properly this.term = this._value(); this.close( event ); this.selectedItem = item; } }); this.liveRegion = $( "<span>", { role: "status", "aria-live": "assertive", "aria-relevant": "additions" }) .addClass( "ui-helper-hidden-accessible" ) .appendTo( this.document[ 0 ].body ); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _destroy: function() { clearTimeout( this.searching ); this.element .removeClass( "ui-autocomplete-input" ) .removeAttr( "autocomplete" ); this.menu.element.remove(); this.liveRegion.remove(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "source" ) { this._initSource(); } if ( key === "appendTo" ) { this.menu.element.appendTo( this._appendTo() ); } if ( key === "disabled" && value && this.xhr ) { this.xhr.abort(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element ) { element = element.jquery || element.nodeType ? $( element ) : this.document.find( element ).eq( 0 ); } if ( !element || !element[ 0 ] ) { element = this.element.closest( ".ui-front" ); } if ( !element.length ) { element = this.document[ 0 ].body; } return element; }, _initSource: function() { var array, url, that = this; if ( $.isArray( this.options.source ) ) { array = this.options.source; this.source = function( request, response ) { response( $.ui.autocomplete.filter( array, request.term ) ); }; } else if ( typeof this.options.source === "string" ) { url = this.options.source; this.source = function( request, response ) { if ( that.xhr ) { that.xhr.abort(); } that.xhr = $.ajax({ url: url, data: request, dataType: "json", success: function( data ) { response( data ); }, error: function() { response([]); } }); }; } else { this.source = this.options.source; } }, _searchTimeout: function( event ) { clearTimeout( this.searching ); this.searching = this._delay(function() { // Search if the value has changed, or if the user retypes the same value (see #7434) var equalValues = this.term === this._value(), menuVisible = this.menu.element.is( ":visible" ), modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey; if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) { this.selectedItem = null; this.search( null, event ); } }, this.options.delay ); }, search: function( value, event ) { value = value != null ? value : this._value(); // always save the actual value, not the one passed as an argument this.term = this._value(); if ( value.length < this.options.minLength ) { return this.close( event ); } if ( this._trigger( "search", event ) === false ) { return; } return this._search( value ); }, _search: function( value ) { this.pending++; this.element.addClass( "ui-autocomplete-loading" ); this.cancelSearch = false; this.source( { term: value }, this._response() ); }, _response: function() { var index = ++this.requestIndex; return $.proxy(function( content ) { if ( index === this.requestIndex ) { this.__response( content ); } this.pending--; if ( !this.pending ) { this.element.removeClass( "ui-autocomplete-loading" ); } }, this ); }, __response: function( content ) { if ( content ) { content = this._normalize( content ); } this._trigger( "response", null, { content: content } ); if ( !this.options.disabled && content && content.length && !this.cancelSearch ) { this._suggest( content ); this._trigger( "open" ); } else { // use ._close() instead of .close() so we don't cancel future searches this._close(); } }, close: function( event ) { this.cancelSearch = true; this._close( event ); }, _close: function( event ) { if ( this.menu.element.is( ":visible" ) ) { this.menu.element.hide(); this.menu.blur(); this.isNewMenu = true; this._trigger( "close", event ); } }, _change: function( event ) { if ( this.previous !== this._value() ) { this._trigger( "change", event, { item: this.selectedItem } ); } }, _normalize: function( items ) { // assume all items have the right format when the first item is complete if ( items.length && items[ 0 ].label && items[ 0 ].value ) { return items; } return $.map( items, function( item ) { if ( typeof item === "string" ) { return { label: item, value: item }; } return $.extend( {}, item, { label: item.label || item.value, value: item.value || item.label }); }); }, _suggest: function( items ) { var ul = this.menu.element.empty(); this._renderMenu( ul, items ); this.isNewMenu = true; this.menu.refresh(); // size and position menu ul.show(); this._resizeMenu(); ul.position( $.extend({ of: this.element }, this.options.position ) ); if ( this.options.autoFocus ) { this.menu.next(); } }, _resizeMenu: function() { var ul = this.menu.element; ul.outerWidth( Math.max( // Firefox wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping (#7513) ul.width( "" ).outerWidth() + 1, this.element.outerWidth() ) ); }, _renderMenu: function( ul, items ) { var that = this; $.each( items, function( index, item ) { that._renderItemData( ul, item ); }); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-autocomplete-item", item ); }, _renderItem: function( ul, item ) { return $( "<li>" ).text( item.label ).appendTo( ul ); }, _move: function( direction, event ) { if ( !this.menu.element.is( ":visible" ) ) { this.search( null, event ); return; } if ( this.menu.isFirstItem() && /^previous/.test( direction ) || this.menu.isLastItem() && /^next/.test( direction ) ) { if ( !this.isMultiLine ) { this._value( this.term ); } this.menu.blur(); return; } this.menu[ direction ]( event ); }, widget: function() { return this.menu.element; }, _value: function() { return this.valueMethod.apply( this.element, arguments ); }, _keyEvent: function( keyEvent, event ) { if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { this._move( keyEvent, event ); // prevents moving cursor to beginning/end of the text field in some browsers event.preventDefault(); } } }); $.extend( $.ui.autocomplete, { escapeRegex: function( value ) { return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); }, filter: function( array, term ) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" ); return $.grep( array, function( value ) { return matcher.test( value.label || value.value || value ); }); } }); // live region extension, adding a `messages` option // NOTE: This is an experimental API. We are still investigating // a full solution for string manipulation and internationalization. $.widget( "ui.autocomplete", $.ui.autocomplete, { options: { messages: { noResults: "No search results.", results: function( amount ) { return amount + ( amount > 1 ? " results are" : " result is" ) + " available, use up and down arrow keys to navigate."; } } }, __response: function( content ) { var message; this._superApply( arguments ); if ( this.options.disabled || this.cancelSearch ) { return; } if ( content && content.length ) { message = this.options.messages.results( content.length ); } else { message = this.options.messages.noResults; } this.liveRegion.children().hide(); $( "<div>" ).text( message ).appendTo( this.liveRegion ); } }); var autocomplete = $.ui.autocomplete; /*! * jQuery UI Button 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/button/ */ var lastActive, baseClasses = "ui-button ui-widget ui-state-default ui-corner-all", typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only", formResetHandler = function() { var form = $( this ); setTimeout(function() { form.find( ":ui-button" ).button( "refresh" ); }, 1 ); }, radioGroup = function( radio ) { var name = radio.name, form = radio.form, radios = $( [] ); if ( name ) { name = name.replace( /'/g, "\\'" ); if ( form ) { radios = $( form ).find( "[name='" + name + "'][type=radio]" ); } else { radios = $( "[name='" + name + "'][type=radio]", radio.ownerDocument ) .filter(function() { return !this.form; }); } } return radios; }; $.widget( "ui.button", { version: "1.11.0", defaultElement: "<button>", options: { disabled: null, text: true, label: null, icons: { primary: null, secondary: null } }, _create: function() { this.element.closest( "form" ) .unbind( "reset" + this.eventNamespace ) .bind( "reset" + this.eventNamespace, formResetHandler ); if ( typeof this.options.disabled !== "boolean" ) { this.options.disabled = !!this.element.prop( "disabled" ); } else { this.element.prop( "disabled", this.options.disabled ); } this._determineButtonType(); this.hasTitle = !!this.buttonElement.attr( "title" ); var that = this, options = this.options, toggleButton = this.type === "checkbox" || this.type === "radio", activeClass = !toggleButton ? "ui-state-active" : ""; if ( options.label === null ) { options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html()); } this._hoverable( this.buttonElement ); this.buttonElement .addClass( baseClasses ) .attr( "role", "button" ) .bind( "mouseenter" + this.eventNamespace, function() { if ( options.disabled ) { return; } if ( this === lastActive ) { $( this ).addClass( "ui-state-active" ); } }) .bind( "mouseleave" + this.eventNamespace, function() { if ( options.disabled ) { return; } $( this ).removeClass( activeClass ); }) .bind( "click" + this.eventNamespace, function( event ) { if ( options.disabled ) { event.preventDefault(); event.stopImmediatePropagation(); } }); // Can't use _focusable() because the element that receives focus // and the element that gets the ui-state-focus class are different this._on({ focus: function() { this.buttonElement.addClass( "ui-state-focus" ); }, blur: function() { this.buttonElement.removeClass( "ui-state-focus" ); } }); if ( toggleButton ) { this.element.bind( "change" + this.eventNamespace, function() { that.refresh(); }); } if ( this.type === "checkbox" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled ) { return false; } }); } else if ( this.type === "radio" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); that.buttonElement.attr( "aria-pressed", "true" ); var radio = that.element[ 0 ]; radioGroup( radio ) .not( radio ) .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); }); } else { this.buttonElement .bind( "mousedown" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); lastActive = this; that.document.one( "mouseup", function() { lastActive = null; }); }) .bind( "mouseup" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).removeClass( "ui-state-active" ); }) .bind( "keydown" + this.eventNamespace, function(event) { if ( options.disabled ) { return false; } if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) { $( this ).addClass( "ui-state-active" ); } }) // see #8559, we bind to blur here in case the button element loses // focus between keydown and keyup, it would be left in an "active" state .bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() { $( this ).removeClass( "ui-state-active" ); }); if ( this.buttonElement.is("a") ) { this.buttonElement.keyup(function(event) { if ( event.keyCode === $.ui.keyCode.SPACE ) { // TODO pass through original event correctly (just as 2nd argument doesn't work) $( this ).click(); } }); } } this._setOption( "disabled", options.disabled ); this._resetButton(); }, _determineButtonType: function() { var ancestor, labelSelector, checked; if ( this.element.is("[type=checkbox]") ) { this.type = "checkbox"; } else if ( this.element.is("[type=radio]") ) { this.type = "radio"; } else if ( this.element.is("input") ) { this.type = "input"; } else { this.type = "button"; } if ( this.type === "checkbox" || this.type === "radio" ) { // we don't search against the document in case the element // is disconnected from the DOM ancestor = this.element.parents().last(); labelSelector = "label[for='" + this.element.attr("id") + "']"; this.buttonElement = ancestor.find( labelSelector ); if ( !this.buttonElement.length ) { ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings(); this.buttonElement = ancestor.filter( labelSelector ); if ( !this.buttonElement.length ) { this.buttonElement = ancestor.find( labelSelector ); } } this.element.addClass( "ui-helper-hidden-accessible" ); checked = this.element.is( ":checked" ); if ( checked ) { this.buttonElement.addClass( "ui-state-active" ); } this.buttonElement.prop( "aria-pressed", checked ); } else { this.buttonElement = this.element; } }, widget: function() { return this.buttonElement; }, _destroy: function() { this.element .removeClass( "ui-helper-hidden-accessible" ); this.buttonElement .removeClass( baseClasses + " ui-state-active " + typeClasses ) .removeAttr( "role" ) .removeAttr( "aria-pressed" ) .html( this.buttonElement.find(".ui-button-text").html() ); if ( !this.hasTitle ) { this.buttonElement.removeAttr( "title" ); } }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "disabled" ) { this.widget().toggleClass( "ui-state-disabled", !!value ); this.element.prop( "disabled", !!value ); if ( value ) { if ( this.type === "checkbox" || this.type === "radio" ) { this.buttonElement.removeClass( "ui-state-focus" ); } else { this.buttonElement.removeClass( "ui-state-focus ui-state-active" ); } } return; } this._resetButton(); }, refresh: function() { //See #8237 & #8828 var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" ); if ( isDisabled !== this.options.disabled ) { this._setOption( "disabled", isDisabled ); } if ( this.type === "radio" ) { radioGroup( this.element[0] ).each(function() { if ( $( this ).is( ":checked" ) ) { $( this ).button( "widget" ) .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { $( this ).button( "widget" ) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } }); } else if ( this.type === "checkbox" ) { if ( this.element.is( ":checked" ) ) { this.buttonElement .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { this.buttonElement .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } } }, _resetButton: function() { if ( this.type === "input" ) { if ( this.options.label ) { this.element.val( this.options.label ); } return; } var buttonElement = this.buttonElement.removeClass( typeClasses ), buttonText = $( "<span></span>", this.document[0] ) .addClass( "ui-button-text" ) .html( this.options.label ) .appendTo( buttonElement.empty() ) .text(), icons = this.options.icons, multipleIcons = icons.primary && icons.secondary, buttonClasses = []; if ( icons.primary || icons.secondary ) { if ( this.options.text ) { buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) ); } if ( icons.primary ) { buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" ); } if ( icons.secondary ) { buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" ); } if ( !this.options.text ) { buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" ); if ( !this.hasTitle ) { buttonElement.attr( "title", $.trim( buttonText ) ); } } } else { buttonClasses.push( "ui-button-text-only" ); } buttonElement.addClass( buttonClasses.join( " " ) ); } }); $.widget( "ui.buttonset", { version: "1.11.0", options: { items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)" }, _create: function() { this.element.addClass( "ui-buttonset" ); }, _init: function() { this.refresh(); }, _setOption: function( key, value ) { if ( key === "disabled" ) { this.buttons.button( "option", key, value ); } this._super( key, value ); }, refresh: function() { var rtl = this.element.css( "direction" ) === "rtl", allButtons = this.element.find( this.options.items ), existingButtons = allButtons.filter( ":ui-button" ); // Initialize new buttons allButtons.not( ":ui-button" ).button(); // Refresh existing buttons existingButtons.button( "refresh" ); this.buttons = allButtons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-all ui-corner-left ui-corner-right" ) .filter( ":first" ) .addClass( rtl ? "ui-corner-right" : "ui-corner-left" ) .end() .filter( ":last" ) .addClass( rtl ? "ui-corner-left" : "ui-corner-right" ) .end() .end(); }, _destroy: function() { this.element.removeClass( "ui-buttonset" ); this.buttons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-left ui-corner-right" ) .end() .button( "destroy" ); } }); var button = $.ui.button; /*! * jQuery UI Datepicker 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/datepicker/ */ $.extend($.ui, { datepicker: { version: "1.11.0" } }); var datepicker_instActive; function datepicker_getZindex( elem ) { var position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } return 0; } /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class this._appendClass = "ui-datepicker-append"; // The name of the append marker class this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[""] = { // Default regional settings closeText: "Done", // Display text for close link prevText: "Prev", // Display text for previous month link nextText: "Next", // Display text for next month link currentText: "Today", // Display text for current month link monthNames: ["January","February","March","April","May","June", "July","August","September","October","November","December"], // Names of months for drop-down and formatting monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday weekHeader: "Wk", // Column header for week of the year dateFormat: "mm/dd/yy", // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: "" // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: "focus", // "focus" for popup on focus, // "button" for trigger button, or "both" for either showAnim: "fadeIn", // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: "", // Display text following the input box, e.g. showing the format buttonText: "...", // Text for trigger button buttonImage: "", // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: "c-10:c+10", // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: "+10", // Short year values < this are in the current century, // > this are in the previous century, // string value starting with "+" for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: "fast", // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "", // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: "", // Selector for an alternate field to store selected dates into altFormat: "", // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional[""]); this.regional.en = $.extend( true, {}, this.regional[ "" ]); this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en ); this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: "hasDatepicker", //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. * @param settings object - the new settings to use as defaults (anonymous object) * @return the manager object */ setDefaults: function(settings) { datepicker_extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. * @param target element - the target input field or division or span * @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { var nodeName, inline, inst; nodeName = target.nodeName.toLowerCase(); inline = (nodeName === "div" || nodeName === "span"); if (!target.id) { this.uuid += 1; target.id = "dp" + this.uuid; } inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}); if (nodeName === "input") { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) { return; } this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp); this._autoSize(inst); $.data(target, "datepicker", inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var showOn, buttonText, buttonImage, appendText = this._get(inst, "appendText"), isRTL = this._get(inst, "isRTL"); if (inst.append) { inst.append.remove(); } if (appendText) { inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>"); input[isRTL ? "before" : "after"](inst.append); } input.unbind("focus", this._showDatepicker); if (inst.trigger) { inst.trigger.remove(); } showOn = this._get(inst, "showOn"); if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field input.focus(this._showDatepicker); } if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked buttonText = this._get(inst, "buttonText"); buttonImage = this._get(inst, "buttonImage"); inst.trigger = $(this._get(inst, "buttonImageOnly") ? $("<img/>").addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $("<button type='button'></button>").addClass(this._triggerClass). html(!buttonImage ? buttonText : $("<img/>").attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? "before" : "after"](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) { $.datepicker._hideDatepicker(); } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else { $.datepicker._showDatepicker(input[0]); } return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, "autoSize") && !inst.inline) { var findMax, max, maxI, i, date = new Date(2009, 12 - 1, 20), // Ensure double digits dateFormat = this._get(inst, "dateFormat"); if (dateFormat.match(/[DM]/)) { findMax = function(names) { max = 0; maxI = 0; for (i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? "monthNames" : "monthNamesShort")))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? "dayNames" : "dayNamesShort"))) + 20 - date.getDay()); } inst.input.attr("size", this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) { return; } divSpan.addClass(this.markerClassName).append(inst.dpDiv); $.data(target, "datepicker", inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. * @param input element - ignored * @param date string or Date - the initial date to display * @param onSelect function - the function to call when a date is selected * @param settings object - update the dialog date picker instance's settings (anonymous object) * @param pos int[2] - coordinates for the dialog's position within the screen or * event - with x/y coordinates or * leave empty for default (screen centre) * @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var id, browserWidth, browserHeight, scrollX, scrollY, inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; id = "dp" + this.uuid; this._dialogInput = $("<input type='text' id='" + id + "' style='position: absolute; top: -100px; width: 0px;'/>"); this._dialogInput.keydown(this._doKeyDown); $("body").append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], "datepicker", inst); } datepicker_extendRemove(inst.settings, settings || {}); date = (date && date.constructor === Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { browserWidth = document.documentElement.clientWidth; browserHeight = document.documentElement.clientHeight; scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px"); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) { $.blockUI(this.dpDiv); } $.data(this._dialogInput[0], "datepicker", inst); return this; }, /* Detach a datepicker from its control. * @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var nodeName, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); $.removeData(target, "datepicker"); if (nodeName === "input") { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind("focus", this._showDatepicker). unbind("keydown", this._doKeyDown). unbind("keypress", this._doKeyPress). unbind("keyup", this._doKeyUp); } else if (nodeName === "div" || nodeName === "span") { $target.removeClass(this.markerClassName).empty(); } }, /* Enable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = false; inst.trigger.filter("button"). each(function() { this.disabled = false; }).end(). filter("img").css({opacity: "1.0", cursor: ""}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().removeClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", false); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = true; inst.trigger.filter("button"). each(function() { this.disabled = true; }).end(). filter("img").css({opacity: "0.5", cursor: "default"}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().addClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", true); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? * @param target element - the target input field or division or span * @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] === target) { return true; } } return false; }, /* Retrieve the instance data for the target control. * @param target element - the target input field or division or span * @return object - the associated instance data * @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, "datepicker"); } catch (err) { throw "Missing instance data for this datepicker"; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. * @param target element - the target input field or division or span * @param name object - the new settings to update or * string - the name of the setting to change or retrieve, * when retrieving also "all" for all instance settings or * "defaults" for all global defaults * @param value any - the new value for the setting * (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var settings, date, minDate, maxDate, inst = this._getInst(target); if (arguments.length === 2 && typeof name === "string") { return (name === "defaults" ? $.extend({}, $.datepicker._defaults) : (inst ? (name === "all" ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } settings = name || {}; if (typeof name === "string") { settings = {}; settings[name] = value; } if (inst) { if (this._curInst === inst) { this._hideDatepicker(); } date = this._getDateDatepicker(target, true); minDate = this._getMinMaxDate(inst, "min"); maxDate = this._getMinMaxDate(inst, "max"); datepicker_extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) { inst.settings.minDate = this._formatDate(inst, minDate); } if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) { inst.settings.maxDate = this._formatDate(inst, maxDate); } if ( "disabled" in settings ) { if ( settings.disabled ) { this._disableDatepicker(target); } else { this._enableDatepicker(target); } } this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. * @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. * @param target element - the target input field or division or span * @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. * @param target element - the target input field or division or span * @param noDefault boolean - true if no default date is to be used * @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) { this._setDateFromField(inst, noDefault); } return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var onSelect, dateStr, sel, inst = $.datepicker._getInst(event.target), handled = true, isRTL = inst.dpDiv.is(".ui-datepicker-rtl"); inst._keyEvent = true; if ($.datepicker._datepickerShowing) { switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." + $.datepicker._currentClass + ")", inst.dpDiv); if (sel[0]) { $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); } onSelect = $.datepicker._get(inst, "onSelect"); if (onSelect) { dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else { $.datepicker._hideDatepicker(); } return false; // don't submit the form case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) { $.datepicker._clearDate(event.target); } handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) { $.datepicker._gotoToday(event.target); } handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D"); } handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, -7, "D"); } handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D"); } handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, +7, "D"); } handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home $.datepicker._showDatepicker(this); } else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var chars, chr, inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, "constrainInput")) { chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat")); chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var date, inst = $.datepicker._getInst(event.target); if (inst.input.val() !== inst.lastVal) { try { date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { } } return true; }, /* Pop-up the date picker for a given input field. * If false returned from beforeShow event handler do not show. * @param input element - the input field attached to the date picker or * event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger input = $("input", input.parentNode)[0]; } if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here return; } var inst, beforeShow, beforeShowSettings, isFixed, offset, showAnim, duration; inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst !== inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } beforeShow = $.datepicker._get(inst, "beforeShow"); beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ return; } datepicker_extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) { // hide cursor input.value = ""; } if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css("position") === "fixed"; return !isFixed; }); offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? "static" : (isFixed ? "fixed" : "absolute")), display: "none", left: offset.left + "px", top: offset.top + "px"}); if (!inst.inline) { showAnim = $.datepicker._get(inst, "showAnim"); duration = $.datepicker._get(inst, "duration"); inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 ); $.datepicker._datepickerShowing = true; if ( $.effects && $.effects.effect[ showAnim ] ) { inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration); } else { inst.dpDiv[showAnim || "show"](showAnim ? duration : null); } if ( $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) datepicker_instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); inst.dpDiv.find("." + this._dayOverClass + " a"); var origyearshtml, numMonths = this._getNumberOfMonths(inst), cols = numMonths[1], width = 17; inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""); if (cols > 1) { inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em"); } inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") + "Class"]("ui-datepicker-multi"); inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") + "Class"]("ui-datepicker-rtl"); if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, // #6694 - don't focus the input if it's already focused // this breaks the change event in IE // Support: IE and jQuery <1.9 _shouldFocusInput: function( inst ) { return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" ); }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(), dpHeight = inst.dpDiv.outerHeight(), inputWidth = inst.input ? inst.input.outerWidth() : 0, inputHeight = inst.input ? inst.input.outerHeight() : 0, viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()), viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var position, inst = this._getInst(obj), isRTL = this._get(inst, "isRTL"); while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? "previousSibling" : "nextSibling"]; } position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. * @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var showAnim, duration, postProcess, onClose, inst = this._curInst; if (!inst || (input && inst !== $.data(input, "datepicker"))) { return; } if (this._datepickerShowing) { showAnim = this._get(inst, "showAnim"); duration = this._get(inst, "duration"); postProcess = function() { $.datepicker._tidyDialog(inst); }; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) { inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess); } else { inst.dpDiv[(showAnim === "slideDown" ? "slideUp" : (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess); } if (!showAnim) { postProcess(); } this._datepickerShowing = false; onClose = this._get(inst, "onClose"); if (onClose) { onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]); } this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" }); if ($.blockUI) { $.unblockUI(); $("body").append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar"); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) { return; } var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id !== $.datepicker._mainDivId && $target.parents("#" + $.datepicker._mainDivId).length === 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) { $.datepicker._hideDatepicker(); } }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id), inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var date, target = $(id), inst = this._getInst(target[0]); if (this._get(inst, "gotoCurrent") && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id), inst = this._getInst(target[0]); inst["selected" + (period === "M" ? "Month" : "Year")] = inst["draw" + (period === "M" ? "Month" : "Year")] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var inst, target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $("a", td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); this._selectDate(target, ""); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var onSelect, target = $(id), inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) { inst.input.val(dateStr); } this._updateAlternate(inst); onSelect = this._get(inst, "onSelect"); if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback } else if (inst.input) { inst.input.trigger("change"); // fire the change event } if (inst.inline){ this._updateDatepicker(inst); } else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) !== "object") { inst.input.focus(); // restore focus } this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altFormat, date, dateStr, altField = this._get(inst, "altField"); if (altField) { // update alternate field too altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat"); date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. * @param date Date - the date to customise * @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), ""]; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. * @param date Date - the date to get the week for * @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var time, checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. * See formatDate below for the possible formats. * * @param format string - the expected format of the date * @param value string - the date in the above format * @param settings Object - attributes include: * shortYearCutoff number - the cutoff year for determining the century (optional) * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) { throw "Invalid arguments"; } value = (typeof value === "object" ? value.toString() : value + ""); if (value === "") { return null; } var iFormat, dim, extra, iValue = 0, shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff, shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp : new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)), dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, year = -1, month = -1, day = -1, doy = -1, literal = false, date, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Extract a number from the string value getNumber = function(match) { var isDoubled = lookAhead(match), size = (match === "@" ? 14 : (match === "!" ? 20 : (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))), digits = new RegExp("^\\d{1," + size + "}"), num = value.substring(iValue).match(digits); if (!num) { throw "Missing number at position " + iValue; } iValue += num[0].length; return parseInt(num[0], 10); }, // Extract a name from the string value and convert to an index getName = function(match, shortNames, longNames) { var index = -1, names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index !== -1) { return index + 1; } else { throw "Unknown name at position " + iValue; } }, // Confirm that a literal character matches the string value checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { throw "Unexpected literal at position " + iValue; } iValue++; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { checkLiteral(); } } else { switch (format.charAt(iFormat)) { case "d": day = getNumber("d"); break; case "D": getName("D", dayNamesShort, dayNames); break; case "o": doy = getNumber("o"); break; case "m": month = getNumber("m"); break; case "M": month = getName("M", monthNamesShort, monthNames); break; case "y": year = getNumber("y"); break; case "@": date = new Date(getNumber("@")); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "!": date = new Date((getNumber("!") - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")){ checkLiteral(); } else { literal = true; } break; default: checkLiteral(); } } } if (iValue < value.length){ extra = value.substr(iValue); if (!/^\s+/.test(extra)) { throw "Extra/unparsed characters found in date: " + extra; } } if (year === -1) { year = new Date().getFullYear(); } else if (year < 100) { year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); } if (doy > -1) { month = 1; day = doy; do { dim = this._getDaysInMonth(year, month - 1); if (day <= dim) { break; } month++; day -= dim; } while (true); } date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) { throw "Invalid date"; // E.g. 31/02/00 } return date; }, /* Standard date formats. */ ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601) COOKIE: "D, dd M yy", ISO_8601: "yy-mm-dd", RFC_822: "D, d M y", RFC_850: "DD, dd-M-y", RFC_1036: "D, d M y", RFC_1123: "D, d M yy", RFC_2822: "D, d M yy", RSS: "D, d M y", // RFC 822 TICKS: "!", TIMESTAMP: "@", W3C: "yy-mm-dd", // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. * The format can be combinations of the following: * d - day of month (no leading zero) * dd - day of month (two digit) * o - day of year (no leading zeros) * oo - day of year (three digit) * D - day name short * DD - day name long * m - month of year (no leading zero) * mm - month of year (two digit) * M - month name short * MM - month name long * y - year (two digit) * yy - year (four digit) * @ - Unix timestamp (ms since 01/01/1970) * ! - Windows ticks (100ns since 01/01/0001) * "..." - literal text * '' - single quote * * @param format string - the desired format of the date * @param date Date - the date value to format * @param settings Object - attributes include: * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) { return ""; } var iFormat, dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Format a number, with leading zero if necessary formatNumber = function(match, value, len) { var num = "" + value; if (lookAhead(match)) { while (num.length < len) { num = "0" + num; } } return num; }, // Format a name, short or long as requested formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }, output = "", literal = false; if (date) { for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { output += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": output += formatNumber("d", date.getDate(), 2); break; case "D": output += formatName("D", date.getDay(), dayNamesShort, dayNames); break; case "o": output += formatNumber("o", Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case "m": output += formatNumber("m", date.getMonth() + 1, 2); break; case "M": output += formatName("M", date.getMonth(), monthNamesShort, monthNames); break; case "y": output += (lookAhead("y") ? date.getFullYear() : (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100); break; case "@": output += date.getTime(); break; case "!": output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) { output += "'"; } else { literal = true; } break; default: output += format.charAt(iFormat); } } } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var iFormat, chars = "", literal = false, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { chars += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": case "m": case "y": case "@": chars += "0123456789"; break; case "D": case "M": return null; // Accept anything case "'": if (lookAhead("'")) { chars += "'"; } else { literal = true; } break; default: chars += format.charAt(iFormat); } } } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() === inst.lastVal) { return; } var dateFormat = this._get(inst, "dateFormat"), dates = inst.lastVal = inst.input ? inst.input.val() : null, defaultDate = this._getDefaultDate(inst), date = defaultDate, settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { dates = (noDefault ? "" : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, "defaultDate"), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }, offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(), year = date.getFullYear(), month = date.getMonth(), day = date.getDate(), pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, matches = pattern.exec(offset); while (matches) { switch (matches[2] || "d") { case "d" : case "D" : day += parseInt(matches[1],10); break; case "w" : case "W" : day += parseInt(matches[1],10) * 7; break; case "m" : case "M" : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case "y": case "Y" : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }, newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) : (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. * Hours may be non-zero on daylight saving cut-over: * > 12 when midnight changeover, but then cannot generate * midnight datetime, so jump to 1AM, otherwise reset. * @param date (Date) the date to check * @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) { return null; } date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date, origMonth = inst.selectedMonth, origYear = inst.selectedYear, newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) { this._notifyChange(inst); } this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? "" : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, "stepMonths"), id = "#" + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find("[data-handler]").map(function () { var handler = { prev: function () { $.datepicker._adjustDate(id, -stepMonths, "M"); }, next: function () { $.datepicker._adjustDate(id, +stepMonths, "M"); }, hide: function () { $.datepicker._hideDatepicker(); }, today: function () { $.datepicker._gotoToday(id); }, selectDay: function () { $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this); return false; }, selectMonth: function () { $.datepicker._selectMonthYear(id, this, "M"); return false; }, selectYear: function () { $.datepicker._selectMonthYear(id, this, "Y"); return false; } }; $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var maxDraw, prevText, prev, nextText, next, currentText, gotoDate, controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin, monthNames, monthNamesShort, beforeShowDay, showOtherMonths, selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate, cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows, printDate, dRow, tbody, daySettings, otherMonth, unselectable, tempDate = new Date(), today = this._daylightSavingAdjust( new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time isRTL = this._get(inst, "isRTL"), showButtonPanel = this._get(inst, "showButtonPanel"), hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"), navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"), numMonths = this._getNumberOfMonths(inst), showCurrentAtPos = this._get(inst, "showCurrentAtPos"), stepMonths = this._get(inst, "stepMonths"), isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1), currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))), minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), drawMonth = inst.drawMonth - showCurrentAtPos, drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; prevText = this._get(inst, "prevText"); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" + " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>")); nextText = this._get(inst, "nextText"); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" + " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>")); currentText = this._get(inst, "currentText"); gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" + this._get(inst, "closeText") + "</button>" : ""); buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") + (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" + ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : ""; firstDay = parseInt(this._get(inst, "firstDay"),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); showWeek = this._get(inst, "showWeek"); dayNames = this._get(inst, "dayNames"); dayNamesMin = this._get(inst, "dayNamesMin"); monthNames = this._get(inst, "monthNames"); monthNamesShort = this._get(inst, "monthNamesShort"); beforeShowDay = this._get(inst, "beforeShowDay"); showOtherMonths = this._get(inst, "showOtherMonths"); selectOtherMonths = this._get(inst, "selectOtherMonths"); defaultDate = this._getDefaultDate(inst); html = ""; dow; for (row = 0; row < numMonths[0]; row++) { group = ""; this.maxRows = 4; for (col = 0; col < numMonths[1]; col++) { selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); cornerClass = " ui-corner-all"; calender = ""; if (isMultiMonth) { calender += "<div class='ui-datepicker-group"; if (numMonths[1] > 1) { switch (col) { case 0: calender += " ui-datepicker-group-first"; cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break; case numMonths[1]-1: calender += " ui-datepicker-group-last"; cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break; default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break; } } calender += "'>"; } calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" + (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers "</div><table class='ui-datepicker-calendar'><thead>" + "<tr>"; thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : ""); for (dow = 0; dow < 7; dow++) { // days of the week day = (dow + firstDay) % 7; thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" + "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>"; } calender += thead + "</tr></thead><tbody>"; daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) { inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); } leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += "<tr>"; tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" + this._get(inst, "calculateWeek")(printDate) + "</td>"); for (dow = 0; dow < 7; dow++) { // create date picker days daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]); otherMonth = (printDate.getMonth() !== drawMonth); unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += "<td class='" + ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate " " + this._dayOverClass : "") + // highlight selected day (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions (otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" + (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") + (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + "</tr>"; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += "</tbody></table>" + (isMultiMonth ? "</div>" + ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : ""); group += calender; } html += group; } html += buttonPanel; inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear, changeMonth = this._get(inst, "changeMonth"), changeYear = this._get(inst, "changeYear"), showMonthAfterYear = this._get(inst, "showMonthAfterYear"), html = "<div class='ui-datepicker-title'>", monthHtml = ""; // month selection if (secondary || !changeMonth) { monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>"; } else { inMinYear = (minDate && minDate.getFullYear() === drawYear); inMaxYear = (maxDate && maxDate.getFullYear() === drawYear); monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>"; for ( month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) { monthHtml += "<option value='" + month + "'" + (month === drawMonth ? " selected='selected'" : "") + ">" + monthNamesShort[month] + "</option>"; } } monthHtml += "</select>"; } if (!showMonthAfterYear) { html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : ""); } // year selection if ( !inst.yearshtml ) { inst.yearshtml = ""; if (secondary || !changeYear) { html += "<span class='ui-datepicker-year'>" + drawYear + "</span>"; } else { // determine range of years to display years = this._get(inst, "yearRange").split(":"); thisYear = new Date().getFullYear(); determineYear = function(value) { var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; year = determineYear(years[0]); endYear = Math.max(year, determineYear(years[1] || "")); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"; for (; year <= endYear; year++) { inst.yearshtml += "<option value='" + year + "'" + (year === drawYear ? " selected='selected'" : "") + ">" + year + "</option>"; } inst.yearshtml += "</select>"; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, "yearSuffix"); if (showMonthAfterYear) { html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml; } html += "</div>"; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period === "Y" ? offset : 0), month = inst.drawMonth + (period === "M" ? offset : 0), day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0), date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period === "M" || period === "Y") { this._notifyChange(inst); } }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), newDate = (minDate && date < minDate ? minDate : date); return (maxDate && newDate > maxDate ? maxDate : newDate); }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, "onChangeMonthYear"); if (onChange) { onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); } }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, "numberOfMonths"); return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + "Date"), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst), date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) { date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); } return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var yearSplit, currentYear, minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), minYear = null, maxYear = null, years = this._get(inst, "yearRange"); if (years){ yearSplit = years.split(":"); currentYear = new Date().getFullYear(); minYear = parseInt(yearSplit[0], 10); maxYear = parseInt(yearSplit[1], 10); if ( yearSplit[0].match(/[+\-].*/) ) { minYear += currentYear; } if ( yearSplit[1].match(/[+\-].*/) ) { maxYear += currentYear; } } return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime()) && (!minYear || date.getFullYear() >= minYear) && (!maxYear || date.getFullYear() <= maxYear)); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, "shortYearCutoff"); shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"), monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day === "object" ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function datepicker_bindHover(dpDiv) { var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a"; return dpDiv.delegate(selector, "mouseout", function() { $(this).removeClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).removeClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).removeClass("ui-datepicker-next-hover"); } }) .delegate(selector, "mouseover", function(){ if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline ? dpDiv.parent()[0] : datepicker_instActive.input[0])) { $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"); $(this).addClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).addClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).addClass("ui-datepicker-next-hover"); } } }); } /* jQuery extend now ignores nulls! */ function datepicker_extendRemove(target, props) { $.extend(target, props); for (var name in props) { if (props[name] == null) { target[name] = props[name]; } } return target; } /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick); $.datepicker.initialized = true; } /* Append datepicker main container to body if not exist. */ if ($("#"+$.datepicker._mainDivId).length === 0) { $("body").append($.datepicker.dpDiv); } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } return this.each(function() { typeof options === "string" ? $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.11.0"; var datepicker = $.datepicker; /*! * jQuery UI Draggable 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/draggable/ */ $.widget("ui.draggable", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "drag", options: { addClasses: true, appendTo: "parent", axis: false, connectToSortable: false, containment: false, cursor: "auto", cursorAt: false, grid: false, handle: false, helper: "original", iframeFix: false, opacity: false, refreshPositions: false, revert: false, revertDuration: 500, scope: "default", scroll: true, scrollSensitivity: 20, scrollSpeed: 20, snap: false, snapMode: "both", snapTolerance: 20, stack: false, zIndex: false, // callbacks drag: null, start: null, stop: null }, _create: function() { if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) { this.element[0].style.position = "relative"; } if (this.options.addClasses){ this.element.addClass("ui-draggable"); } if (this.options.disabled){ this.element.addClass("ui-draggable-disabled"); } this._setHandleClassName(); this._mouseInit(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "handle" ) { this._setHandleClassName(); } }, _destroy: function() { if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) { this.destroyOnClear = true; return; } this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._removeHandleClassName(); this._mouseDestroy(); }, _mouseCapture: function(event) { var document = this.document[ 0 ], o = this.options; // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { // Support: IE9+ // If the <body> is blurred, IE will switch windows, see #9520 if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) { // Blur any element that currently has focus, see #4261 $( document.activeElement ).blur(); } } catch ( error ) {} // among others, prevent a drag on a resizable-handle if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) { return false; } //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) { return false; } $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>") .css({ width: this.offsetWidth + "px", height: this.offsetHeight + "px", position: "absolute", opacity: "0.001", zIndex: 1000 }) .css($(this).offset()) .appendTo("body"); }); return true; }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); this.helper.addClass("ui-draggable-dragging"); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if ($.ui.ddmanager) { $.ui.ddmanager.current = this; } /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css( "position" ); this.scrollParent = this.helper.scrollParent(); this.offsetParent = this.helper.offsetParent(); this.offsetParentCssPosition = this.offsetParent.css( "position" ); //The element's absolute position on the page minus margins this.offset = this.positionAbs = this.element.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; //Reset scroll cache this.offset.scroll = false; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); //Generate the original position this.originalPosition = this.position = this._generatePosition( event, false ); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Set a containment if given in the options this._setContainment(); //Trigger event + callbacks if (this._trigger("start", event) === false) { this._clear(); return false; } //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStart(this, event); } return true; }, _mouseDrag: function(event, noPropagation) { // reset any necessary cached properties (see #5009) if ( this.offsetParentCssPosition === "fixed" ) { this.offset.parent = this._getParentOffset(); } //Compute the helpers position this.position = this._generatePosition( event, true ); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); if (this._trigger("drag", event, ui) === false) { this._mouseUp({}); return false; } this.position = ui.position; } this.helper[ 0 ].style.left = this.position.left + "px"; this.helper[ 0 ].style.top = this.position.top + "px"; if ($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var that = this, dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) { dropped = $.ui.ddmanager.drop(this, event); } //if a drop comes from outside (a sortable) if (this.dropped) { dropped = this.dropped; this.dropped = false; } if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { if (that._trigger("stop", event) !== false) { that._clear(); } }); } else { if (this._trigger("stop", event) !== false) { this._clear(); } } return false; }, _mouseUp: function(event) { //Remove frame helpers $("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStop(this, event); } // The interaction is over; whether or not the click resulted in a drag, focus the element this.element.focus(); return $.ui.mouse.prototype._mouseUp.call(this, event); }, cancel: function() { if (this.helper.is(".ui-draggable-dragging")) { this._mouseUp({}); } else { this._clear(); } return this; }, _getHandle: function(event) { return this.options.handle ? !!$( event.target ).closest( this.element.find( this.options.handle ) ).length : true; }, _setHandleClassName: function() { this._removeHandleClassName(); $( this.options.handle || this.element ).addClass( "ui-draggable-handle" ); }, _removeHandleClassName: function() { this.element.find( ".ui-draggable-handle" ) .addBack() .removeClass( "ui-draggable-handle" ); }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[ 0 ], [ event ])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element); if (!helper.parents("body").length) { helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo)); } if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { helper.css("position", "absolute"); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = { left: +obj[0], top: +obj[1] || 0 }; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _isRootNode: function( element ) { return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ]; }, _getParentOffset: function() { //Get the offsetParent and cache its position var po = this.offsetParent.offset(), document = this.document[ 0 ]; // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if ( this._isRootNode( this.offsetParent[ 0 ] ) ) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if ( this.cssPosition !== "relative" ) { return { top: 0, left: 0 }; } var p = this.element.position(), scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ), left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 ) }; }, _cacheMargins: function() { this.margins = { left: (parseInt(this.element.css("marginLeft"),10) || 0), top: (parseInt(this.element.css("marginTop"),10) || 0), right: (parseInt(this.element.css("marginRight"),10) || 0), bottom: (parseInt(this.element.css("marginBottom"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var over, c, ce, o = this.options, document = this.document[ 0 ]; this.relative_container = null; if ( !o.containment ) { this.containment = null; return; } if ( o.containment === "window" ) { this.containment = [ $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left, $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top, $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left, $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment === "document") { this.containment = [ 0, 0, $( document ).width() - this.helperProportions.width - this.margins.left, ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment.constructor === Array ) { this.containment = o.containment; return; } if ( o.containment === "parent" ) { o.containment = this.helper[ 0 ].parentNode; } c = $( o.containment ); ce = c[ 0 ]; if ( !ce ) { return; } over = c.css( "overflow" ) !== "hidden"; this.containment = [ ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ), ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ), ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right, ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom ]; this.relative_container = c; }, _convertPositionTo: function(d, pos) { if (!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod) ) }; }, _generatePosition: function( event, constrainPosition ) { var containment, co, top, left, o = this.options, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ), pageX = event.pageX, pageY = event.pageY; // Cache the scroll if ( !scrollIsRootNode || !this.offset.scroll ) { this.offset.scroll = { top: this.scrollParent.scrollTop(), left: this.scrollParent.scrollLeft() }; } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ // If we are not dragging yet, we won't check for options if ( constrainPosition ) { if ( this.containment ) { if ( this.relative_container ){ co = this.relative_container.offset(); containment = [ this.containment[ 0 ] + co.left, this.containment[ 1 ] + co.top, this.containment[ 2 ] + co.left, this.containment[ 3 ] + co.top ]; } else { containment = this.containment; } if (event.pageX - this.offset.click.left < containment[0]) { pageX = containment[0] + this.offset.click.left; } if (event.pageY - this.offset.click.top < containment[1]) { pageY = containment[1] + this.offset.click.top; } if (event.pageX - this.offset.click.left > containment[2]) { pageX = containment[2] + this.offset.click.left; } if (event.pageY - this.offset.click.top > containment[3]) { pageY = containment[3] + this.offset.click.top; } } if (o.grid) { //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } if ( o.axis === "y" ) { pageX = this.originalPageX; } if ( o.axis === "x" ) { pageY = this.originalPageY; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) { this.helper.remove(); } this.helper = null; this.cancelHelperRemoval = false; if ( this.destroyOnClear ) { this.destroy(); } }, // From now on bulk stuff - mainly helpers _trigger: function(type, event, ui) { ui = ui || this._uiHash(); $.ui.plugin.call( this, type, [ event, ui, this ], true ); //The absolute position has to be recalculated after plugins if (type === "drag") { this.positionAbs = this._convertPositionTo("absolute"); } return $.Widget.prototype._trigger.call(this, type, event, ui); }, plugins: {}, _uiHash: function() { return { helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs }; } }); $.ui.plugin.add("draggable", "connectToSortable", { start: function( event, ui, inst ) { var o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element }); inst.sortables = []; $(o.connectToSortable).each(function() { var sortable = $( this ).sortable( "instance" ); if (sortable && !sortable.options.disabled) { inst.sortables.push({ instance: sortable, shouldRevert: sortable.options.revert }); sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page). sortable._trigger("activate", event, uiSortable); } }); }, stop: function( event, ui, inst ) { //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper var uiSortable = $.extend( {}, ui, { item: inst.element }); $.each(inst.sortables, function() { if (this.instance.isOver) { this.instance.isOver = 0; inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid" if (this.shouldRevert) { this.instance.options.revert = this.shouldRevert; } //Trigger the stop of the sortable this.instance._mouseStop(event); this.instance.options.helper = this.instance.options._helper; //If the helper has been the original item, restore properties in the sortable if (inst.options.helper === "original") { this.instance.currentItem.css({ top: "auto", left: "auto" }); } } else { this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance this.instance._trigger("deactivate", event, uiSortable); } }); }, drag: function( event, ui, inst ) { var that = this; $.each(inst.sortables, function() { var innermostIntersecting = false, thisSortable = this; //Copy over some variables to allow calling the sortable's native _intersectsWith this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this.instance._intersectsWith(this.instance.containerCache)) { innermostIntersecting = true; $.each(inst.sortables, function() { this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this !== thisSortable && this.instance._intersectsWith(this.instance.containerCache) && $.contains(thisSortable.instance.element[0], this.instance.element[0]) ) { innermostIntersecting = false; } return innermostIntersecting; }); } if (innermostIntersecting) { //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once if (!this.instance.isOver) { this.instance.isOver = 1; //Now we fake the start of dragging for the sortable instance, //by cloning the list group item, appending it to the sortable and using it as inst.currentItem //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true); this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it this.instance.options.helper = function() { return ui.helper[0]; }; event.target = this.instance.currentItem[0]; this.instance._mouseCapture(event, true); this.instance._mouseStart(event, true, true); //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes this.instance.offset.click.top = inst.offset.click.top; this.instance.offset.click.left = inst.offset.click.left; this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; inst._trigger("toSortable", event); inst.dropped = this.instance.element; //draggable revert needs that //hack so receive/update callbacks work (mostly) inst.currentItem = inst.element; this.instance.fromOutside = inst; } //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable if (this.instance.currentItem) { this.instance._mouseDrag(event); } } else { //If it doesn't intersect with the sortable, and it intersected before, //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval if (this.instance.isOver) { this.instance.isOver = 0; this.instance.cancelHelperRemoval = true; //Prevent reverting on this forced stop this.instance.options.revert = false; // The out event needs to be triggered independently this.instance._trigger("out", event, this.instance._uiHash(this.instance)); this.instance._mouseStop(event, true); this.instance.options.helper = this.instance.options._helper; //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size this.instance.currentItem.remove(); if (this.instance.placeholder) { this.instance.placeholder.remove(); } inst._trigger("fromSortable", event); inst.dropped = false; //draggable revert needs that } } }); } }); $.ui.plugin.add("draggable", "cursor", { start: function( event, ui, instance ) { var t = $( "body" ), o = instance.options; if (t.css("cursor")) { o._cursor = t.css("cursor"); } t.css("cursor", o.cursor); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._cursor) { $("body").css("cursor", o._cursor); } } }); $.ui.plugin.add("draggable", "opacity", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("opacity")) { o._opacity = t.css("opacity"); } t.css("opacity", o.opacity); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._opacity) { $(ui.helper).css("opacity", o._opacity); } } }); $.ui.plugin.add("draggable", "scroll", { start: function( event, ui, i ) { if ( i.scrollParent[ 0 ] !== i.document[ 0 ] && i.scrollParent[ 0 ].tagName !== "HTML" ) { i.overflowOffset = i.scrollParent.offset(); } }, drag: function( event, ui, i ) { var o = i.options, scrolled = false, document = i.document[ 0 ]; if ( i.scrollParent[ 0 ] !== document && i.scrollParent[ 0 ].tagName !== "HTML" ) { if (!o.axis || o.axis !== "x") { if ((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; } else if (event.pageY - i.overflowOffset.top < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; } } if (!o.axis || o.axis !== "y") { if ((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; } else if (event.pageX - i.overflowOffset.left < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed; } } } else { if (!o.axis || o.axis !== "x") { if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } } if (!o.axis || o.axis !== "y") { if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } } if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(i, event); } } }); $.ui.plugin.add("draggable", "snap", { start: function( event, ui, i ) { var o = i.options; i.snapElements = []; $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() { var $t = $(this), $o = $t.offset(); if (this !== i.element[0]) { i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); } }); }, drag: function( event, ui, inst ) { var ts, bs, ls, rs, l, r, t, b, i, first, o = inst.options, d = o.snapTolerance, x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (i = inst.snapElements.length - 1; i >= 0; i--){ l = inst.snapElements[i].left; r = l + inst.snapElements[i].width; t = inst.snapElements[i].top; b = t + inst.snapElements[i].height; if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) { if (inst.snapElements[i].snapping) { (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = false; continue; } if (o.snapMode !== "inner") { ts = Math.abs(t - y2) <= d; bs = Math.abs(b - y1) <= d; ls = Math.abs(l - x2) <= d; rs = Math.abs(r - x1) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left; } } first = (ts || bs || ls || rs); if (o.snapMode !== "outer") { ts = Math.abs(t - y1) <= d; bs = Math.abs(b - y2) <= d; ls = Math.abs(l - x1) <= d; rs = Math.abs(r - x2) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left; } } if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) { (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = (ts || bs || ls || rs || first); } } }); $.ui.plugin.add("draggable", "stack", { start: function( event, ui, instance ) { var min, o = instance.options, group = $.makeArray($(o.stack)).sort(function(a,b) { return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $(this).css("zIndex", min + i); }); this.css("zIndex", (min + group.length)); } }); $.ui.plugin.add("draggable", "zIndex", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("zIndex")) { o._zIndex = t.css("zIndex"); } t.css("zIndex", o.zIndex); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._zIndex) { $(ui.helper).css("zIndex", o._zIndex); } } }); var draggable = $.ui.draggable; /*! * jQuery UI Resizable 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/resizable/ */ $.widget("ui.resizable", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "resize", options: { alsoResize: false, animate: false, animateDuration: "slow", animateEasing: "swing", aspectRatio: false, autoHide: false, containment: false, ghost: false, grid: false, handles: "e,s,se", helper: false, maxHeight: null, maxWidth: null, minHeight: 10, minWidth: 10, // See #7960 zIndex: 90, // callbacks resize: null, start: null, stop: null }, _num: function( value ) { return parseInt( value, 10 ) || 0; }, _isNumber: function( value ) { return !isNaN( parseInt( value , 10 ) ); }, _hasScroll: function( el, a ) { if ( $( el ).css( "overflow" ) === "hidden") { return false; } var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", has = false; if ( el[ scroll ] > 0 ) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[ scroll ] = 1; has = ( el[ scroll ] > 0 ); el[ scroll ] = 0; return has; }, _create: function() { var n, i, handle, axis, hname, that = this, o = this.options; this.element.addClass("ui-resizable"); $.extend(this, { _aspectRatio: !!(o.aspectRatio), aspectRatio: o.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null }); // Wrap the element if it cannot hold child nodes if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { this.element.wrap( $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({ position: this.element.css("position"), width: this.element.outerWidth(), height: this.element.outerHeight(), top: this.element.css("top"), left: this.element.css("left") }) ); this.element = this.element.parent().data( "ui-resizable", this.element.resizable( "instance" ) ); this.elementIsWrapper = true; this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); // support: Safari // Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css("resize"); this.originalElement.css("resize", "none"); this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" })); // support: IE9 // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css("margin") }); this._proportionallyResize(); } this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" }); if(this.handles.constructor === String) { if ( this.handles === "all") { this.handles = "n,e,s,w,se,sw,ne,nw"; } n = this.handles.split(","); this.handles = {}; for(i = 0; i < n.length; i++) { handle = $.trim(n[i]); hname = "ui-resizable-"+handle; axis = $("<div class='ui-resizable-handle " + hname + "'></div>"); axis.css({ zIndex: o.zIndex }); // TODO : What's going on here? if ("se" === handle) { axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se"); } this.handles[handle] = ".ui-resizable-"+handle; this.element.append(axis); } } this._renderAxis = function(target) { var i, axis, padPos, padWrapper; target = target || this.element; for(i in this.handles) { if(this.handles[i].constructor === String) { this.handles[i] = this.element.children( this.handles[ i ] ).first().show(); } if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { axis = $(this.handles[i], this.element); padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); padPos = [ "padding", /ne|nw|n/.test(i) ? "Top" : /se|sw|s/.test(i) ? "Bottom" : /^e$/.test(i) ? "Right" : "Left" ].join(""); target.css(padPos, padWrapper); this._proportionallyResize(); } // TODO: What's that good for? There's not anything to be executed left if(!$(this.handles[i]).length) { continue; } } }; // TODO: make renderAxis a prototype function this._renderAxis(this.element); this._handles = $(".ui-resizable-handle", this.element) .disableSelection(); this._handles.mouseover(function() { if (!that.resizing) { if (this.className) { axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); } that.axis = axis && axis[1] ? axis[1] : "se"; } }); if (o.autoHide) { this._handles.hide(); $(this.element) .addClass("ui-resizable-autohide") .mouseenter(function() { if (o.disabled) { return; } $(this).removeClass("ui-resizable-autohide"); that._handles.show(); }) .mouseleave(function(){ if (o.disabled) { return; } if (!that.resizing) { $(this).addClass("ui-resizable-autohide"); that._handles.hide(); } }); } this._mouseInit(); }, _destroy: function() { this._mouseDestroy(); var wrapper, _destroy = function(exp) { $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") .removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove(); }; // TODO: Unwrap at same DOM position if (this.elementIsWrapper) { _destroy(this.element); wrapper = this.element; this.originalElement.css({ position: wrapper.css("position"), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css("top"), left: wrapper.css("left") }).insertAfter( wrapper ); wrapper.remove(); } this.originalElement.css("resize", this.originalResizeStyle); _destroy(this.originalElement); return this; }, _mouseCapture: function(event) { var i, handle, capture = false; for (i in this.handles) { handle = $(this.handles[i])[0]; if (handle === event.target || $.contains(handle, event.target)) { capture = true; } } return !this.options.disabled && capture; }, _mouseStart: function(event) { var curleft, curtop, cursor, o = this.options, el = this.element; this.resizing = true; this._renderProxy(); curleft = this._num(this.helper.css("left")); curtop = this._num(this.helper.css("top")); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: this.helper.width(), height: this.helper.height() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); cursor = $(".ui-resizable-" + this.axis).css("cursor"); $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor); el.addClass("ui-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { var data, el = this.helper, props = {}, smp = this.originalMousePosition, a = this.axis, dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0, trigger = this._change[a]; this.prevPosition = { top: this.position.top, left: this.position.left }; this.prevSize = { width: this.size.width, height: this.size.height }; if (!trigger) { return false; } data = trigger.apply(this, [event, dx, dy]); this._updateVirtualBoundaries(event.shiftKey); if (this._aspectRatio || event.shiftKey) { data = this._updateRatio(data, event); } data = this._respectSize(data, event); this._updateCache(data); this._propagate("resize", event); if ( this.position.top !== this.prevPosition.top ) { props.top = this.position.top + "px"; } if ( this.position.left !== this.prevPosition.left ) { props.left = this.position.left + "px"; } if ( this.size.width !== this.prevSize.width ) { props.width = this.size.width + "px"; } if ( this.size.height !== this.prevSize.height ) { props.height = this.size.height + "px"; } el.css( props ); if ( !this._helper && this._proportionallyResizeElements.length ) { this._proportionallyResize(); } if ( !$.isEmptyObject( props ) ) { this._trigger( "resize", event, this.ui() ); } return false; }, _mouseStop: function(event) { this.resizing = false; var pr, ista, soffseth, soffsetw, s, left, top, o = this.options, that = this; if(this._helper) { pr = this._proportionallyResizeElements; ista = pr.length && (/textarea/i).test(pr[0].nodeName); soffseth = ista && this._hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height; soffsetw = ista ? 0 : that.sizeDiff.width; s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) }; left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null; top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; if (!o.animate) { this.element.css($.extend(s, { top: top, left: left })); } that.helper.height(that.size.height); that.helper.width(that.size.width); if (this._helper && !o.animate) { this._proportionallyResize(); } } $("body").css("cursor", "auto"); this.element.removeClass("ui-resizable-resizing"); this._propagate("stop", event); if (this._helper) { this.helper.remove(); } return false; }, _updateVirtualBoundaries: function(forceAspectRatio) { var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b, o = this.options; b = { minWidth: this._isNumber(o.minWidth) ? o.minWidth : 0, maxWidth: this._isNumber(o.maxWidth) ? o.maxWidth : Infinity, minHeight: this._isNumber(o.minHeight) ? o.minHeight : 0, maxHeight: this._isNumber(o.maxHeight) ? o.maxHeight : Infinity }; if(this._aspectRatio || forceAspectRatio) { pMinWidth = b.minHeight * this.aspectRatio; pMinHeight = b.minWidth / this.aspectRatio; pMaxWidth = b.maxHeight * this.aspectRatio; pMaxHeight = b.maxWidth / this.aspectRatio; if(pMinWidth > b.minWidth) { b.minWidth = pMinWidth; } if(pMinHeight > b.minHeight) { b.minHeight = pMinHeight; } if(pMaxWidth < b.maxWidth) { b.maxWidth = pMaxWidth; } if(pMaxHeight < b.maxHeight) { b.maxHeight = pMaxHeight; } } this._vBoundaries = b; }, _updateCache: function(data) { this.offset = this.helper.offset(); if (this._isNumber(data.left)) { this.position.left = data.left; } if (this._isNumber(data.top)) { this.position.top = data.top; } if (this._isNumber(data.height)) { this.size.height = data.height; } if (this._isNumber(data.width)) { this.size.width = data.width; } }, _updateRatio: function( data ) { var cpos = this.position, csize = this.size, a = this.axis; if (this._isNumber(data.height)) { data.width = (data.height * this.aspectRatio); } else if (this._isNumber(data.width)) { data.height = (data.width / this.aspectRatio); } if (a === "sw") { data.left = cpos.left + (csize.width - data.width); data.top = null; } if (a === "nw") { data.top = cpos.top + (csize.height - data.height); data.left = cpos.left + (csize.width - data.width); } return data; }, _respectSize: function( data ) { var o = this._vBoundaries, a = this.axis, ismaxw = this._isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = this._isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = this._isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = this._isNumber(data.height) && o.minHeight && (o.minHeight > data.height), dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height, cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); if (isminw) { data.width = o.minWidth; } if (isminh) { data.height = o.minHeight; } if (ismaxw) { data.width = o.maxWidth; } if (ismaxh) { data.height = o.maxHeight; } if (isminw && cw) { data.left = dw - o.minWidth; } if (ismaxw && cw) { data.left = dw - o.maxWidth; } if (isminh && ch) { data.top = dh - o.minHeight; } if (ismaxh && ch) { data.top = dh - o.maxHeight; } // Fixing jump error on top/left - bug #2330 if (!data.width && !data.height && !data.left && data.top) { data.top = null; } else if (!data.width && !data.height && !data.top && data.left) { data.left = null; } return data; }, _proportionallyResize: function() { if (!this._proportionallyResizeElements.length) { return; } var i, j, borders, paddings, prel, element = this.helper || this.element; for ( i=0; i < this._proportionallyResizeElements.length; i++) { prel = this._proportionallyResizeElements[i]; if (!this.borderDif) { this.borderDif = []; borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")]; paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")]; for ( j = 0; j < borders.length; j++ ) { this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 ); } } prel.css({ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 }); } }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if(this._helper) { this.helper = this.helper || $("<div style='overflow:hidden;'></div>"); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() - 1, height: this.element.outerHeight() - 1, position: "absolute", left: this.elementOffset.left +"px", top: this.elementOffset.top +"px", zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx) { return { width: this.originalSize.width + dx }; }, w: function(event, dx) { var cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(event, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); } }, _propagate: function(n, event) { $.ui.plugin.call(this, n, [event, this.ui()]); (n !== "resize" && this._trigger(n, event, this.ui())); }, plugins: {}, ui: function() { return { originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, originalSize: this.originalSize, originalPosition: this.originalPosition, prevSize: this.prevSize, prevPosition: this.prevPosition }; } }); /* * Resizable Extensions */ $.ui.plugin.add("resizable", "animate", { stop: function( event ) { var that = $(this).resizable( "instance" ), o = that.options, pr = that._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && that._hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height, soffsetw = ista ? 0 : that.sizeDiff.width, style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) }, left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null, top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; that.element.animate( $.extend(style, top && left ? { top: top, left: left } : {}), { duration: o.animateDuration, easing: o.animateEasing, step: function() { var data = { width: parseInt(that.element.css("width"), 10), height: parseInt(that.element.css("height"), 10), top: parseInt(that.element.css("top"), 10), left: parseInt(that.element.css("left"), 10) }; if (pr && pr.length) { $(pr[0]).css({ width: data.width, height: data.height }); } // propagating resize, and updating values for each animation step that._updateCache(data); that._propagate("resize", event); } } ); } }); $.ui.plugin.add( "resizable", "containment", { start: function() { var element, p, co, ch, cw, width, height, that = $( this ).resizable( "instance" ), o = that.options, el = that.element, oc = o.containment, ce = ( oc instanceof $ ) ? oc.get( 0 ) : ( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc; if ( !ce ) { return; } that.containerElement = $( ce ); if ( /document/.test( oc ) || oc === document ) { that.containerOffset = { left: 0, top: 0 }; that.containerPosition = { left: 0, top: 0 }; that.parentData = { element: $( document ), left: 0, top: 0, width: $( document ).width(), height: $( document ).height() || document.body.parentNode.scrollHeight }; } else { element = $( ce ); p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function( i, name ) { p[ i ] = that._num( element.css( "padding" + name ) ); }); that.containerOffset = element.offset(); that.containerPosition = element.position(); that.containerSize = { height: ( element.innerHeight() - p[ 3 ] ), width: ( element.innerWidth() - p[ 1 ] ) }; co = that.containerOffset; ch = that.containerSize.height; cw = that.containerSize.width; width = ( that._hasScroll ( ce, "left" ) ? ce.scrollWidth : cw ); height = ( that._hasScroll ( ce ) ? ce.scrollHeight : ch ) ; that.parentData = { element: ce, left: co.left, top: co.top, width: width, height: height }; } }, resize: function( event, ui ) { var woset, hoset, isParent, isOffsetRelative, that = $( this ).resizable( "instance" ), o = that.options, co = that.containerOffset, cp = that.position, pRatio = that._aspectRatio || event.shiftKey, cop = { top: 0, left: 0 }, ce = that.containerElement, continueResize = true; if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) { cop = co; } if ( cp.left < ( that._helper ? co.left : 0 ) ) { that.size.width = that.size.width + ( that._helper ? ( that.position.left - co.left ) : ( that.position.left - cop.left ) ); if ( pRatio ) { that.size.height = that.size.width / that.aspectRatio; continueResize = false; } that.position.left = o.helper ? co.left : 0; } if ( cp.top < ( that._helper ? co.top : 0 ) ) { that.size.height = that.size.height + ( that._helper ? ( that.position.top - co.top ) : that.position.top ); if ( pRatio ) { that.size.width = that.size.height * that.aspectRatio; continueResize = false; } that.position.top = that._helper ? co.top : 0; } that.offset.left = that.parentData.left + that.position.left; that.offset.top = that.parentData.top + that.position.top; woset = Math.abs( ( that._helper ? that.offset.left - cop.left : ( that.offset.left - co.left ) ) + that.sizeDiff.width ); hoset = Math.abs( ( that._helper ? that.offset.top - cop.top : ( that.offset.top - co.top ) ) + that.sizeDiff.height ); isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 ); isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) ); if ( isParent && isOffsetRelative ) { woset -= Math.abs( that.parentData.left ); } if ( woset + that.size.width >= that.parentData.width ) { that.size.width = that.parentData.width - woset; if ( pRatio ) { that.size.height = that.size.width / that.aspectRatio; continueResize = false; } } if ( hoset + that.size.height >= that.parentData.height ) { that.size.height = that.parentData.height - hoset; if ( pRatio ) { that.size.width = that.size.height * that.aspectRatio; continueResize = false; } } if ( !continueResize ){ that.position.left = ui.prevPosition.left; that.position.top = ui.prevPosition.top; that.size.width = ui.prevSize.width; that.size.height = ui.prevSize.height; } }, stop: function(){ var that = $( this ).resizable( "instance" ), o = that.options, co = that.containerOffset, cop = that.containerPosition, ce = that.containerElement, helper = $( that.helper ), ho = helper.offset(), w = helper.outerWidth() - that.sizeDiff.width, h = helper.outerHeight() - that.sizeDiff.height; if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) { $( this ).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) { $( this ).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } } }); $.ui.plugin.add("resizable", "alsoResize", { start: function () { var that = $(this).resizable( "instance" ), o = that.options, _store = function (exp) { $(exp).each(function() { var el = $(this); el.data("ui-resizable-alsoresize", { width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10) }); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) { if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } else { $.each(o.alsoResize, function (exp) { _store(exp); }); } }else{ _store(o.alsoResize); } }, resize: function (event, ui) { var that = $(this).resizable( "instance" ), o = that.options, os = that.originalSize, op = that.originalPosition, delta = { height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0, top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0 }, _alsoResize = function (exp, c) { $(exp).each(function() { var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {}, css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"]; $.each(css, function (i, prop) { var sum = (start[prop]||0) + (delta[prop]||0); if (sum && sum >= 0) { style[prop] = sum || null; } }); el.css(style); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) { $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); }); }else{ _alsoResize(o.alsoResize); } }, stop: function () { $(this).removeData("resizable-alsoresize"); } }); $.ui.plugin.add("resizable", "ghost", { start: function() { var that = $(this).resizable( "instance" ), o = that.options, cs = that.size; that.ghost = that.originalElement.clone(); that.ghost .css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) .addClass("ui-resizable-ghost") .addClass(typeof o.ghost === "string" ? o.ghost : ""); that.ghost.appendTo(that.helper); }, resize: function(){ var that = $(this).resizable( "instance" ); if (that.ghost) { that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width }); } }, stop: function() { var that = $(this).resizable( "instance" ); if (that.ghost && that.helper) { that.helper.get(0).removeChild(that.ghost.get(0)); } } }); $.ui.plugin.add("resizable", "grid", { resize: function() { var that = $(this).resizable( "instance" ), o = that.options, cs = that.size, os = that.originalSize, op = that.originalPosition, a = that.axis, grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid, gridX = (grid[0]||1), gridY = (grid[1]||1), ox = Math.round((cs.width - os.width) / gridX) * gridX, oy = Math.round((cs.height - os.height) / gridY) * gridY, newWidth = os.width + ox, newHeight = os.height + oy, isMaxWidth = o.maxWidth && (o.maxWidth < newWidth), isMaxHeight = o.maxHeight && (o.maxHeight < newHeight), isMinWidth = o.minWidth && (o.minWidth > newWidth), isMinHeight = o.minHeight && (o.minHeight > newHeight); o.grid = grid; if (isMinWidth) { newWidth = newWidth + gridX; } if (isMinHeight) { newHeight = newHeight + gridY; } if (isMaxWidth) { newWidth = newWidth - gridX; } if (isMaxHeight) { newHeight = newHeight - gridY; } if (/^(se|s|e)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; } else if (/^(ne)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.left = op.left - ox; } else { if ( newHeight - gridY > 0 ) { that.size.height = newHeight; that.position.top = op.top - oy; } else { that.size.height = gridY; that.position.top = op.top + os.height - gridY; } if ( newWidth - gridX > 0 ) { that.size.width = newWidth; that.position.left = op.left - ox; } else { that.size.width = gridX; that.position.left = op.left + os.width - gridX; } } } }); var resizable = $.ui.resizable; /*! * jQuery UI Dialog 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/dialog/ */ var dialog = $.widget( "ui.dialog", { version: "1.11.0", options: { appendTo: "body", autoOpen: true, buttons: [], closeOnEscape: true, closeText: "Close", dialogClass: "", draggable: true, hide: null, height: "auto", maxHeight: null, maxWidth: null, minHeight: 150, minWidth: 150, modal: false, position: { my: "center", at: "center", of: window, collision: "fit", // Ensure the titlebar is always visible using: function( pos ) { var topOffset = $( this ).css( pos ).offset().top; if ( topOffset < 0 ) { $( this ).css( "top", pos.top - topOffset ); } } }, resizable: true, show: null, title: null, width: 300, // callbacks beforeClose: null, close: null, drag: null, dragStart: null, dragStop: null, focus: null, open: null, resize: null, resizeStart: null, resizeStop: null }, sizeRelatedOptions: { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions: { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }, _create: function() { this.originalCss = { display: this.element[ 0 ].style.display, width: this.element[ 0 ].style.width, minHeight: this.element[ 0 ].style.minHeight, maxHeight: this.element[ 0 ].style.maxHeight, height: this.element[ 0 ].style.height }; this.originalPosition = { parent: this.element.parent(), index: this.element.parent().children().index( this.element ) }; this.originalTitle = this.element.attr( "title" ); this.options.title = this.options.title || this.originalTitle; this._createWrapper(); this.element .show() .removeAttr( "title" ) .addClass( "ui-dialog-content ui-widget-content" ) .appendTo( this.uiDialog ); this._createTitlebar(); this._createButtonPane(); if ( this.options.draggable && $.fn.draggable ) { this._makeDraggable(); } if ( this.options.resizable && $.fn.resizable ) { this._makeResizable(); } this._isOpen = false; this._trackFocus(); }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element && (element.jquery || element.nodeType) ) { return $( element ); } return this.document.find( element || "body" ).eq( 0 ); }, _destroy: function() { var next, originalPosition = this.originalPosition; this._destroyOverlay(); this.element .removeUniqueId() .removeClass( "ui-dialog-content ui-widget-content" ) .css( this.originalCss ) // Without detaching first, the following becomes really slow .detach(); this.uiDialog.stop( true, true ).remove(); if ( this.originalTitle ) { this.element.attr( "title", this.originalTitle ); } next = originalPosition.parent.children().eq( originalPosition.index ); // Don't try to place the dialog next to itself (#8613) if ( next.length && next[ 0 ] !== this.element[ 0 ] ) { next.before( this.element ); } else { originalPosition.parent.append( this.element ); } }, widget: function() { return this.uiDialog; }, disable: $.noop, enable: $.noop, close: function( event ) { var activeElement, that = this; if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) { return; } this._isOpen = false; this._focusedElement = null; this._destroyOverlay(); this._untrackInstance(); if ( !this.opener.filter( ":focusable" ).focus().length ) { // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { activeElement = this.document[ 0 ].activeElement; // Support: IE9, IE10 // If the <body> is blurred, IE will switch windows, see #4520 if ( activeElement && activeElement.nodeName.toLowerCase() !== "body" ) { // Hiding a focused element doesn't trigger blur in WebKit // so in case we have nothing to focus on, explicitly blur the active element // https://bugs.webkit.org/show_bug.cgi?id=47182 $( activeElement ).blur(); } } catch ( error ) {} } this._hide( this.uiDialog, this.options.hide, function() { that._trigger( "close", event ); }); }, isOpen: function() { return this._isOpen; }, moveToTop: function() { this._moveToTop(); }, _moveToTop: function( event, silent ) { var moved = false, zIndicies = this.uiDialog.siblings( ".ui-front:visible" ).map(function() { return +$( this ).css( "z-index" ); }).get(), zIndexMax = Math.max.apply( null, zIndicies ); if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) { this.uiDialog.css( "z-index", zIndexMax + 1 ); moved = true; } if ( moved && !silent ) { this._trigger( "focus", event ); } return moved; }, open: function() { var that = this; if ( this._isOpen ) { if ( this._moveToTop() ) { this._focusTabbable(); } return; } this._isOpen = true; this.opener = $( this.document[ 0 ].activeElement ); this._size(); this._position(); this._createOverlay(); this._moveToTop( null, true ); this._show( this.uiDialog, this.options.show, function() { that._focusTabbable(); that._trigger( "focus" ); }); this._trigger( "open" ); }, _focusTabbable: function() { // Set focus to the first match: // 1. An element that was focused previously // 2. First element inside the dialog matching [autofocus] // 3. Tabbable element inside the content element // 4. Tabbable element inside the buttonpane // 5. The close button // 6. The dialog itself var hasFocus = this._focusedElement; if ( !hasFocus ) { hasFocus = this.element.find( "[autofocus]" ); } if ( !hasFocus.length ) { hasFocus = this.element.find( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialogButtonPane.find( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialog; } hasFocus.eq( 0 ).focus(); }, _keepFocus: function( event ) { function checkFocus() { var activeElement = this.document[0].activeElement, isActive = this.uiDialog[0] === activeElement || $.contains( this.uiDialog[0], activeElement ); if ( !isActive ) { this._focusTabbable(); } } event.preventDefault(); checkFocus.call( this ); // support: IE // IE <= 8 doesn't prevent moving focus even with event.preventDefault() // so we check again later this._delay( checkFocus ); }, _createWrapper: function() { this.uiDialog = $("<div>") .addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " + this.options.dialogClass ) .hide() .attr({ // Setting tabIndex makes the div focusable tabIndex: -1, role: "dialog" }) .appendTo( this._appendTo() ); this._on( this.uiDialog, { keydown: function( event ) { if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE ) { event.preventDefault(); this.close( event ); return; } // prevent tabbing out of dialogs if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) { return; } var tabbables = this.uiDialog.find( ":tabbable" ), first = tabbables.filter( ":first" ), last = tabbables.filter( ":last" ); if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) { this._delay(function() { first.focus(); }); event.preventDefault(); } else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) { this._delay(function() { last.focus(); }); event.preventDefault(); } }, mousedown: function( event ) { if ( this._moveToTop( event ) ) { this._focusTabbable(); } } }); // We assume that any existing aria-describedby attribute means // that the dialog content is marked up properly // otherwise we brute force the content as the description if ( !this.element.find( "[aria-describedby]" ).length ) { this.uiDialog.attr({ "aria-describedby": this.element.uniqueId().attr( "id" ) }); } }, _createTitlebar: function() { var uiDialogTitle; this.uiDialogTitlebar = $( "<div>" ) .addClass( "ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix" ) .prependTo( this.uiDialog ); this._on( this.uiDialogTitlebar, { mousedown: function( event ) { // Don't prevent click on close button (#8838) // Focusing a dialog that is partially scrolled out of view // causes the browser to scroll it into view, preventing the click event if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) { // Dialog isn't getting focus when dragging (#8063) this.uiDialog.focus(); } } }); // support: IE // Use type="button" to prevent enter keypresses in textboxes from closing the // dialog in IE (#9312) this.uiDialogTitlebarClose = $( "<button type='button'></button>" ) .button({ label: this.options.closeText, icons: { primary: "ui-icon-closethick" }, text: false }) .addClass( "ui-dialog-titlebar-close" ) .appendTo( this.uiDialogTitlebar ); this._on( this.uiDialogTitlebarClose, { click: function( event ) { event.preventDefault(); this.close( event ); } }); uiDialogTitle = $( "<span>" ) .uniqueId() .addClass( "ui-dialog-title" ) .prependTo( this.uiDialogTitlebar ); this._title( uiDialogTitle ); this.uiDialog.attr({ "aria-labelledby": uiDialogTitle.attr( "id" ) }); }, _title: function( title ) { if ( !this.options.title ) { title.html( "&#160;" ); } title.text( this.options.title ); }, _createButtonPane: function() { this.uiDialogButtonPane = $( "<div>" ) .addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" ); this.uiButtonSet = $( "<div>" ) .addClass( "ui-dialog-buttonset" ) .appendTo( this.uiDialogButtonPane ); this._createButtons(); }, _createButtons: function() { var that = this, buttons = this.options.buttons; // if we already have a button pane, remove it this.uiDialogButtonPane.remove(); this.uiButtonSet.empty(); if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) { this.uiDialog.removeClass( "ui-dialog-buttons" ); return; } $.each( buttons, function( name, props ) { var click, buttonOptions; props = $.isFunction( props ) ? { click: props, text: name } : props; // Default to a non-submitting button props = $.extend( { type: "button" }, props ); // Change the context for the click callback to be the main element click = props.click; props.click = function() { click.apply( that.element[ 0 ], arguments ); }; buttonOptions = { icons: props.icons, text: props.showText }; delete props.icons; delete props.showText; $( "<button></button>", props ) .button( buttonOptions ) .appendTo( that.uiButtonSet ); }); this.uiDialog.addClass( "ui-dialog-buttons" ); this.uiDialogButtonPane.appendTo( this.uiDialog ); }, _makeDraggable: function() { var that = this, options = this.options; function filteredUi( ui ) { return { position: ui.position, offset: ui.offset }; } this.uiDialog.draggable({ cancel: ".ui-dialog-content, .ui-dialog-titlebar-close", handle: ".ui-dialog-titlebar", containment: "document", start: function( event, ui ) { $( this ).addClass( "ui-dialog-dragging" ); that._blockFrames(); that._trigger( "dragStart", event, filteredUi( ui ) ); }, drag: function( event, ui ) { that._trigger( "drag", event, filteredUi( ui ) ); }, stop: function( event, ui ) { var left = ui.offset.left - that.document.scrollLeft(), top = ui.offset.top - that.document.scrollTop(); options.position = { my: "left top", at: "left" + (left >= 0 ? "+" : "") + left + " " + "top" + (top >= 0 ? "+" : "") + top, of: that.window }; $( this ).removeClass( "ui-dialog-dragging" ); that._unblockFrames(); that._trigger( "dragStop", event, filteredUi( ui ) ); } }); }, _makeResizable: function() { var that = this, options = this.options, handles = options.resizable, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = this.uiDialog.css("position"), resizeHandles = typeof handles === "string" ? handles : "n,e,s,w,se,sw,ne,nw"; function filteredUi( ui ) { return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; } this.uiDialog.resizable({ cancel: ".ui-dialog-content", containment: "document", alsoResize: this.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: this._minHeight(), handles: resizeHandles, start: function( event, ui ) { $( this ).addClass( "ui-dialog-resizing" ); that._blockFrames(); that._trigger( "resizeStart", event, filteredUi( ui ) ); }, resize: function( event, ui ) { that._trigger( "resize", event, filteredUi( ui ) ); }, stop: function( event, ui ) { var offset = that.uiDialog.offset(), left = offset.left - that.document.scrollLeft(), top = offset.top - that.document.scrollTop(); options.height = that.uiDialog.height(); options.width = that.uiDialog.width(); options.position = { my: "left top", at: "left" + (left >= 0 ? "+" : "") + left + " " + "top" + (top >= 0 ? "+" : "") + top, of: that.window }; $( this ).removeClass( "ui-dialog-resizing" ); that._unblockFrames(); that._trigger( "resizeStop", event, filteredUi( ui ) ); } }) .css( "position", position ); }, _trackFocus: function() { this._on( this.widget(), { "focusin": function( event ) { this._untrackInstance(); this._trackingInstances().unshift( this ); this._focusedElement = $( event.target ); } }); }, _untrackInstance: function() { var instances = this._trackingInstances(), exists = $.inArray( this, instances ); if ( exists !== -1 ) { instances.splice( exists, 1 ); } }, _trackingInstances: function() { var instances = this.document.data( "ui-dialog-instances" ); if ( !instances ) { instances = []; this.document.data( "ui-dialog-instances", instances ); } return instances; }, _minHeight: function() { var options = this.options; return options.height === "auto" ? options.minHeight : Math.min( options.minHeight, options.height ); }, _position: function() { // Need to show the dialog to get the actual offset in the position plugin var isVisible = this.uiDialog.is( ":visible" ); if ( !isVisible ) { this.uiDialog.show(); } this.uiDialog.position( this.options.position ); if ( !isVisible ) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var that = this, resize = false, resizableOptions = {}; $.each( options, function( key, value ) { that._setOption( key, value ); if ( key in that.sizeRelatedOptions ) { resize = true; } if ( key in that.resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); this._position(); } if ( this.uiDialog.is( ":data(ui-resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function( key, value ) { var isDraggable, isResizable, uiDialog = this.uiDialog; if ( key === "dialogClass" ) { uiDialog .removeClass( this.options.dialogClass ) .addClass( value ); } if ( key === "disabled" ) { return; } this._super( key, value ); if ( key === "appendTo" ) { this.uiDialog.appendTo( this._appendTo() ); } if ( key === "buttons" ) { this._createButtons(); } if ( key === "closeText" ) { this.uiDialogTitlebarClose.button({ // Ensure that we always pass a string label: "" + value }); } if ( key === "draggable" ) { isDraggable = uiDialog.is( ":data(ui-draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { this._makeDraggable(); } } if ( key === "position" ) { this._position(); } if ( key === "resizable" ) { // currently resizable, becoming non-resizable isResizable = uiDialog.is( ":data(ui-resizable)" ); if ( isResizable && !value ) { uiDialog.resizable( "destroy" ); } // currently resizable, changing handles if ( isResizable && typeof value === "string" ) { uiDialog.resizable( "option", "handles", value ); } // currently non-resizable, becoming resizable if ( !isResizable && value !== false ) { this._makeResizable(); } } if ( key === "title" ) { this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) ); } }, _size: function() { // If the user has resized the dialog, the .ui-dialog and .ui-dialog-content // divs will both have width and height set, so we need to reset them var nonContentHeight, minContentHeight, maxContentHeight, options = this.options; // Reset content sizing this.element.show().css({ width: "auto", minHeight: 0, maxHeight: "none", height: 0 }); if ( options.minWidth > options.width ) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: "auto", width: options.width }) .outerHeight(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); maxContentHeight = typeof options.maxHeight === "number" ? Math.max( 0, options.maxHeight - nonContentHeight ) : "none"; if ( options.height === "auto" ) { this.element.css({ minHeight: minContentHeight, maxHeight: maxContentHeight, height: "auto" }); } else { this.element.height( Math.max( 0, options.height - nonContentHeight ) ); } if ( this.uiDialog.is( ":data(ui-resizable)" ) ) { this.uiDialog.resizable( "option", "minHeight", this._minHeight() ); } }, _blockFrames: function() { this.iframeBlocks = this.document.find( "iframe" ).map(function() { var iframe = $( this ); return $( "<div>" ) .css({ position: "absolute", width: iframe.outerWidth(), height: iframe.outerHeight() }) .appendTo( iframe.parent() ) .offset( iframe.offset() )[0]; }); }, _unblockFrames: function() { if ( this.iframeBlocks ) { this.iframeBlocks.remove(); delete this.iframeBlocks; } }, _allowInteraction: function( event ) { if ( $( event.target ).closest( ".ui-dialog" ).length ) { return true; } // TODO: Remove hack when datepicker implements // the .ui-front logic (#8989) return !!$( event.target ).closest( ".ui-datepicker" ).length; }, _createOverlay: function() { if ( !this.options.modal ) { return; } // We use a delay in case the overlay is created from an // event that we're going to be cancelling (#2804) var isOpening = true; this._delay(function() { isOpening = false; }); if ( !this.document.data( "ui-dialog-overlays" ) ) { // Prevent use of anchors and inputs // Using _on() for an event handler shared across many instances is // safe because the dialogs stack and must be closed in reverse order this._on( this.document, { focusin: function( event ) { if ( isOpening ) { return; } if ( !this._allowInteraction( event ) ) { event.preventDefault(); this._trackingInstances()[ 0 ]._focusTabbable(); } } }); } this.overlay = $( "<div>" ) .addClass( "ui-widget-overlay ui-front" ) .appendTo( this._appendTo() ); this._on( this.overlay, { mousedown: "_keepFocus" }); this.document.data( "ui-dialog-overlays", (this.document.data( "ui-dialog-overlays" ) || 0) + 1 ); }, _destroyOverlay: function() { if ( !this.options.modal ) { return; } if ( this.overlay ) { var overlays = this.document.data( "ui-dialog-overlays" ) - 1; if ( !overlays ) { this.document .unbind( "focusin" ) .removeData( "ui-dialog-overlays" ); } else { this.document.data( "ui-dialog-overlays", overlays ); } this.overlay.remove(); this.overlay = null; } } }); /*! * jQuery UI Droppable 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/droppable/ */ $.widget( "ui.droppable", { version: "1.11.0", widgetEventPrefix: "drop", options: { accept: "*", activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: "default", tolerance: "intersect", // callbacks activate: null, deactivate: null, drop: null, out: null, over: null }, _create: function() { var proportions, o = this.options, accept = o.accept; this.isover = false; this.isout = true; this.accept = $.isFunction( accept ) ? accept : function( d ) { return d.is( accept ); }; this.proportions = function( /* valueToWrite */ ) { if ( arguments.length ) { // Store the droppable's proportions proportions = arguments[ 0 ]; } else { // Retrieve or derive the droppable's proportions return proportions ? proportions : proportions = { width: this.element[ 0 ].offsetWidth, height: this.element[ 0 ].offsetHeight }; } }; this._addToManager( o.scope ); o.addClasses && this.element.addClass( "ui-droppable" ); }, _addToManager: function( scope ) { // Add the reference and positions to the manager $.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || []; $.ui.ddmanager.droppables[ scope ].push( this ); }, _splice: function( drop ) { var i = 0; for ( ; i < drop.length; i++ ) { if ( drop[ i ] === this ) { drop.splice( i, 1 ); } } }, _destroy: function() { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this.element.removeClass( "ui-droppable ui-droppable-disabled" ); }, _setOption: function( key, value ) { if ( key === "accept" ) { this.accept = $.isFunction( value ) ? value : function( d ) { return d.is( value ); }; } else if ( key === "scope" ) { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this._addToManager( value ); } this._super( key, value ); }, _activate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.addClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "activate", event, this.ui( draggable ) ); } }, _deactivate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "deactivate", event, this.ui( draggable ) ); } }, _over: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.addClass( this.options.hoverClass ); } this._trigger( "over", event, this.ui( draggable ) ); } }, _out: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "out", event, this.ui( draggable ) ); } }, _drop: function( event, custom ) { var draggable = custom || $.ui.ddmanager.current, childrenIntersection = false; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return false; } this.element.find( ":data(ui-droppable)" ).not( ".ui-draggable-dragging" ).each(function() { var inst = $( this ).droppable( "instance" ); if ( inst.options.greedy && !inst.options.disabled && inst.options.scope === draggable.options.scope && inst.accept.call( inst.element[ 0 ], ( draggable.currentItem || draggable.element ) ) && $.ui.intersect( draggable, $.extend( inst, { offset: inst.element.offset() } ), inst.options.tolerance ) ) { childrenIntersection = true; return false; } }); if ( childrenIntersection ) { return false; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "drop", event, this.ui( draggable ) ); return this.element; } return false; }, ui: function( c ) { return { draggable: ( c.currentItem || c.element ), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.ui.intersect = (function() { function isOverAxis( x, reference, size ) { return ( x >= reference ) && ( x < ( reference + size ) ); } return function( draggable, droppable, toleranceMode ) { if ( !droppable.offset ) { return false; } var draggableLeft, draggableTop, x1 = ( draggable.positionAbs || draggable.position.absolute ).left, y1 = ( draggable.positionAbs || draggable.position.absolute ).top, x2 = x1 + draggable.helperProportions.width, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, t = droppable.offset.top, r = l + droppable.proportions().width, b = t + droppable.proportions().height; switch ( toleranceMode ) { case "fit": return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b ); case "intersect": return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half case "pointer": draggableLeft = ( ( draggable.positionAbs || draggable.position.absolute ).left + ( draggable.clickOffset || draggable.offset.click ).left ); draggableTop = ( ( draggable.positionAbs || draggable.position.absolute ).top + ( draggable.clickOffset || draggable.offset.click ).top ); return isOverAxis( draggableTop, t, droppable.proportions().height ) && isOverAxis( draggableLeft, l, droppable.proportions().width ); case "touch": return ( ( y1 >= t && y1 <= b ) || // Top edge touching ( y2 >= t && y2 <= b ) || // Bottom edge touching ( y1 < t && y2 > b ) // Surrounded vertically ) && ( ( x1 >= l && x1 <= r ) || // Left edge touching ( x2 >= l && x2 <= r ) || // Right edge touching ( x1 < l && x2 > r ) // Surrounded horizontally ); default: return false; } }; })(); /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { "default": [] }, prepareOffsets: function( t, event ) { var i, j, m = $.ui.ddmanager.droppables[ t.options.scope ] || [], type = event ? event.type : null, // workaround for #2317 list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack(); droppablesLoop: for ( i = 0; i < m.length; i++ ) { // No disabled and non-accepted if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) { continue; } // Filter out elements in the current dragged item for ( j = 0; j < list.length; j++ ) { if ( list[ j ] === m[ i ].element[ 0 ] ) { m[ i ].proportions().height = 0; continue droppablesLoop; } } m[ i ].visible = m[ i ].element.css( "display" ) !== "none"; if ( !m[ i ].visible ) { continue; } // Activate the droppable if used directly from draggables if ( type === "mousedown" ) { m[ i ]._activate.call( m[ i ], event ); } m[ i ].offset = m[ i ].element.offset(); m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight }); } }, drop: function( draggable, event ) { var dropped = false; // Create a copy of the droppables in case the list changes during the drop (#9116) $.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() { if ( !this.options ) { return; } if ( !this.options.disabled && this.visible && $.ui.intersect( draggable, this, this.options.tolerance ) ) { dropped = this._drop.call( this, event ) || dropped; } if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { this.isout = true; this.isover = false; this._deactivate.call( this, event ); } }); return dropped; }, dragStart: function( draggable, event ) { // Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() { if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } }); }, drag: function( draggable, event ) { // If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if ( draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } // Run through all droppables and check their positions based on specific tolerance options $.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() { if ( this.options.disabled || this.greedyChild || !this.visible ) { return; } var parentInstance, scope, parent, intersects = $.ui.intersect( draggable, this, this.options.tolerance ), c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null ); if ( !c ) { return; } if ( this.options.greedy ) { // find droppable parents with same scope scope = this.options.scope; parent = this.element.parents( ":data(ui-droppable)" ).filter(function() { return $( this ).droppable( "instance" ).options.scope === scope; }); if ( parent.length ) { parentInstance = $( parent[ 0 ] ).droppable( "instance" ); parentInstance.greedyChild = ( c === "isover" ); } } // we just moved into a greedy child if ( parentInstance && c === "isover" ) { parentInstance.isover = false; parentInstance.isout = true; parentInstance._out.call( parentInstance, event ); } this[ c ] = true; this[c === "isout" ? "isover" : "isout"] = false; this[c === "isover" ? "_over" : "_out"].call( this, event ); // we just moved out of a greedy child if ( parentInstance && c === "isout" ) { parentInstance.isout = false; parentInstance.isover = true; parentInstance._over.call( parentInstance, event ); } }); }, dragStop: function( draggable, event ) { draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" ); // Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } } }; var droppable = $.ui.droppable; /*! * jQuery UI Effects 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/effects-core/ */ var dataSpace = "ui-effects-"; $.effects = { effect: {} }; /*! * jQuery Color Animations v2.1.2 * https://github.com/jquery/jquery-color * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * Date: Wed Jan 16 08:47:09 2013 -0600 */ (function( jQuery, undefined ) { var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor", // plusequals test for += 100 -= 100 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, // a set of RE's that can match strings and generate color tuples. stringParsers = [ { re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ], execResult[ 3 ], execResult[ 4 ] ]; } }, { re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ] * 2.55, execResult[ 2 ] * 2.55, execResult[ 3 ] * 2.55, execResult[ 4 ] ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ], 16 ), parseInt( execResult[ 2 ], 16 ), parseInt( execResult[ 3 ], 16 ) ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) ]; } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ] / 100, execResult[ 3 ] / 100, execResult[ 4 ] ]; } } ], // jQuery.Color( ) color = jQuery.Color = function( color, green, blue, alpha ) { return new jQuery.Color.fn.parse( color, green, blue, alpha ); }, spaces = { rgba: { props: { red: { idx: 0, type: "byte" }, green: { idx: 1, type: "byte" }, blue: { idx: 2, type: "byte" } } }, hsla: { props: { hue: { idx: 0, type: "degrees" }, saturation: { idx: 1, type: "percent" }, lightness: { idx: 2, type: "percent" } } } }, propTypes = { "byte": { floor: true, max: 255 }, "percent": { max: 1 }, "degrees": { mod: 360, floor: true } }, support = color.support = {}, // element for support tests supportElem = jQuery( "<p>" )[ 0 ], // colors = jQuery.Color.names colors, // local aliases of functions called often each = jQuery.each; // determine rgba support immediately supportElem.style.cssText = "background-color:rgba(1,1,1,.5)"; support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1; // define cache name and alpha properties // for rgba and hsla spaces each( spaces, function( spaceName, space ) { space.cache = "_" + spaceName; space.props.alpha = { idx: 3, type: "percent", def: 1 }; }); function clamp( value, prop, allowEmpty ) { var type = propTypes[ prop.type ] || {}; if ( value == null ) { return (allowEmpty || !prop.def) ? null : prop.def; } // ~~ is an short way of doing floor for positive numbers value = type.floor ? ~~value : parseFloat( value ); // IE will pass in empty strings as value for alpha, // which will hit this case if ( isNaN( value ) ) { return prop.def; } if ( type.mod ) { // we add mod before modding to make sure that negatives values // get converted properly: -10 -> 350 return (value + type.mod) % type.mod; } // for now all property types without mod have min and max return 0 > value ? 0 : type.max < value ? type.max : value; } function stringParse( string ) { var inst = color(), rgba = inst._rgba = []; string = string.toLowerCase(); each( stringParsers, function( i, parser ) { var parsed, match = parser.re.exec( string ), values = match && parser.parse( match ), spaceName = parser.space || "rgba"; if ( values ) { parsed = inst[ spaceName ]( values ); // if this was an rgba parse the assignment might happen twice // oh well.... inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ]; rgba = inst._rgba = parsed._rgba; // exit each( stringParsers ) here because we matched return false; } }); // Found a stringParser that handled it if ( rgba.length ) { // if this came from a parsed string, force "transparent" when alpha is 0 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) if ( rgba.join() === "0,0,0,0" ) { jQuery.extend( rgba, colors.transparent ); } return inst; } // named colors return colors[ string ]; } color.fn = jQuery.extend( color.prototype, { parse: function( red, green, blue, alpha ) { if ( red === undefined ) { this._rgba = [ null, null, null, null ]; return this; } if ( red.jquery || red.nodeType ) { red = jQuery( red ).css( green ); green = undefined; } var inst = this, type = jQuery.type( red ), rgba = this._rgba = []; // more than 1 argument specified - assume ( red, green, blue, alpha ) if ( green !== undefined ) { red = [ red, green, blue, alpha ]; type = "array"; } if ( type === "string" ) { return this.parse( stringParse( red ) || colors._default ); } if ( type === "array" ) { each( spaces.rgba.props, function( key, prop ) { rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); }); return this; } if ( type === "object" ) { if ( red instanceof color ) { each( spaces, function( spaceName, space ) { if ( red[ space.cache ] ) { inst[ space.cache ] = red[ space.cache ].slice(); } }); } else { each( spaces, function( spaceName, space ) { var cache = space.cache; each( space.props, function( key, prop ) { // if the cache doesn't exist, and we know how to convert if ( !inst[ cache ] && space.to ) { // if the value was null, we don't need to copy it // if the key was alpha, we don't need to copy it either if ( key === "alpha" || red[ key ] == null ) { return; } inst[ cache ] = space.to( inst._rgba ); } // this is the only case where we allow nulls for ALL properties. // call clamp with alwaysAllowEmpty inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); }); // everything defined but alpha? if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) { // use the default of 1 inst[ cache ][ 3 ] = 1; if ( space.from ) { inst._rgba = space.from( inst[ cache ] ); } } }); } return this; } }, is: function( compare ) { var is = color( compare ), same = true, inst = this; each( spaces, function( _, space ) { var localCache, isCache = is[ space.cache ]; if (isCache) { localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || []; each( space.props, function( _, prop ) { if ( isCache[ prop.idx ] != null ) { same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); return same; } }); } return same; }); return same; }, _space: function() { var used = [], inst = this; each( spaces, function( spaceName, space ) { if ( inst[ space.cache ] ) { used.push( spaceName ); } }); return used.pop(); }, transition: function( other, distance ) { var end = color( other ), spaceName = end._space(), space = spaces[ spaceName ], startColor = this.alpha() === 0 ? color( "transparent" ) : this, start = startColor[ space.cache ] || space.to( startColor._rgba ), result = start.slice(); end = end[ space.cache ]; each( space.props, function( key, prop ) { var index = prop.idx, startValue = start[ index ], endValue = end[ index ], type = propTypes[ prop.type ] || {}; // if null, don't override start value if ( endValue === null ) { return; } // if null - use end if ( startValue === null ) { result[ index ] = endValue; } else { if ( type.mod ) { if ( endValue - startValue > type.mod / 2 ) { startValue += type.mod; } else if ( startValue - endValue > type.mod / 2 ) { startValue -= type.mod; } } result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); } }); return this[ spaceName ]( result ); }, blend: function( opaque ) { // if we are already opaque - return ourself if ( this._rgba[ 3 ] === 1 ) { return this; } var rgb = this._rgba.slice(), a = rgb.pop(), blend = color( opaque )._rgba; return color( jQuery.map( rgb, function( v, i ) { return ( 1 - a ) * blend[ i ] + a * v; })); }, toRgbaString: function() { var prefix = "rgba(", rgba = jQuery.map( this._rgba, function( v, i ) { return v == null ? ( i > 2 ? 1 : 0 ) : v; }); if ( rgba[ 3 ] === 1 ) { rgba.pop(); prefix = "rgb("; } return prefix + rgba.join() + ")"; }, toHslaString: function() { var prefix = "hsla(", hsla = jQuery.map( this.hsla(), function( v, i ) { if ( v == null ) { v = i > 2 ? 1 : 0; } // catch 1 and 2 if ( i && i < 3 ) { v = Math.round( v * 100 ) + "%"; } return v; }); if ( hsla[ 3 ] === 1 ) { hsla.pop(); prefix = "hsl("; } return prefix + hsla.join() + ")"; }, toHexString: function( includeAlpha ) { var rgba = this._rgba.slice(), alpha = rgba.pop(); if ( includeAlpha ) { rgba.push( ~~( alpha * 255 ) ); } return "#" + jQuery.map( rgba, function( v ) { // default to 0 when nulls exist v = ( v || 0 ).toString( 16 ); return v.length === 1 ? "0" + v : v; }).join(""); }, toString: function() { return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); } }); color.fn.parse.prototype = color.fn; // hsla conversions adapted from: // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021 function hue2rgb( p, q, h ) { h = ( h + 1 ) % 1; if ( h * 6 < 1 ) { return p + ( q - p ) * h * 6; } if ( h * 2 < 1) { return q; } if ( h * 3 < 2 ) { return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6; } return p; } spaces.hsla.to = function( rgba ) { if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { return [ null, null, null, rgba[ 3 ] ]; } var r = rgba[ 0 ] / 255, g = rgba[ 1 ] / 255, b = rgba[ 2 ] / 255, a = rgba[ 3 ], max = Math.max( r, g, b ), min = Math.min( r, g, b ), diff = max - min, add = max + min, l = add * 0.5, h, s; if ( min === max ) { h = 0; } else if ( r === max ) { h = ( 60 * ( g - b ) / diff ) + 360; } else if ( g === max ) { h = ( 60 * ( b - r ) / diff ) + 120; } else { h = ( 60 * ( r - g ) / diff ) + 240; } // chroma (diff) == 0 means greyscale which, by definition, saturation = 0% // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add) if ( diff === 0 ) { s = 0; } else if ( l <= 0.5 ) { s = diff / add; } else { s = diff / ( 2 - add ); } return [ Math.round(h) % 360, s, l, a == null ? 1 : a ]; }; spaces.hsla.from = function( hsla ) { if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { return [ null, null, null, hsla[ 3 ] ]; } var h = hsla[ 0 ] / 360, s = hsla[ 1 ], l = hsla[ 2 ], a = hsla[ 3 ], q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, p = 2 * l - q; return [ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), Math.round( hue2rgb( p, q, h ) * 255 ), Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), a ]; }; each( spaces, function( spaceName, space ) { var props = space.props, cache = space.cache, to = space.to, from = space.from; // makes rgba() and hsla() color.fn[ spaceName ] = function( value ) { // generate a cache for this space if it doesn't exist if ( to && !this[ cache ] ) { this[ cache ] = to( this._rgba ); } if ( value === undefined ) { return this[ cache ].slice(); } var ret, type = jQuery.type( value ), arr = ( type === "array" || type === "object" ) ? value : arguments, local = this[ cache ].slice(); each( props, function( key, prop ) { var val = arr[ type === "object" ? key : prop.idx ]; if ( val == null ) { val = local[ prop.idx ]; } local[ prop.idx ] = clamp( val, prop ); }); if ( from ) { ret = color( from( local ) ); ret[ cache ] = local; return ret; } else { return color( local ); } }; // makes red() green() blue() alpha() hue() saturation() lightness() each( props, function( key, prop ) { // alpha is included in more than one space if ( color.fn[ key ] ) { return; } color.fn[ key ] = function( value ) { var vtype = jQuery.type( value ), fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ), local = this[ fn ](), cur = local[ prop.idx ], match; if ( vtype === "undefined" ) { return cur; } if ( vtype === "function" ) { value = value.call( this, cur ); vtype = jQuery.type( value ); } if ( value == null && prop.empty ) { return this; } if ( vtype === "string" ) { match = rplusequals.exec( value ); if ( match ) { value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); } } local[ prop.idx ] = value; return this[ fn ]( local ); }; }); }); // add cssHook and .fx.step function for each named hook. // accept a space separated string of properties color.hook = function( hook ) { var hooks = hook.split( " " ); each( hooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, curElem, backgroundColor = ""; if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) { value = color( parsed || value ); if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { curElem = hook === "backgroundColor" ? elem.parentNode : elem; while ( (backgroundColor === "" || backgroundColor === "transparent") && curElem && curElem.style ) { try { backgroundColor = jQuery.css( curElem, "backgroundColor" ); curElem = curElem.parentNode; } catch ( e ) { } } value = value.blend( backgroundColor && backgroundColor !== "transparent" ? backgroundColor : "_default" ); } value = value.toRgbaString(); } try { elem.style[ hook ] = value; } catch( e ) { // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit' } } }; jQuery.fx.step[ hook ] = function( fx ) { if ( !fx.colorInit ) { fx.start = color( fx.elem, hook ); fx.end = color( fx.end ); fx.colorInit = true; } jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); }; }); }; color.hook( stepHooks ); jQuery.cssHooks.borderColor = { expand: function( value ) { var expanded = {}; each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) { expanded[ "border" + part + "Color" ] = value; }); return expanded; } }; // Basic color names only. // Usage of any of the other color names requires adding yourself or including // jquery.color.svg-names.js. colors = jQuery.Color.names = { // 4.1. Basic color keywords aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", // 4.2.3. "transparent" color keyword transparent: [ null, null, null, 0 ], _default: "#ffffff" }; })( jQuery ); /******************************************************************************/ /****************************** CLASS ANIMATIONS ******************************/ /******************************************************************************/ (function() { var classAnimationActions = [ "add", "remove", "toggle" ], shorthandStyles = { border: 1, borderBottom: 1, borderColor: 1, borderLeft: 1, borderRight: 1, borderTop: 1, borderWidth: 1, margin: 1, padding: 1 }; $.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) { $.fx.step[ prop ] = function( fx ) { if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) { jQuery.style( fx.elem, prop, fx.end ); fx.setAttr = true; } }; }); function getElementStyles( elem ) { var key, len, style = elem.ownerDocument.defaultView ? elem.ownerDocument.defaultView.getComputedStyle( elem, null ) : elem.currentStyle, styles = {}; if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) { len = style.length; while ( len-- ) { key = style[ len ]; if ( typeof style[ key ] === "string" ) { styles[ $.camelCase( key ) ] = style[ key ]; } } // support: Opera, IE <9 } else { for ( key in style ) { if ( typeof style[ key ] === "string" ) { styles[ key ] = style[ key ]; } } } return styles; } function styleDifference( oldStyle, newStyle ) { var diff = {}, name, value; for ( name in newStyle ) { value = newStyle[ name ]; if ( oldStyle[ name ] !== value ) { if ( !shorthandStyles[ name ] ) { if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) { diff[ name ] = value; } } } } return diff; } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } $.effects.animateClass = function( value, duration, easing, callback ) { var o = $.speed( duration, easing, callback ); return this.queue( function() { var animated = $( this ), baseClass = animated.attr( "class" ) || "", applyClassChange, allAnimations = o.children ? animated.find( "*" ).addBack() : animated; // map the animated objects to store the original styles. allAnimations = allAnimations.map(function() { var el = $( this ); return { el: el, start: getElementStyles( this ) }; }); // apply class change applyClassChange = function() { $.each( classAnimationActions, function(i, action) { if ( value[ action ] ) { animated[ action + "Class" ]( value[ action ] ); } }); }; applyClassChange(); // map all animated objects again - calculate new styles and diff allAnimations = allAnimations.map(function() { this.end = getElementStyles( this.el[ 0 ] ); this.diff = styleDifference( this.start, this.end ); return this; }); // apply original class animated.attr( "class", baseClass ); // map all animated objects again - this time collecting a promise allAnimations = allAnimations.map(function() { var styleInfo = this, dfd = $.Deferred(), opts = $.extend({}, o, { queue: false, complete: function() { dfd.resolve( styleInfo ); } }); this.el.animate( this.diff, opts ); return dfd.promise(); }); // once all animations have completed: $.when.apply( $, allAnimations.get() ).done(function() { // set the final class applyClassChange(); // for each animated element, // clear all css properties that were animated $.each( arguments, function() { var el = this.el; $.each( this.diff, function(key) { el.css( key, "" ); }); }); // this is guarnteed to be there if you use jQuery.speed() // it also handles dequeuing the next anim... o.complete.call( animated[ 0 ] ); }); }); }; $.fn.extend({ addClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { add: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.addClass ), removeClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return arguments.length > 1 ? $.effects.animateClass.call( this, { remove: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.removeClass ), toggleClass: (function( orig ) { return function( classNames, force, speed, easing, callback ) { if ( typeof force === "boolean" || force === undefined ) { if ( !speed ) { // without speed parameter return orig.apply( this, arguments ); } else { return $.effects.animateClass.call( this, (force ? { add: classNames } : { remove: classNames }), speed, easing, callback ); } } else { // without force parameter return $.effects.animateClass.call( this, { toggle: classNames }, force, speed, easing ); } }; })( $.fn.toggleClass ), switchClass: function( remove, add, speed, easing, callback) { return $.effects.animateClass.call( this, { add: add, remove: remove }, speed, easing, callback ); } }); })(); /******************************************************************************/ /*********************************** EFFECTS **********************************/ /******************************************************************************/ (function() { $.extend( $.effects, { version: "1.11.0", // Saves a set of properties in a data storage save: function( element, set ) { for ( var i = 0; i < set.length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }, // Restores a set of previously saved properties from a data storage restore: function( element, set ) { var val, i; for ( i = 0; i < set.length; i++ ) { if ( set[ i ] !== null ) { val = element.data( dataSpace + set[ i ] ); // support: jQuery 1.6.2 // http://bugs.jquery.com/ticket/9917 // jQuery 1.6.2 incorrectly returns undefined for any falsy value. // We can't differentiate between "" and 0 here, so we just assume // empty string since it's likely to be a more common value... if ( val === undefined ) { val = ""; } element.css( set[ i ], val ); } } }, setMode: function( el, mode ) { if (mode === "toggle") { mode = el.is( ":hidden" ) ? "show" : "hide"; } return mode; }, // Translates a [top,left] array into a baseline value // this should be a little more flexible in the future to handle a string & hash getBaseline: function( origin, original ) { var y, x; switch ( origin[ 0 ] ) { case "top": y = 0; break; case "middle": y = 0.5; break; case "bottom": y = 1; break; default: y = origin[ 0 ] / original.height; } switch ( origin[ 1 ] ) { case "left": x = 0; break; case "center": x = 0.5; break; case "right": x = 1; break; default: x = origin[ 1 ] / original.width; } return { x: x, y: y }; }, // Wraps the element around a wrapper that copies position properties createWrapper: function( element ) { // if the element is already wrapped, return it if ( element.parent().is( ".ui-effects-wrapper" )) { return element.parent(); } // wrap the element var props = { width: element.outerWidth(true), height: element.outerHeight(true), "float": element.css( "float" ) }, wrapper = $( "<div></div>" ) .addClass( "ui-effects-wrapper" ) .css({ fontSize: "100%", background: "transparent", border: "none", margin: 0, padding: 0 }), // Store the size in case width/height are defined in % - Fixes #5245 size = { width: element.width(), height: element.height() }, active = document.activeElement; // support: Firefox // Firefox incorrectly exposes anonymous content // https://bugzilla.mozilla.org/show_bug.cgi?id=561664 try { active.id; } catch( e ) { active = document.body; } element.wrap( wrapper ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element // transfer positioning properties to the wrapper if ( element.css( "position" ) === "static" ) { wrapper.css({ position: "relative" }); element.css({ position: "relative" }); } else { $.extend( props, { position: element.css( "position" ), zIndex: element.css( "z-index" ) }); $.each([ "top", "left", "bottom", "right" ], function(i, pos) { props[ pos ] = element.css( pos ); if ( isNaN( parseInt( props[ pos ], 10 ) ) ) { props[ pos ] = "auto"; } }); element.css({ position: "relative", top: 0, left: 0, right: "auto", bottom: "auto" }); } element.css(size); return wrapper.css( props ).show(); }, removeWrapper: function( element ) { var active = document.activeElement; if ( element.parent().is( ".ui-effects-wrapper" ) ) { element.parent().replaceWith( element ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } } return element; }, setTransition: function( element, list, factor, value ) { value = value || {}; $.each( list, function( i, x ) { var unit = element.cssUnit( x ); if ( unit[ 0 ] > 0 ) { value[ x ] = unit[ 0 ] * factor + unit[ 1 ]; } }); return value; } }); // return an effect options object for the given parameters: function _normalizeArguments( effect, options, speed, callback ) { // allow passing all options as the first parameter if ( $.isPlainObject( effect ) ) { options = effect; effect = effect.effect; } // convert to an object effect = { effect: effect }; // catch (effect, null, ...) if ( options == null ) { options = {}; } // catch (effect, callback) if ( $.isFunction( options ) ) { callback = options; speed = null; options = {}; } // catch (effect, speed, ?) if ( typeof options === "number" || $.fx.speeds[ options ] ) { callback = speed; speed = options; options = {}; } // catch (effect, options, callback) if ( $.isFunction( speed ) ) { callback = speed; speed = null; } // add options to effect if ( options ) { $.extend( effect, options ); } speed = speed || options.duration; effect.duration = $.fx.off ? 0 : typeof speed === "number" ? speed : speed in $.fx.speeds ? $.fx.speeds[ speed ] : $.fx.speeds._default; effect.complete = callback || options.complete; return effect; } function standardAnimationOption( option ) { // Valid standard speeds (nothing, number, named speed) if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) { return true; } // Invalid strings - treat as "normal" speed if ( typeof option === "string" && !$.effects.effect[ option ] ) { return true; } // Complete callback if ( $.isFunction( option ) ) { return true; } // Options hash (but not naming an effect) if ( typeof option === "object" && !option.effect ) { return true; } // Didn't match any standard API return false; } $.fn.extend({ effect: function( /* effect, options, speed, callback */ ) { var args = _normalizeArguments.apply( this, arguments ), mode = args.mode, queue = args.queue, effectMethod = $.effects.effect[ args.effect ]; if ( $.fx.off || !effectMethod ) { // delegate to the original method (e.g., .show()) if possible if ( mode ) { return this[ mode ]( args.duration, args.complete ); } else { return this.each( function() { if ( args.complete ) { args.complete.call( this ); } }); } } function run( next ) { var elem = $( this ), complete = args.complete, mode = args.mode; function done() { if ( $.isFunction( complete ) ) { complete.call( elem[0] ); } if ( $.isFunction( next ) ) { next(); } } // If the element already has the correct final state, delegate to // the core methods so the internal tracking of "olddisplay" works. if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) { elem[ mode ](); done(); } else { effectMethod.call( elem[0], args, done ); } } return queue === false ? this.each( run ) : this.queue( queue || "fx", run ); }, show: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "show"; return this.effect.call( this, args ); } }; })( $.fn.show ), hide: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "hide"; return this.effect.call( this, args ); } }; })( $.fn.hide ), toggle: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) || typeof option === "boolean" ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "toggle"; return this.effect.call( this, args ); } }; })( $.fn.toggle ), // helper functions cssUnit: function(key) { var style = this.css( key ), val = []; $.each( [ "em", "px", "%", "pt" ], function( i, unit ) { if ( style.indexOf( unit ) > 0 ) { val = [ parseFloat( style ), unit ]; } }); return val; } }); })(); /******************************************************************************/ /*********************************** EASING ***********************************/ /******************************************************************************/ (function() { // based on easing equations from Robert Penner (http://www.robertpenner.com/easing) var baseEasings = {}; $.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) { baseEasings[ name ] = function( p ) { return Math.pow( p, i + 2 ); }; }); $.extend( baseEasings, { Sine: function( p ) { return 1 - Math.cos( p * Math.PI / 2 ); }, Circ: function( p ) { return 1 - Math.sqrt( 1 - p * p ); }, Elastic: function( p ) { return p === 0 || p === 1 ? p : -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 ); }, Back: function( p ) { return p * p * ( 3 * p - 2 ); }, Bounce: function( p ) { var pow2, bounce = 4; while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {} return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 ); } }); $.each( baseEasings, function( name, easeIn ) { $.easing[ "easeIn" + name ] = easeIn; $.easing[ "easeOut" + name ] = function( p ) { return 1 - easeIn( 1 - p ); }; $.easing[ "easeInOut" + name ] = function( p ) { return p < 0.5 ? easeIn( p * 2 ) / 2 : 1 - easeIn( p * -2 + 2 ) / 2; }; }); })(); var effect = $.effects; /*! * jQuery UI Effects Blind 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/blind-effect/ */ var effectBlind = $.effects.effect.blind = function( o, done ) { // Create element var el = $( this ), rvertical = /up|down|vertical/, rpositivemotion = /up|left|vertical|horizontal/, props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), direction = o.direction || "up", vertical = rvertical.test( direction ), ref = vertical ? "height" : "width", ref2 = vertical ? "top" : "left", motion = rpositivemotion.test( direction ), animation = {}, show = mode === "show", wrapper, distance, margin; // if already wrapped, the wrapper's properties are my property. #6245 if ( el.parent().is( ".ui-effects-wrapper" ) ) { $.effects.save( el.parent(), props ); } else { $.effects.save( el, props ); } el.show(); wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = wrapper[ ref ](); margin = parseFloat( wrapper.css( ref2 ) ) || 0; animation[ ref ] = show ? distance : 0; if ( !motion ) { el .css( vertical ? "bottom" : "right", 0 ) .css( vertical ? "top" : "left", "auto" ) .css({ position: "absolute" }); animation[ ref2 ] = show ? margin : distance + margin; } // start at 0 if we are showing if ( show ) { wrapper.css( ref, 0 ); if ( !motion ) { wrapper.css( ref2, margin + distance ); } } // Animate wrapper.animate( animation, { duration: o.duration, easing: o.easing, queue: false, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Bounce 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/bounce-effect/ */ var effectBounce = $.effects.effect.bounce = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], // defaults: mode = $.effects.setMode( el, o.mode || "effect" ), hide = mode === "hide", show = mode === "show", direction = o.direction || "up", distance = o.distance, times = o.times || 5, // number of internal animations anims = times * 2 + ( show || hide ? 1 : 0 ), speed = o.duration / anims, easing = o.easing, // utility: ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ), i, upAnim, downAnim, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; // Avoid touching opacity to prevent clearType and PNG issues in IE if ( show || hide ) { props.push( "opacity" ); } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Create Wrapper // default distance for the BIGGEST bounce is the outer Distance / 3 if ( !distance ) { distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3; } if ( show ) { downAnim = { opacity: 1 }; downAnim[ ref ] = 0; // if we are showing, force opacity 0 and set the initial position // then do the "first" animation el.css( "opacity", 0 ) .css( ref, motion ? -distance * 2 : distance * 2 ) .animate( downAnim, speed, easing ); } // start at the smallest distance if we are hiding if ( hide ) { distance = distance / Math.pow( 2, times - 1 ); } downAnim = {}; downAnim[ ref ] = 0; // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here for ( i = 0; i < times; i++ ) { upAnim = {}; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ) .animate( downAnim, speed, easing ); distance = hide ? distance * 2 : distance / 2; } // Last Bounce when Hiding if ( hide ) { upAnim = { opacity: 0 }; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ); } el.queue(function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; /*! * jQuery UI Effects Clip 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/clip-effect/ */ var effectClip = $.effects.effect.clip = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "vertical", vert = direction === "vertical", size = vert ? "height" : "width", position = vert ? "top" : "left", animation = {}, wrapper, animate, distance; // Save & Show $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); animate = ( el[0].tagName === "IMG" ) ? wrapper : el; distance = animate[ size ](); // Shift if ( show ) { animate.css( size, 0 ); animate.css( position, distance / 2 ); } // Create Animation Object: animation[ size ] = show ? distance : 0; animation[ position ] = show ? 0 : distance / 2; // Animate animate.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( !show ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Drop 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/drop-effect/ */ var effectDrop = $.effects.effect.drop = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "left", ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg", animation = { opacity: show ? 1 : 0 }, distance; // Adjust $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2; if ( show ) { el .css( "opacity", 0 ) .css( ref, motion === "pos" ? -distance : distance ); } // Animation animation[ ref ] = ( show ? ( motion === "pos" ? "+=" : "-=" ) : ( motion === "pos" ? "-=" : "+=" ) ) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Explode 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/explode-effect/ */ var effectExplode = $.effects.effect.explode = function( o, done ) { var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3, cells = rows, el = $( this ), mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", // show and then visibility:hidden the element before calculating offset offset = el.show().css( "visibility", "hidden" ).offset(), // width and height of a piece width = Math.ceil( el.outerWidth() / cells ), height = Math.ceil( el.outerHeight() / rows ), pieces = [], // loop i, j, left, top, mx, my; // children animate complete: function childComplete() { pieces.push( this ); if ( pieces.length === rows * cells ) { animComplete(); } } // clone the element for each row and cell. for ( i = 0; i < rows ; i++ ) { // ===> top = offset.top + i * height; my = i - ( rows - 1 ) / 2 ; for ( j = 0; j < cells ; j++ ) { // ||| left = offset.left + j * width; mx = j - ( cells - 1 ) / 2 ; // Create a clone of the now hidden main element that will be absolute positioned // within a wrapper div off the -left and -top equal to size of our pieces el .clone() .appendTo( "body" ) .wrap( "<div></div>" ) .css({ position: "absolute", visibility: "visible", left: -j * width, top: -i * height }) // select the wrapper - make it overflow: hidden and absolute positioned based on // where the original was located +left and +top equal to the size of pieces .parent() .addClass( "ui-effects-explode" ) .css({ position: "absolute", overflow: "hidden", width: width, height: height, left: left + ( show ? mx * width : 0 ), top: top + ( show ? my * height : 0 ), opacity: show ? 0 : 1 }).animate({ left: left + ( show ? 0 : mx * width ), top: top + ( show ? 0 : my * height ), opacity: show ? 1 : 0 }, o.duration || 500, o.easing, childComplete ); } } function animComplete() { el.css({ visibility: "visible" }); $( pieces ).remove(); if ( !show ) { el.hide(); } done(); } }; /*! * jQuery UI Effects Fade 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/fade-effect/ */ var effectFade = $.effects.effect.fade = function( o, done ) { var el = $( this ), mode = $.effects.setMode( el, o.mode || "toggle" ); el.animate({ opacity: mode }, { queue: false, duration: o.duration, easing: o.easing, complete: done }); }; /*! * jQuery UI Effects Fold 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/fold-effect/ */ var effectFold = $.effects.effect.fold = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", hide = mode === "hide", size = o.size || 15, percent = /([0-9]+)%/.exec( size ), horizFirst = !!o.horizFirst, widthFirst = show !== horizFirst, ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ], duration = o.duration / 2, wrapper, distance, animation1 = {}, animation2 = {}; $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = widthFirst ? [ wrapper.width(), wrapper.height() ] : [ wrapper.height(), wrapper.width() ]; if ( percent ) { size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ]; } if ( show ) { wrapper.css( horizFirst ? { height: 0, width: size } : { height: size, width: 0 }); } // Animation animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size; animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0; // Animate wrapper .animate( animation1, duration, o.easing ) .animate( animation2, duration, o.easing, function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); }; /*! * jQuery UI Effects Highlight 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/highlight-effect/ */ var effectHighlight = $.effects.effect.highlight = function( o, done ) { var elem = $( this ), props = [ "backgroundImage", "backgroundColor", "opacity" ], mode = $.effects.setMode( elem, o.mode || "show" ), animation = { backgroundColor: elem.css( "backgroundColor" ) }; if (mode === "hide") { animation.opacity = 0; } $.effects.save( elem, props ); elem .show() .css({ backgroundImage: "none", backgroundColor: o.color || "#ffff99" }) .animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { elem.hide(); } $.effects.restore( elem, props ); done(); } }); }; /*! * jQuery UI Effects Size 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/size-effect/ */ var effectSize = $.effects.effect.size = function( o, done ) { // Create element var original, baseline, factor, el = $( this ), props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ], // Always restore props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ], // Copy for children props2 = [ "width", "height", "overflow" ], cProps = [ "fontSize" ], vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ], hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ], // Set options mode = $.effects.setMode( el, o.mode || "effect" ), restore = o.restore || mode !== "effect", scale = o.scale || "both", origin = o.origin || [ "middle", "center" ], position = el.css( "position" ), props = restore ? props0 : props1, zero = { height: 0, width: 0, outerHeight: 0, outerWidth: 0 }; if ( mode === "show" ) { el.show(); } original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }; if ( o.mode === "toggle" && mode === "show" ) { el.from = o.to || zero; el.to = o.from || original; } else { el.from = o.from || ( mode === "show" ? zero : original ); el.to = o.to || ( mode === "hide" ? zero : original ); } // Set scaling factor factor = { from: { y: el.from.height / original.height, x: el.from.width / original.width }, to: { y: el.to.height / original.height, x: el.to.width / original.width } }; // Scale the css box if ( scale === "box" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( vProps ); el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { props = props.concat( hProps ); el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from ); el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to ); } } // Scale the content if ( scale === "content" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( cProps ).concat( props2 ); el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to ); } } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); el.css( "overflow", "hidden" ).css( el.from ); // Adjust if (origin) { // Calculate baseline shifts baseline = $.effects.getBaseline( origin, original ); el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y; el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x; el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y; el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x; } el.css( el.from ); // set top & left // Animate if ( scale === "content" || scale === "both" ) { // Scale the children // Add margins/font-size vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps); hProps = hProps.concat([ "marginLeft", "marginRight" ]); props2 = props0.concat(vProps).concat(hProps); el.find( "*[width]" ).each( function() { var child = $( this ), c_original = { height: child.height(), width: child.width(), outerHeight: child.outerHeight(), outerWidth: child.outerWidth() }; if (restore) { $.effects.save(child, props2); } child.from = { height: c_original.height * factor.from.y, width: c_original.width * factor.from.x, outerHeight: c_original.outerHeight * factor.from.y, outerWidth: c_original.outerWidth * factor.from.x }; child.to = { height: c_original.height * factor.to.y, width: c_original.width * factor.to.x, outerHeight: c_original.height * factor.to.y, outerWidth: c_original.width * factor.to.x }; // Vertical props scaling if ( factor.from.y !== factor.to.y ) { child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from ); child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from ); child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to ); } // Animate children child.css( child.from ); child.animate( child.to, o.duration, o.easing, function() { // Restore children if ( restore ) { $.effects.restore( child, props2 ); } }); }); } // Animate el.animate( el.to, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( el.to.opacity === 0 ) { el.css( "opacity", el.from.opacity ); } if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); if ( !restore ) { // we need to calculate our new positioning based on the scaling if ( position === "static" ) { el.css({ position: "relative", top: el.to.top, left: el.to.left }); } else { $.each([ "top", "left" ], function( idx, pos ) { el.css( pos, function( _, str ) { var val = parseInt( str, 10 ), toRef = idx ? el.to.left : el.to.top; // if original was "auto", recalculate the new value from wrapper if ( str === "auto" ) { return toRef + "px"; } return val + toRef + "px"; }); }); } } $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Scale 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/scale-effect/ */ var effectScale = $.effects.effect.scale = function( o, done ) { // Create element var el = $( this ), options = $.extend( true, {}, o ), mode = $.effects.setMode( el, o.mode || "effect" ), percent = parseInt( o.percent, 10 ) || ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ), direction = o.direction || "both", origin = o.origin, original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }, factor = { y: direction !== "horizontal" ? (percent / 100) : 1, x: direction !== "vertical" ? (percent / 100) : 1 }; // We are going to pass this effect to the size effect: options.effect = "size"; options.queue = false; options.complete = done; // Set default origin and restore for show/hide if ( mode !== "effect" ) { options.origin = origin || [ "middle", "center" ]; options.restore = true; } options.from = o.from || ( mode === "show" ? { height: 0, width: 0, outerHeight: 0, outerWidth: 0 } : original ); options.to = { height: original.height * factor.y, width: original.width * factor.x, outerHeight: original.outerHeight * factor.y, outerWidth: original.outerWidth * factor.x }; // Fade option to support puff if ( options.fade ) { if ( mode === "show" ) { options.from.opacity = 0; options.to.opacity = 1; } if ( mode === "hide" ) { options.from.opacity = 1; options.to.opacity = 0; } } // Animate el.effect( options ); }; /*! * jQuery UI Effects Puff 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/puff-effect/ */ var effectPuff = $.effects.effect.puff = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "hide" ), hide = mode === "hide", percent = parseInt( o.percent, 10 ) || 150, factor = percent / 100, original = { height: elem.height(), width: elem.width(), outerHeight: elem.outerHeight(), outerWidth: elem.outerWidth() }; $.extend( o, { effect: "scale", queue: false, fade: true, mode: mode, complete: done, percent: hide ? percent : 100, from: hide ? original : { height: original.height * factor, width: original.width * factor, outerHeight: original.outerHeight * factor, outerWidth: original.outerWidth * factor } }); elem.effect( o ); }; /*! * jQuery UI Effects Pulsate 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/pulsate-effect/ */ var effectPulsate = $.effects.effect.pulsate = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "show" ), show = mode === "show", hide = mode === "hide", showhide = ( show || mode === "hide" ), // showing or hiding leaves of the "last" animation anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ), duration = o.duration / anims, animateTo = 0, queue = elem.queue(), queuelen = queue.length, i; if ( show || !elem.is(":visible")) { elem.css( "opacity", 0 ).show(); animateTo = 1; } // anims - 1 opacity "toggles" for ( i = 1; i < anims; i++ ) { elem.animate({ opacity: animateTo }, duration, o.easing ); animateTo = 1 - animateTo; } elem.animate({ opacity: animateTo }, duration, o.easing); elem.queue(function() { if ( hide ) { elem.hide(); } done(); }); // We just queued up "anims" animations, we need to put them next in the queue if ( queuelen > 1 ) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } elem.dequeue(); }; /*! * jQuery UI Effects Shake 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/shake-effect/ */ var effectShake = $.effects.effect.shake = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "effect" ), direction = o.direction || "left", distance = o.distance || 20, times = o.times || 3, anims = times * 2 + 1, speed = Math.round( o.duration / anims ), ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), animation = {}, animation1 = {}, animation2 = {}, i, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Animation animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance; animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2; animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2; // Animate el.animate( animation, speed, o.easing ); // Shakes for ( i = 1; i < times; i++ ) { el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing ); } el .animate( animation1, speed, o.easing ) .animate( animation, speed / 2, o.easing ) .queue(function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; /*! * jQuery UI Effects Slide 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/slide-effect/ */ var effectSlide = $.effects.effect.slide = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "width", "height" ], mode = $.effects.setMode( el, o.mode || "show" ), show = mode === "show", direction = o.direction || "left", ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), distance, animation = {}; // Adjust $.effects.save( el, props ); el.show(); distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ); $.effects.createWrapper( el ).css({ overflow: "hidden" }); if ( show ) { el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance ); } // Animation animation[ ref ] = ( show ? ( positiveMotion ? "+=" : "-=") : ( positiveMotion ? "-=" : "+=")) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Transfer 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/transfer-effect/ */ var effectTransfer = $.effects.effect.transfer = function( o, done ) { var elem = $( this ), target = $( o.to ), targetFixed = target.css( "position" ) === "fixed", body = $("body"), fixTop = targetFixed ? body.scrollTop() : 0, fixLeft = targetFixed ? body.scrollLeft() : 0, endPosition = target.offset(), animation = { top: endPosition.top - fixTop, left: endPosition.left - fixLeft, height: target.innerHeight(), width: target.innerWidth() }, startPosition = elem.offset(), transfer = $( "<div class='ui-effects-transfer'></div>" ) .appendTo( document.body ) .addClass( o.className ) .css({ top: startPosition.top - fixTop, left: startPosition.left - fixLeft, height: elem.innerHeight(), width: elem.innerWidth(), position: targetFixed ? "fixed" : "absolute" }) .animate( animation, o.duration, o.easing, function() { transfer.remove(); done(); }); }; /*! * jQuery UI Progressbar 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/progressbar/ */ var progressbar = $.widget( "ui.progressbar", { version: "1.11.0", options: { max: 100, value: 0, change: null, complete: null }, min: 0, _create: function() { // Constrain initial value this.oldValue = this.options.value = this._constrainedValue(); this.element .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .attr({ // Only set static values, aria-valuenow and aria-valuemax are // set inside _refreshValue() role: "progressbar", "aria-valuemin": this.min }); this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) .appendTo( this.element ); this._refreshValue(); }, _destroy: function() { this.element .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.valueDiv.remove(); }, value: function( newValue ) { if ( newValue === undefined ) { return this.options.value; } this.options.value = this._constrainedValue( newValue ); this._refreshValue(); }, _constrainedValue: function( newValue ) { if ( newValue === undefined ) { newValue = this.options.value; } this.indeterminate = newValue === false; // sanitize value if ( typeof newValue !== "number" ) { newValue = 0; } return this.indeterminate ? false : Math.min( this.options.max, Math.max( this.min, newValue ) ); }, _setOptions: function( options ) { // Ensure "value" option is set after other values (like max) var value = options.value; delete options.value; this._super( options ); this.options.value = this._constrainedValue( value ); this._refreshValue(); }, _setOption: function( key, value ) { if ( key === "max" ) { // Don't allow a max less than min value = Math.max( this.min, value ); } if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); } this._super( key, value ); }, _percentage: function() { return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min ); }, _refreshValue: function() { var value = this.options.value, percentage = this._percentage(); this.valueDiv .toggle( this.indeterminate || value > this.min ) .toggleClass( "ui-corner-right", value === this.options.max ) .width( percentage.toFixed(0) + "%" ); this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate ); if ( this.indeterminate ) { this.element.removeAttr( "aria-valuenow" ); if ( !this.overlayDiv ) { this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv ); } } else { this.element.attr({ "aria-valuemax": this.options.max, "aria-valuenow": value }); if ( this.overlayDiv ) { this.overlayDiv.remove(); this.overlayDiv = null; } } if ( this.oldValue !== value ) { this.oldValue = value; this._trigger( "change" ); } if ( value === this.options.max ) { this._trigger( "complete" ); } } }); /*! * jQuery UI Selectable 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/selectable/ */ var selectable = $.widget("ui.selectable", $.ui.mouse, { version: "1.11.0", options: { appendTo: "body", autoRefresh: true, distance: 0, filter: "*", tolerance: "touch", // callbacks selected: null, selecting: null, start: null, stop: null, unselected: null, unselecting: null }, _create: function() { var selectees, that = this; this.element.addClass("ui-selectable"); this.dragged = false; // cache selectee children based on filter this.refresh = function() { selectees = $(that.options.filter, that.element[0]); selectees.addClass("ui-selectee"); selectees.each(function() { var $this = $(this), pos = $this.offset(); $.data(this, "selectable-item", { element: this, $element: $this, left: pos.left, top: pos.top, right: pos.left + $this.outerWidth(), bottom: pos.top + $this.outerHeight(), startselected: false, selected: $this.hasClass("ui-selected"), selecting: $this.hasClass("ui-selecting"), unselecting: $this.hasClass("ui-unselecting") }); }); }; this.refresh(); this.selectees = selectees.addClass("ui-selectee"); this._mouseInit(); this.helper = $("<div class='ui-selectable-helper'></div>"); }, _destroy: function() { this.selectees .removeClass("ui-selectee") .removeData("selectable-item"); this.element .removeClass("ui-selectable ui-selectable-disabled"); this._mouseDestroy(); }, _mouseStart: function(event) { var that = this, options = this.options; this.opos = [ event.pageX, event.pageY ]; if (this.options.disabled) { return; } this.selectees = $(options.filter, this.element[0]); this._trigger("start", event); $(options.appendTo).append(this.helper); // position helper (lasso) this.helper.css({ "left": event.pageX, "top": event.pageY, "width": 0, "height": 0 }); if (options.autoRefresh) { this.refresh(); } this.selectees.filter(".ui-selected").each(function() { var selectee = $.data(this, "selectable-item"); selectee.startselected = true; if (!event.metaKey && !event.ctrlKey) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } }); $(event.target).parents().addBack().each(function() { var doSelect, selectee = $.data(this, "selectable-item"); if (selectee) { doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected"); selectee.$element .removeClass(doSelect ? "ui-unselecting" : "ui-selected") .addClass(doSelect ? "ui-selecting" : "ui-unselecting"); selectee.unselecting = !doSelect; selectee.selecting = doSelect; selectee.selected = doSelect; // selectable (UN)SELECTING callback if (doSelect) { that._trigger("selecting", event, { selecting: selectee.element }); } else { that._trigger("unselecting", event, { unselecting: selectee.element }); } return false; } }); }, _mouseDrag: function(event) { this.dragged = true; if (this.options.disabled) { return; } var tmp, that = this, options = this.options, x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } this.helper.css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1 }); this.selectees.each(function() { var selectee = $.data(this, "selectable-item"), hit = false; //prevent helper from being selected if appendTo: selectable if (!selectee || selectee.element === that.element[0]) { return; } if (options.tolerance === "touch") { hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); } else if (options.tolerance === "fit") { hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); } if (hit) { // SELECT if (selectee.selected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; } if (selectee.unselecting) { selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; } if (!selectee.selecting) { selectee.$element.addClass("ui-selecting"); selectee.selecting = true; // selectable SELECTING callback that._trigger("selecting", event, { selecting: selectee.element }); } } else { // UNSELECT if (selectee.selecting) { if ((event.metaKey || event.ctrlKey) && selectee.startselected) { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; selectee.$element.addClass("ui-selected"); selectee.selected = true; } else { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; if (selectee.startselected) { selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; } // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } if (selectee.selected) { if (!event.metaKey && !event.ctrlKey && !selectee.startselected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } } }); return false; }, _mouseStop: function(event) { var that = this; this.dragged = false; $(".ui-unselecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; selectee.startselected = false; that._trigger("unselected", event, { unselected: selectee.element }); }); $(".ui-selecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass("ui-selecting").addClass("ui-selected"); selectee.selecting = false; selectee.selected = true; selectee.startselected = true; that._trigger("selected", event, { selected: selectee.element }); }); this._trigger("stop", event); this.helper.remove(); return false; } }); /*! * jQuery UI Selectmenu 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/selectmenu */ var selectmenu = $.widget( "ui.selectmenu", { version: "1.11.0", defaultElement: "<select>", options: { appendTo: null, disabled: null, icons: { button: "ui-icon-triangle-1-s" }, position: { my: "left top", at: "left bottom", collision: "none" }, width: null, // callbacks change: null, close: null, focus: null, open: null, select: null }, _create: function() { var selectmenuId = this.element.uniqueId().attr( "id" ); this.ids = { element: selectmenuId, button: selectmenuId + "-button", menu: selectmenuId + "-menu" }; this._drawButton(); this._drawMenu(); if ( this.options.disabled ) { this.disable(); } }, _drawButton: function() { var that = this, tabindex = this.element.attr( "tabindex" ); // Associate existing label with the new button this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button ); this._on( this.label, { click: function( event ) { this.button.focus(); event.preventDefault(); } }); // Hide original select element this.element.hide(); // Create button this.button = $( "<span>", { "class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all", tabindex: tabindex || this.options.disabled ? -1 : 0, id: this.ids.button, role: "combobox", "aria-expanded": "false", "aria-autocomplete": "list", "aria-owns": this.ids.menu, "aria-haspopup": "true" }) .insertAfter( this.element ); $( "<span>", { "class": "ui-icon " + this.options.icons.button }) .prependTo( this.button ); this.buttonText = $( "<span>", { "class": "ui-selectmenu-text" }) .appendTo( this.button ); this._setText( this.buttonText, this.element.find( "option:selected" ).text() ); this._setOption( "width", this.options.width ); this._on( this.button, this._buttonEvents ); this.button.one( "focusin", function() { // Delay rendering the menu items until the button receives focus. // The menu may have already been rendered via a programmatic open. if ( !that.menuItems ) { that._refreshMenu(); } }); this._hoverable( this.button ); this._focusable( this.button ); }, _drawMenu: function() { var that = this; // Create menu this.menu = $( "<ul>", { "aria-hidden": "true", "aria-labelledby": this.ids.button, id: this.ids.menu }); // Wrap menu this.menuWrap = $( "<div>", { "class": "ui-selectmenu-menu ui-front" }) .append( this.menu ) .appendTo( this._appendTo() ); // Initialize menu widget this.menuInstance = this.menu .menu({ role: "listbox", select: function( event, ui ) { event.preventDefault(); that._select( ui.item.data( "ui-selectmenu-item" ), event ); }, focus: function( event, ui ) { var item = ui.item.data( "ui-selectmenu-item" ); // Prevent inital focus from firing and check if its a newly focused item if ( that.focusIndex != null && item.index !== that.focusIndex ) { that._trigger( "focus", event, { item: item } ); if ( !that.isOpen ) { that._select( item, event ); } } that.focusIndex = item.index; that.button.attr( "aria-activedescendant", that.menuItems.eq( item.index ).attr( "id" ) ); } }) .menu( "instance" ); // Adjust menu styles to dropdown this.menu .addClass( "ui-corner-bottom" ) .removeClass( "ui-corner-all" ); // Don't close the menu on mouseleave this.menuInstance._off( this.menu, "mouseleave" ); // Cancel the menu's collapseAll on document click this.menuInstance._closeOnDocumentClick = function() { return false; }; // Selects often contain empty items, but never contain dividers this.menuInstance._isDivider = function() { return false; }; }, refresh: function() { this._refreshMenu(); this._setText( this.buttonText, this._getSelectedItem().text() ); this._setOption( "width", this.options.width ); }, _refreshMenu: function() { this.menu.empty(); var item, options = this.element.find( "option" ); if ( !options.length ) { return; } this._parseOptions( options ); this._renderMenu( this.menu, this.items ); this.menuInstance.refresh(); this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" ); item = this._getSelectedItem(); // Update the menu to have the correct item focused this.menuInstance.focus( null, item ); this._setAria( item.data( "ui-selectmenu-item" ) ); // Set disabled state this._setOption( "disabled", this.element.prop( "disabled" ) ); }, open: function( event ) { if ( this.options.disabled ) { return; } // If this is the first time the menu is being opened, render the items if ( !this.menuItems ) { this._refreshMenu(); } else { // Menu clears focus on close, reset focus to selected item this.menu.find( ".ui-state-focus" ).removeClass( "ui-state-focus" ); this.menuInstance.focus( null, this._getSelectedItem() ); } this.isOpen = true; this._toggleAttr(); this._resizeMenu(); this._position(); this._on( this.document, this._documentClick ); this._trigger( "open", event ); }, _position: function() { this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) ); }, close: function( event ) { if ( !this.isOpen ) { return; } this.isOpen = false; this._toggleAttr(); this._off( this.document ); this._trigger( "close", event ); }, widget: function() { return this.button; }, menuWidget: function() { return this.menu; }, _renderMenu: function( ul, items ) { var that = this, currentOptgroup = ""; $.each( items, function( index, item ) { if ( item.optgroup !== currentOptgroup ) { $( "<li>", { "class": "ui-selectmenu-optgroup ui-menu-divider" + ( item.element.parent( "optgroup" ).prop( "disabled" ) ? " ui-state-disabled" : "" ), text: item.optgroup }) .appendTo( ul ); currentOptgroup = item.optgroup; } that._renderItemData( ul, item ); }); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-selectmenu-item", item ); }, _renderItem: function( ul, item ) { var li = $( "<li>" ); if ( item.disabled ) { li.addClass( "ui-state-disabled" ); } this._setText( li, item.label ); return li.appendTo( ul ); }, _setText: function( element, value ) { if ( value ) { element.text( value ); } else { element.html( "&#160;" ); } }, _move: function( direction, event ) { var item, next, filter = ".ui-menu-item"; if ( this.isOpen ) { item = this.menuItems.eq( this.focusIndex ); } else { item = this.menuItems.eq( this.element[ 0 ].selectedIndex ); filter += ":not(.ui-state-disabled)"; } if ( direction === "first" || direction === "last" ) { next = item[ direction === "first" ? "prevAll" : "nextAll" ]( filter ).eq( -1 ); } else { next = item[ direction + "All" ]( filter ).eq( 0 ); } if ( next.length ) { this.menuInstance.focus( event, next ); } }, _getSelectedItem: function() { return this.menuItems.eq( this.element[ 0 ].selectedIndex ); }, _toggle: function( event ) { this[ this.isOpen ? "close" : "open" ]( event ); }, _documentClick: { mousedown: function( event ) { if ( !this.isOpen ) { return; } if ( !$( event.target ).closest( ".ui-selectmenu-menu, #" + this.ids.button ).length ) { this.close( event ); } } }, _buttonEvents: { click: "_toggle", keydown: function( event ) { var preventDefault = true; switch ( event.keyCode ) { case $.ui.keyCode.TAB: case $.ui.keyCode.ESCAPE: this.close( event ); preventDefault = false; break; case $.ui.keyCode.ENTER: if ( this.isOpen ) { this._selectFocusedItem( event ); } break; case $.ui.keyCode.UP: if ( event.altKey ) { this._toggle( event ); } else { this._move( "prev", event ); } break; case $.ui.keyCode.DOWN: if ( event.altKey ) { this._toggle( event ); } else { this._move( "next", event ); } break; case $.ui.keyCode.SPACE: if ( this.isOpen ) { this._selectFocusedItem( event ); } else { this._toggle( event ); } break; case $.ui.keyCode.LEFT: this._move( "prev", event ); break; case $.ui.keyCode.RIGHT: this._move( "next", event ); break; case $.ui.keyCode.HOME: case $.ui.keyCode.PAGE_UP: this._move( "first", event ); break; case $.ui.keyCode.END: case $.ui.keyCode.PAGE_DOWN: this._move( "last", event ); break; default: this.menu.trigger( event ); preventDefault = false; } if ( preventDefault ) { event.preventDefault(); } } }, _selectFocusedItem: function( event ) { var item = this.menuItems.eq( this.focusIndex ); if ( !item.hasClass( "ui-state-disabled" ) ) { this._select( item.data( "ui-selectmenu-item" ), event ); } }, _select: function( item, event ) { var oldIndex = this.element[ 0 ].selectedIndex; // Change native select element this.element[ 0 ].selectedIndex = item.index; this._setText( this.buttonText, item.label ); this._setAria( item ); this._trigger( "select", event, { item: item } ); if ( item.index !== oldIndex ) { this._trigger( "change", event, { item: item } ); } this.close( event ); }, _setAria: function( item ) { var id = this.menuItems.eq( item.index ).attr( "id" ); this.button.attr({ "aria-labelledby": id, "aria-activedescendant": id }); this.menu.attr( "aria-activedescendant", id ); }, _setOption: function( key, value ) { if ( key === "icons" ) { this.button.find( "span.ui-icon" ) .removeClass( this.options.icons.button ) .addClass( value.button ); } this._super( key, value ); if ( key === "appendTo" ) { this.menuWrap.appendTo( this._appendTo() ); } if ( key === "disabled" ) { this.menuInstance.option( "disabled", value ); this.button .toggleClass( "ui-state-disabled", value ) .attr( "aria-disabled", value ); this.element.prop( "disabled", value ); if ( value ) { this.button.attr( "tabindex", -1 ); this.close(); } else { this.button.attr( "tabindex", 0 ); } } if ( key === "width" ) { if ( !value ) { value = this.element.outerWidth(); } this.button.outerWidth( value ); } }, _appendTo: function() { var element = this.options.appendTo; if ( element ) { element = element.jquery || element.nodeType ? $( element ) : this.document.find( element ).eq( 0 ); } if ( !element || !element[ 0 ] ) { element = this.element.closest( ".ui-front" ); } if ( !element.length ) { element = this.document[ 0 ].body; } return element; }, _toggleAttr: function() { this.button .toggleClass( "ui-corner-top", this.isOpen ) .toggleClass( "ui-corner-all", !this.isOpen ) .attr( "aria-expanded", this.isOpen ); this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen ); this.menu.attr( "aria-hidden", !this.isOpen ); }, _resizeMenu: function() { this.menu.outerWidth( Math.max( this.button.outerWidth(), // support: IE10 // IE10 wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping this.menu.width( "" ).outerWidth() + 1 ) ); }, _getCreateOptions: function() { return { disabled: this.element.prop( "disabled" ) }; }, _parseOptions: function( options ) { var data = []; options.each(function( index, item ) { var option = $( item ), optgroup = option.parent( "optgroup" ); data.push({ element: option, index: index, value: option.attr( "value" ), label: option.text(), optgroup: optgroup.attr( "label" ) || "", disabled: optgroup.prop( "disabled" ) || option.prop( "disabled" ) }); }); this.items = data; }, _destroy: function() { this.menuWrap.remove(); this.button.remove(); this.element.show(); this.element.removeUniqueId(); this.label.attr( "for", this.ids.element ); } }); /*! * jQuery UI Slider 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/slider/ */ var slider = $.widget( "ui.slider", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null, // callbacks change: null, slide: null, start: null, stop: null }, // number of pages in a slider // (how many times can you page up/down to go through the whole range) numPages: 5, _create: function() { this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass( "ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); this._refresh(); this._setOption( "disabled", this.options.disabled ); this._animateOff = false; }, _refresh: function() { this._createRange(); this._createHandles(); this._setupEvents(); this._refreshValue(); }, _createHandles: function() { var i, handleCount, options = this.options, existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), handle = "<span class='ui-slider-handle ui-state-default ui-corner-all' tabindex='0'></span>", handles = []; handleCount = ( options.values && options.values.length ) || 1; if ( existingHandles.length > handleCount ) { existingHandles.slice( handleCount ).remove(); existingHandles = existingHandles.slice( 0, handleCount ); } for ( i = existingHandles.length; i < handleCount; i++ ) { handles.push( handle ); } this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); this.handle = this.handles.eq( 0 ); this.handles.each(function( i ) { $( this ).data( "ui-slider-handle-index", i ); }); }, _createRange: function() { var options = this.options, classes = ""; if ( options.range ) { if ( options.range === true ) { if ( !options.values ) { options.values = [ this._valueMin(), this._valueMin() ]; } else if ( options.values.length && options.values.length !== 2 ) { options.values = [ options.values[0], options.values[0] ]; } else if ( $.isArray( options.values ) ) { options.values = options.values.slice(0); } } if ( !this.range || !this.range.length ) { this.range = $( "<div></div>" ) .appendTo( this.element ); classes = "ui-slider-range" + // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes " ui-widget-header ui-corner-all"; } else { this.range.removeClass( "ui-slider-range-min ui-slider-range-max" ) // Handle range switching from true to min/max .css({ "left": "", "bottom": "" }); } this.range.addClass( classes + ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) ); } else { if ( this.range ) { this.range.remove(); } this.range = null; } }, _setupEvents: function() { this._off( this.handles ); this._on( this.handles, this._handleEvents ); this._hoverable( this.handles ); this._focusable( this.handles ); }, _destroy: function() { this.handles.remove(); if ( this.range ) { this.range.remove(); } this.element .removeClass( "ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-widget" + " ui-widget-content" + " ui-corner-all" ); this._mouseDestroy(); }, _mouseCapture: function( event ) { var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, that = this, o = this.options; if ( o.disabled ) { return false; } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); position = { x: event.pageX, y: event.pageY }; normValue = this._normValueFromMouse( position ); distance = this._valueMax() - this._valueMin() + 1; this.handles.each(function( i ) { var thisDistance = Math.abs( normValue - that.values(i) ); if (( distance > thisDistance ) || ( distance === thisDistance && (i === that._lastChangedValue || that.values(i) === o.min ))) { distance = thisDistance; closestHandle = $( this ); index = i; } }); allowed = this._start( event, index ); if ( allowed === false ) { return false; } this._mouseSliding = true; this._handleIndex = index; closestHandle .addClass( "ui-state-active" ) .focus(); offset = closestHandle.offset(); mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" ); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - ( closestHandle.width() / 2 ), top: event.pageY - offset.top - ( closestHandle.height() / 2 ) - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) }; if ( !this.handles.hasClass( "ui-state-hover" ) ) { this._slide( event, index, normValue ); } this._animateOff = true; return true; }, _mouseStart: function() { return true; }, _mouseDrag: function( event ) { var position = { x: event.pageX, y: event.pageY }, normValue = this._normValueFromMouse( position ); this._slide( event, this._handleIndex, normValue ); return false; }, _mouseStop: function( event ) { this.handles.removeClass( "ui-state-active" ); this._mouseSliding = false; this._stop( event, this._handleIndex ); this._change( event, this._handleIndex ); this._handleIndex = null; this._clickOffset = null; this._animateOff = false; return false; }, _detectOrientation: function() { this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; }, _normValueFromMouse: function( position ) { var pixelTotal, pixelMouse, percentMouse, valueTotal, valueMouse; if ( this.orientation === "horizontal" ) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); } percentMouse = ( pixelMouse / pixelTotal ); if ( percentMouse > 1 ) { percentMouse = 1; } if ( percentMouse < 0 ) { percentMouse = 0; } if ( this.orientation === "vertical" ) { percentMouse = 1 - percentMouse; } valueTotal = this._valueMax() - this._valueMin(); valueMouse = this._valueMin() + percentMouse * valueTotal; return this._trimAlignValue( valueMouse ); }, _start: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } return this._trigger( "start", event, uiHash ); }, _slide: function( event, index, newVal ) { var otherVal, newValues, allowed; if ( this.options.values && this.options.values.length ) { otherVal = this.values( index ? 0 : 1 ); if ( ( this.options.values.length === 2 && this.options.range === true ) && ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) ) { newVal = otherVal; } if ( newVal !== this.values( index ) ) { newValues = this.values(); newValues[ index ] = newVal; // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal, values: newValues } ); otherVal = this.values( index ? 0 : 1 ); if ( allowed !== false ) { this.values( index, newVal ); } } } else { if ( newVal !== this.value() ) { // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal } ); if ( allowed !== false ) { this.value( newVal ); } } } }, _stop: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "stop", event, uiHash ); }, _change: function( event, index ) { if ( !this._keySliding && !this._mouseSliding ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } //store the last changed value index for reference when handles overlap this._lastChangedValue = index; this._trigger( "change", event, uiHash ); } }, value: function( newValue ) { if ( arguments.length ) { this.options.value = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, 0 ); return; } return this._value(); }, values: function( index, newValue ) { var vals, newValues, i; if ( arguments.length > 1 ) { this.options.values[ index ] = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, index ); return; } if ( arguments.length ) { if ( $.isArray( arguments[ 0 ] ) ) { vals = this.options.values; newValues = arguments[ 0 ]; for ( i = 0; i < vals.length; i += 1 ) { vals[ i ] = this._trimAlignValue( newValues[ i ] ); this._change( null, i ); } this._refreshValue(); } else { if ( this.options.values && this.options.values.length ) { return this._values( index ); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function( key, value ) { var i, valsLength = 0; if ( key === "range" && this.options.range === true ) { if ( value === "min" ) { this.options.value = this._values( 0 ); this.options.values = null; } else if ( value === "max" ) { this.options.value = this._values( this.options.values.length - 1 ); this.options.values = null; } } if ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } if ( key === "disabled" ) { this.element.toggleClass( "ui-state-disabled", !!value ); } this._super( key, value ); switch ( key ) { case "orientation": this._detectOrientation(); this.element .removeClass( "ui-slider-horizontal ui-slider-vertical" ) .addClass( "ui-slider-" + this.orientation ); this._refreshValue(); break; case "value": this._animateOff = true; this._refreshValue(); this._change( null, 0 ); this._animateOff = false; break; case "values": this._animateOff = true; this._refreshValue(); for ( i = 0; i < valsLength; i += 1 ) { this._change( null, i ); } this._animateOff = false; break; case "min": case "max": this._animateOff = true; this._refreshValue(); this._animateOff = false; break; case "range": this._animateOff = true; this._refresh(); this._animateOff = false; break; } }, //internal value getter // _value() returns value trimmed by min and max, aligned by step _value: function() { var val = this.options.value; val = this._trimAlignValue( val ); return val; }, //internal values getter // _values() returns array of values trimmed by min and max, aligned by step // _values( index ) returns single value trimmed by min and max, aligned by step _values: function( index ) { var val, vals, i; if ( arguments.length ) { val = this.options.values[ index ]; val = this._trimAlignValue( val ); return val; } else if ( this.options.values && this.options.values.length ) { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned vals = this.options.values.slice(); for ( i = 0; i < vals.length; i+= 1) { vals[ i ] = this._trimAlignValue( vals[ i ] ); } return vals; } else { return []; } }, // returns the step-aligned value that val is closest to, between (inclusive) min and max _trimAlignValue: function( val ) { if ( val <= this._valueMin() ) { return this._valueMin(); } if ( val >= this._valueMax() ) { return this._valueMax(); } var step = ( this.options.step > 0 ) ? this.options.step : 1, valModStep = (val - this._valueMin()) % step, alignValue = val - valModStep; if ( Math.abs(valModStep) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat( alignValue.toFixed(5) ); }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.options.max; }, _refreshValue: function() { var lastValPercent, valPercent, value, valueMin, valueMax, oRange = this.options.range, o = this.options, that = this, animate = ( !this._animateOff ) ? o.animate : false, _set = {}; if ( this.options.values && this.options.values.length ) { this.handles.each(function( i ) { valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( that.options.range === true ) { if ( that.orientation === "horizontal" ) { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } else { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } lastValPercent = valPercent; }); } else { value = this.value(); valueMin = this._valueMin(); valueMax = this._valueMax(); valPercent = ( valueMax !== valueMin ) ? ( value - valueMin ) / ( valueMax - valueMin ) * 100 : 0; _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( oRange === "min" && this.orientation === "horizontal" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "horizontal" ) { this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } if ( oRange === "min" && this.orientation === "vertical" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "vertical" ) { this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } } }, _handleEvents: { keydown: function( event ) { var allowed, curVal, newVal, step, index = $( event.target ).data( "ui-slider-handle-index" ); switch ( event.keyCode ) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; $( event.target ).addClass( "ui-state-active" ); allowed = this._start( event, index ); if ( allowed === false ) { return; } } break; } step = this.options.step; if ( this.options.values && this.options.values.length ) { curVal = newVal = this.values( index ); } else { curVal = newVal = this.value(); } switch ( event.keyCode ) { case $.ui.keyCode.HOME: newVal = this._valueMin(); break; case $.ui.keyCode.END: newVal = this._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = this._trimAlignValue( curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / this.numPages ) ); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if ( curVal === this._valueMax() ) { return; } newVal = this._trimAlignValue( curVal + step ); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if ( curVal === this._valueMin() ) { return; } newVal = this._trimAlignValue( curVal - step ); break; } this._slide( event, index, newVal ); }, keyup: function( event ) { var index = $( event.target ).data( "ui-slider-handle-index" ); if ( this._keySliding ) { this._keySliding = false; this._stop( event, index ); this._change( event, index ); $( event.target ).removeClass( "ui-state-active" ); } } } }); /*! * jQuery UI Sortable 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/sortable/ */ var sortable = $.widget("ui.sortable", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "sort", ready: false, options: { appendTo: "parent", axis: false, connectWith: false, containment: false, cursor: "auto", cursorAt: false, dropOnEmpty: true, forcePlaceholderSize: false, forceHelperSize: false, grid: false, handle: false, helper: "original", items: "> *", opacity: false, placeholder: false, revert: false, scroll: true, scrollSensitivity: 20, scrollSpeed: 20, scope: "default", tolerance: "intersect", zIndex: 1000, // callbacks activate: null, beforeStop: null, change: null, deactivate: null, out: null, over: null, receive: null, remove: null, sort: null, start: null, stop: null, update: null }, _isOverAxis: function( x, reference, size ) { return ( x >= reference ) && ( x < ( reference + size ) ); }, _isFloating: function( item ) { return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display")); }, _create: function() { var o = this.options; this.containerCache = {}; this.element.addClass("ui-sortable"); //Get the items this.refresh(); //Let's determine if the items are being displayed horizontally this.floating = this.items.length ? o.axis === "x" || this._isFloating(this.items[0].item) : false; //Let's determine the parent's offset this.offset = this.element.offset(); //Initialize mouse events for interaction this._mouseInit(); this._setHandleClassName(); //We're ready to go this.ready = true; }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "handle" ) { this._setHandleClassName(); } }, _setHandleClassName: function() { this.element.find( ".ui-sortable-handle" ).removeClass( "ui-sortable-handle" ); $.each( this.items, function() { ( this.instance.options.handle ? this.item.find( this.instance.options.handle ) : this.item ) .addClass( "ui-sortable-handle" ); }); }, _destroy: function() { this.element .removeClass( "ui-sortable ui-sortable-disabled" ) .find( ".ui-sortable-handle" ) .removeClass( "ui-sortable-handle" ); this._mouseDestroy(); for ( var i = this.items.length - 1; i >= 0; i-- ) { this.items[i].item.removeData(this.widgetName + "-item"); } return this; }, _mouseCapture: function(event, overrideHandle) { var currentItem = null, validHandle = false, that = this; if (this.reverting) { return false; } if(this.options.disabled || this.options.type === "static") { return false; } //We have to refresh the items data once first this._refreshItems(event); //Find out if the clicked node (or one of its parents) is a actual item in this.items $(event.target).parents().each(function() { if($.data(this, that.widgetName + "-item") === that) { currentItem = $(this); return false; } }); if($.data(event.target, that.widgetName + "-item") === that) { currentItem = $(event.target); } if(!currentItem) { return false; } if(this.options.handle && !overrideHandle) { $(this.options.handle, currentItem).find("*").addBack().each(function() { if(this === event.target) { validHandle = true; } }); if(!validHandle) { return false; } } this.currentItem = currentItem; this._removeCurrentsFromItems(); return true; }, _mouseStart: function(event, overrideHandle, noActivation) { var i, body, o = this.options; this.currentContainer = this; //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture this.refreshPositions(); //Create and append the visible helper this.helper = this._createHelper(event); //Cache the helper size this._cacheHelperProportions(); /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Get the next scrolling parent this.scrollParent = this.helper.scrollParent(); //The element's absolute position on the page minus margins this.offset = this.currentItem.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); // Only after we got the offset, we can change the helper's position to absolute // TODO: Still need to figure out a way to make relative sorting possible this.helper.css("position", "absolute"); this.cssPosition = this.helper.css("position"); //Generate the original position this.originalPosition = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Cache the former DOM position this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] }; //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way if(this.helper[0] !== this.currentItem[0]) { this.currentItem.hide(); } //Create the placeholder this._createPlaceholder(); //Set a containment if given in the options if(o.containment) { this._setContainment(); } if( o.cursor && o.cursor !== "auto" ) { // cursor option body = this.document.find( "body" ); // support: IE this.storedCursor = body.css( "cursor" ); body.css( "cursor", o.cursor ); this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body ); } if(o.opacity) { // opacity option if (this.helper.css("opacity")) { this._storedOpacity = this.helper.css("opacity"); } this.helper.css("opacity", o.opacity); } if(o.zIndex) { // zIndex option if (this.helper.css("zIndex")) { this._storedZIndex = this.helper.css("zIndex"); } this.helper.css("zIndex", o.zIndex); } //Prepare scrolling if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { this.overflowOffset = this.scrollParent.offset(); } //Call callbacks this._trigger("start", event, this._uiHash()); //Recache the helper size if(!this._preserveHelperProportions) { this._cacheHelperProportions(); } //Post "activate" events to possible containers if( !noActivation ) { for ( i = this.containers.length - 1; i >= 0; i-- ) { this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) ); } } //Prepare possible droppables if($.ui.ddmanager) { $.ui.ddmanager.current = this; } if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this.dragging = true; this.helper.addClass("ui-sortable-helper"); this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position return true; }, _mouseDrag: function(event) { var i, item, itemElement, intersection, o = this.options, scrolled = false; //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); if (!this.lastPositionAbs) { this.lastPositionAbs = this.positionAbs; } //Do scrolling if(this.options.scroll) { if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) { this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; } if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) { this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; } } else { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } } //Regenerate the absolute position used for position checks this.positionAbs = this._convertPositionTo("absolute"); //Set the helper position if(!this.options.axis || this.options.axis !== "y") { this.helper[0].style.left = this.position.left+"px"; } if(!this.options.axis || this.options.axis !== "x") { this.helper[0].style.top = this.position.top+"px"; } //Rearrange for (i = this.items.length - 1; i >= 0; i--) { //Cache variables and intersection, continue if no intersection item = this.items[i]; itemElement = item.item[0]; intersection = this._intersectsWithPointer(item); if (!intersection) { continue; } // Only put the placeholder inside the current Container, skip all // items from other containers. This works because when moving // an item from one container to another the // currentContainer is switched before the placeholder is moved. // // Without this, moving items in "sub-sortables" can cause // the placeholder to jitter between the outer and inner container. if (item.instance !== this.currentContainer) { continue; } // cannot intersect with itself // no useless actions that have been done before // no action if the item moved is the parent of the item checked if (itemElement !== this.currentItem[0] && this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement && !$.contains(this.placeholder[0], itemElement) && (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true) ) { this.direction = intersection === 1 ? "down" : "up"; if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) { this._rearrange(event, item); } else { break; } this._trigger("change", event, this._uiHash()); break; } } //Post events to containers this._contactContainers(event); //Interconnect with droppables if($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } //Call callbacks this._trigger("sort", event, this._uiHash()); this.lastPositionAbs = this.positionAbs; return false; }, _mouseStop: function(event, noPropagation) { if(!event) { return; } //If we are using droppables, inform the manager about the drop if ($.ui.ddmanager && !this.options.dropBehaviour) { $.ui.ddmanager.drop(this, event); } if(this.options.revert) { var that = this, cur = this.placeholder.offset(), axis = this.options.axis, animation = {}; if ( !axis || axis === "x" ) { animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft); } if ( !axis || axis === "y" ) { animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop); } this.reverting = true; $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() { that._clear(event); }); } else { this._clear(event, noPropagation); } return false; }, cancel: function() { if(this.dragging) { this._mouseUp({ target: null }); if(this.options.helper === "original") { this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } //Post deactivating events to containers for (var i = this.containers.length - 1; i >= 0; i--){ this.containers[i]._trigger("deactivate", null, this._uiHash(this)); if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", null, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } if (this.placeholder) { //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! if(this.placeholder[0].parentNode) { this.placeholder[0].parentNode.removeChild(this.placeholder[0]); } if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) { this.helper.remove(); } $.extend(this, { helper: null, dragging: false, reverting: false, _noFinalSort: null }); if(this.domPosition.prev) { $(this.domPosition.prev).after(this.currentItem); } else { $(this.domPosition.parent).prepend(this.currentItem); } } return this; }, serialize: function(o) { var items = this._getItemsAsjQuery(o && o.connected), str = []; o = o || {}; $(items).each(function() { var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/)); if (res) { str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2])); } }); if(!str.length && o.key) { str.push(o.key + "="); } return str.join("&"); }, toArray: function(o) { var items = this._getItemsAsjQuery(o && o.connected), ret = []; o = o || {}; items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); }); return ret; }, /* Be careful with the following core functions */ _intersectsWith: function(item) { var x1 = this.positionAbs.left, x2 = x1 + this.helperProportions.width, y1 = this.positionAbs.top, y2 = y1 + this.helperProportions.height, l = item.left, r = l + item.width, t = item.top, b = t + item.height, dyClick = this.offset.click.top, dxClick = this.offset.click.left, isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ), isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ), isOverElement = isOverElementHeight && isOverElementWidth; if ( this.options.tolerance === "pointer" || this.options.forcePointerForContainers || (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"]) ) { return isOverElement; } else { return (l < x1 + (this.helperProportions.width / 2) && // Right Half x2 - (this.helperProportions.width / 2) < r && // Left Half t < y1 + (this.helperProportions.height / 2) && // Bottom Half y2 - (this.helperProportions.height / 2) < b ); // Top Half } }, _intersectsWithPointer: function(item) { var isOverElementHeight = (this.options.axis === "x") || this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = (this.options.axis === "y") || this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth, verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (!isOverElement) { return false; } return this.floating ? ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 ) : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) ); }, _intersectsWithSides: function(item) { var isOverBottomHalf = this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), isOverRightHalf = this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (this.floating && horizontalDirection) { return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf)); } else { return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf)); } }, _getDragVerticalDirection: function() { var delta = this.positionAbs.top - this.lastPositionAbs.top; return delta !== 0 && (delta > 0 ? "down" : "up"); }, _getDragHorizontalDirection: function() { var delta = this.positionAbs.left - this.lastPositionAbs.left; return delta !== 0 && (delta > 0 ? "right" : "left"); }, refresh: function(event) { this._refreshItems(event); this._setHandleClassName(); this.refreshPositions(); return this; }, _connectWith: function() { var options = this.options; return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith; }, _getItemsAsjQuery: function(connected) { var i, j, cur, inst, items = [], queries = [], connectWith = this._connectWith(); if(connectWith && connected) { for (i = connectWith.length - 1; i >= 0; i--){ cur = $(connectWith[i]); for ( j = cur.length - 1; j >= 0; j--){ inst = $.data(cur[j], this.widgetFullName); if(inst && inst !== this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]); } } } } queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]); function addItems() { items.push( this ); } for (i = queries.length - 1; i >= 0; i--){ queries[i][0].each( addItems ); } return $(items); }, _removeCurrentsFromItems: function() { var list = this.currentItem.find(":data(" + this.widgetName + "-item)"); this.items = $.grep(this.items, function (item) { for (var j=0; j < list.length; j++) { if(list[j] === item.item[0]) { return false; } } return true; }); }, _refreshItems: function(event) { this.items = []; this.containers = [this]; var i, j, cur, inst, targetData, _queries, item, queriesLength, items = this.items, queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]], connectWith = this._connectWith(); if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down for (i = connectWith.length - 1; i >= 0; i--){ cur = $(connectWith[i]); for (j = cur.length - 1; j >= 0; j--){ inst = $.data(cur[j], this.widgetFullName); if(inst && inst !== this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]); this.containers.push(inst); } } } } for (i = queries.length - 1; i >= 0; i--) { targetData = queries[i][1]; _queries = queries[i][0]; for (j=0, queriesLength = _queries.length; j < queriesLength; j++) { item = $(_queries[j]); item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager) items.push({ item: item, instance: targetData, width: 0, height: 0, left: 0, top: 0 }); } } }, refreshPositions: function(fast) { //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change if(this.offsetParent && this.helper) { this.offset.parent = this._getParentOffset(); } var i, item, t, p; for (i = this.items.length - 1; i >= 0; i--){ item = this.items[i]; //We ignore calculating positions of all connected containers when we're not over them if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) { continue; } t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; if (!fast) { item.width = t.outerWidth(); item.height = t.outerHeight(); } p = t.offset(); item.left = p.left; item.top = p.top; } if(this.options.custom && this.options.custom.refreshContainers) { this.options.custom.refreshContainers.call(this); } else { for (i = this.containers.length - 1; i >= 0; i--){ p = this.containers[i].element.offset(); this.containers[i].containerCache.left = p.left; this.containers[i].containerCache.top = p.top; this.containers[i].containerCache.width = this.containers[i].element.outerWidth(); this.containers[i].containerCache.height = this.containers[i].element.outerHeight(); } } return this; }, _createPlaceholder: function(that) { that = that || this; var className, o = that.options; if(!o.placeholder || o.placeholder.constructor === String) { className = o.placeholder; o.placeholder = { element: function() { var nodeName = that.currentItem[0].nodeName.toLowerCase(), element = $( "<" + nodeName + ">", that.document[0] ) .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder") .removeClass("ui-sortable-helper"); if ( nodeName === "tr" ) { that.currentItem.children().each(function() { $( "<td>&#160;</td>", that.document[0] ) .attr( "colspan", $( this ).attr( "colspan" ) || 1 ) .appendTo( element ); }); } else if ( nodeName === "img" ) { element.attr( "src", that.currentItem.attr( "src" ) ); } if ( !className ) { element.css( "visibility", "hidden" ); } return element; }, update: function(container, p) { // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified if(className && !o.forcePlaceholderSize) { return; } //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); } if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); } } }; } //Create the placeholder that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem)); //Append it after the actual current item that.currentItem.after(that.placeholder); //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317) o.placeholder.update(that, that.placeholder); }, _contactContainers: function(event) { var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom, floating, axis, innermostContainer = null, innermostIndex = null; // get innermost container that intersects with item for (i = this.containers.length - 1; i >= 0; i--) { // never consider a container that's located within the item itself if($.contains(this.currentItem[0], this.containers[i].element[0])) { continue; } if(this._intersectsWith(this.containers[i].containerCache)) { // if we've already found a container and it's more "inner" than this, then continue if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) { continue; } innermostContainer = this.containers[i]; innermostIndex = i; } else { // container doesn't intersect. trigger "out" event if necessary if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", event, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } // if no intersecting containers found, return if(!innermostContainer) { return; } // move the item into the container if it's not there already if(this.containers.length === 1) { if (!this.containers[innermostIndex].containerCache.over) { this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } } else { //When entering a new container, we will find the item with the least distance and append our item near it dist = 10000; itemWithLeastDistance = null; floating = innermostContainer.floating || this._isFloating(this.currentItem); posProperty = floating ? "left" : "top"; sizeProperty = floating ? "width" : "height"; axis = floating ? "clientX" : "clientY"; for (j = this.items.length - 1; j >= 0; j--) { if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) { continue; } if(this.items[j].item[0] === this.currentItem[0]) { continue; } cur = this.items[j].item.offset()[posProperty]; nearBottom = false; if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) { nearBottom = true; } if ( Math.abs( event[ axis ] - cur ) < dist ) { dist = Math.abs( event[ axis ] - cur ); itemWithLeastDistance = this.items[ j ]; this.direction = nearBottom ? "up": "down"; } } //Check if dropOnEmpty is enabled if(!itemWithLeastDistance && !this.options.dropOnEmpty) { return; } if(this.currentContainer === this.containers[innermostIndex]) { return; } itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); this._trigger("change", event, this._uiHash()); this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); this.currentContainer = this.containers[innermostIndex]; //Update the placeholder this.options.placeholder.update(this.currentContainer, this.placeholder); this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem); //Add the helper to the DOM if that didn't happen already if(!helper.parents("body").length) { $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); } if(helper[0] === this.currentItem[0]) { this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") }; } if(!helper[0].style.width || o.forceHelperSize) { helper.width(this.currentItem.width()); } if(!helper[0].style.height || o.forceHelperSize) { helper.height(this.currentItem.height()); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = {left: +obj[0], top: +obj[1] || 0}; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _getParentOffset: function() { //Get the offsetParent and cache its position this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } // This needs to be actually done for all browsers, since pageX/pageY includes this information // with an ugly IE fix if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition === "relative") { var p = this.currentItem.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() }; } else { return { top: 0, left: 0 }; } }, _cacheMargins: function() { this.margins = { left: (parseInt(this.currentItem.css("marginLeft"),10) || 0), top: (parseInt(this.currentItem.css("marginTop"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var ce, co, over, o = this.options; if(o.containment === "parent") { o.containment = this.helper[0].parentNode; } if(o.containment === "document" || o.containment === "window") { this.containment = [ 0 - this.offset.relative.left - this.offset.parent.left, 0 - this.offset.relative.top - this.offset.parent.top, $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left, ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top ]; } if(!(/^(document|window|parent)$/).test(o.containment)) { ce = $(o.containment)[0]; co = $(o.containment).offset(); over = ($(ce).css("overflow") !== "hidden"); this.containment = [ co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top ]; } }, _convertPositionTo: function(d, pos) { if(!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) ) }; }, _generatePosition: function(event) { var top, left, o = this.options, pageX = event.pageX, pageY = event.pageY, scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); // This is another very weird special case that only happens for relative elements: // 1. If the css position is relative // 2. and the scroll parent is the document or similar to the offset parent // we have to refresh the relative offset during the scroll so there are no jumps if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) { this.offset.relative = this._getRelativeOffset(); } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ if(this.originalPosition) { //If we are not dragging yet, we won't check for options if(this.containment) { if(event.pageX - this.offset.click.left < this.containment[0]) { pageX = this.containment[0] + this.offset.click.left; } if(event.pageY - this.offset.click.top < this.containment[1]) { pageY = this.containment[1] + this.offset.click.top; } if(event.pageX - this.offset.click.left > this.containment[2]) { pageX = this.containment[2] + this.offset.click.left; } if(event.pageY - this.offset.click.top > this.containment[3]) { pageY = this.containment[3] + this.offset.click.top; } } if(o.grid) { top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) ) }; }, _rearrange: function(event, i, a, hardRefresh) { a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling)); //Various things done here to improve the performance: // 1. we create a setTimeout, that calls refreshPositions // 2. on the instance, we have a counter variable, that get's higher after every append // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same // 4. this lets only the last addition to the timeout stack through this.counter = this.counter ? ++this.counter : 1; var counter = this.counter; this._delay(function() { if(counter === this.counter) { this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove } }); }, _clear: function(event, noPropagation) { this.reverting = false; // We delay all events that have to be triggered to after the point where the placeholder has been removed and // everything else normalized again var i, delayedTriggers = []; // We first have to update the dom position of the actual currentItem // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088) if(!this._noFinalSort && this.currentItem.parent().length) { this.placeholder.before(this.currentItem); } this._noFinalSort = null; if(this.helper[0] === this.currentItem[0]) { for(i in this._storedCSS) { if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") { this._storedCSS[i] = ""; } } this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } if(this.fromOutside && !noPropagation) { delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); }); } if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) { delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed } // Check if the items Container has Changed and trigger appropriate // events. if (this !== this.currentContainer) { if(!noPropagation) { delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); }); delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); } } //Post events to containers function delayEvent( type, instance, container ) { return function( event ) { container._trigger( type, event, instance._uiHash( instance ) ); }; } for (i = this.containers.length - 1; i >= 0; i--){ if (!noPropagation) { delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) ); } if(this.containers[i].containerCache.over) { delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) ); this.containers[i].containerCache.over = 0; } } //Do what was originally in plugins if ( this.storedCursor ) { this.document.find( "body" ).css( "cursor", this.storedCursor ); this.storedStylesheet.remove(); } if(this._storedOpacity) { this.helper.css("opacity", this._storedOpacity); } if(this._storedZIndex) { this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex); } this.dragging = false; if(this.cancelHelperRemoval) { if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); for (i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); } //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return false; } if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); } //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! this.placeholder[0].parentNode.removeChild(this.placeholder[0]); if(this.helper[0] !== this.currentItem[0]) { this.helper.remove(); } this.helper = null; if(!noPropagation) { for (i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); } //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return true; }, _trigger: function() { if ($.Widget.prototype._trigger.apply(this, arguments) === false) { this.cancel(); } }, _uiHash: function(_inst) { var inst = _inst || this; return { helper: inst.helper, placeholder: inst.placeholder || $([]), position: inst.position, originalPosition: inst.originalPosition, offset: inst.positionAbs, item: inst.currentItem, sender: _inst ? _inst.element : null }; } }); /*! * jQuery UI Spinner 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/spinner/ */ function spinner_modifier( fn ) { return function() { var previous = this.element.val(); fn.apply( this, arguments ); this._refresh(); if ( previous !== this.element.val() ) { this._trigger( "change" ); } }; } var spinner = $.widget( "ui.spinner", { version: "1.11.0", defaultElement: "<input>", widgetEventPrefix: "spin", options: { culture: null, icons: { down: "ui-icon-triangle-1-s", up: "ui-icon-triangle-1-n" }, incremental: true, max: null, min: null, numberFormat: null, page: 10, step: 1, change: null, spin: null, start: null, stop: null }, _create: function() { // handle string values that need to be parsed this._setOption( "max", this.options.max ); this._setOption( "min", this.options.min ); this._setOption( "step", this.options.step ); // Only format if there is a value, prevents the field from being marked // as invalid in Firefox, see #9573. if ( this.value() !== "" ) { // Format the value, but don't constrain. this._value( this.element.val(), true ); } this._draw(); this._on( this._events ); this._refresh(); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _getCreateOptions: function() { var options = {}, element = this.element; $.each( [ "min", "max", "step" ], function( i, option ) { var value = element.attr( option ); if ( value !== undefined && value.length ) { options[ option ] = value; } }); return options; }, _events: { keydown: function( event ) { if ( this._start( event ) && this._keydown( event ) ) { event.preventDefault(); } }, keyup: "_stop", focus: function() { this.previous = this.element.val(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } this._stop(); this._refresh(); if ( this.previous !== this.element.val() ) { this._trigger( "change", event ); } }, mousewheel: function( event, delta ) { if ( !delta ) { return; } if ( !this.spinning && !this._start( event ) ) { return false; } this._spin( (delta > 0 ? 1 : -1) * this.options.step, event ); clearTimeout( this.mousewheelTimer ); this.mousewheelTimer = this._delay(function() { if ( this.spinning ) { this._stop( event ); } }, 100 ); event.preventDefault(); }, "mousedown .ui-spinner-button": function( event ) { var previous; // We never want the buttons to have focus; whenever the user is // interacting with the spinner, the focus should be on the input. // If the input is focused then this.previous is properly set from // when the input first received focus. If the input is not focused // then we need to set this.previous based on the value before spinning. previous = this.element[0] === this.document[0].activeElement ? this.previous : this.element.val(); function checkFocus() { var isActive = this.element[0] === this.document[0].activeElement; if ( !isActive ) { this.element.focus(); this.previous = previous; // support: IE // IE sets focus asynchronously, so we need to check if focus // moved off of the input because the user clicked on the button. this._delay(function() { this.previous = previous; }); } } // ensure focus is on (or stays on) the text field event.preventDefault(); checkFocus.call( this ); // support: IE // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event // and check (again) if focus moved off of the input. this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; checkFocus.call( this ); }); if ( this._start( event ) === false ) { return; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, "mouseup .ui-spinner-button": "_stop", "mouseenter .ui-spinner-button": function( event ) { // button will add ui-state-active if mouse was down while mouseleave and kept down if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) { return; } if ( this._start( event ) === false ) { return false; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, // TODO: do we really want to consider this a stop? // shouldn't we just stop the repeater and wait until mouseup before // we trigger the stop event? "mouseleave .ui-spinner-button": "_stop" }, _draw: function() { var uiSpinner = this.uiSpinner = this.element .addClass( "ui-spinner-input" ) .attr( "autocomplete", "off" ) .wrap( this._uiSpinnerHtml() ) .parent() // add buttons .append( this._buttonHtml() ); this.element.attr( "role", "spinbutton" ); // button bindings this.buttons = uiSpinner.find( ".ui-spinner-button" ) .attr( "tabIndex", -1 ) .button() .removeClass( "ui-corner-all" ); // IE 6 doesn't understand height: 50% for the buttons // unless the wrapper has an explicit height if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) && uiSpinner.height() > 0 ) { uiSpinner.height( uiSpinner.height() ); } // disable spinner if element was already disabled if ( this.options.disabled ) { this.disable(); } }, _keydown: function( event ) { var options = this.options, keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.UP: this._repeat( null, 1, event ); return true; case keyCode.DOWN: this._repeat( null, -1, event ); return true; case keyCode.PAGE_UP: this._repeat( null, options.page, event ); return true; case keyCode.PAGE_DOWN: this._repeat( null, -options.page, event ); return true; } return false; }, _uiSpinnerHtml: function() { return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"; }, _buttonHtml: function() { return "" + "<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" + "<span class='ui-icon " + this.options.icons.up + "'>&#9650;</span>" + "</a>" + "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" + "<span class='ui-icon " + this.options.icons.down + "'>&#9660;</span>" + "</a>"; }, _start: function( event ) { if ( !this.spinning && this._trigger( "start", event ) === false ) { return false; } if ( !this.counter ) { this.counter = 1; } this.spinning = true; return true; }, _repeat: function( i, steps, event ) { i = i || 500; clearTimeout( this.timer ); this.timer = this._delay(function() { this._repeat( 40, steps, event ); }, i ); this._spin( steps * this.options.step, event ); }, _spin: function( step, event ) { var value = this.value() || 0; if ( !this.counter ) { this.counter = 1; } value = this._adjustValue( value + step * this._increment( this.counter ) ); if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) { this._value( value ); this.counter++; } }, _increment: function( i ) { var incremental = this.options.incremental; if ( incremental ) { return $.isFunction( incremental ) ? incremental( i ) : Math.floor( i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1 ); } return 1; }, _precision: function() { var precision = this._precisionOf( this.options.step ); if ( this.options.min !== null ) { precision = Math.max( precision, this._precisionOf( this.options.min ) ); } return precision; }, _precisionOf: function( num ) { var str = num.toString(), decimal = str.indexOf( "." ); return decimal === -1 ? 0 : str.length - decimal - 1; }, _adjustValue: function( value ) { var base, aboveMin, options = this.options; // make sure we're at a valid step // - find out where we are relative to the base (min or 0) base = options.min !== null ? options.min : 0; aboveMin = value - base; // - round to the nearest step aboveMin = Math.round(aboveMin / options.step) * options.step; // - rounding is based on 0, so adjust back to our base value = base + aboveMin; // fix precision from bad JS floating point math value = parseFloat( value.toFixed( this._precision() ) ); // clamp the value if ( options.max !== null && value > options.max) { return options.max; } if ( options.min !== null && value < options.min ) { return options.min; } return value; }, _stop: function( event ) { if ( !this.spinning ) { return; } clearTimeout( this.timer ); clearTimeout( this.mousewheelTimer ); this.counter = 0; this.spinning = false; this._trigger( "stop", event ); }, _setOption: function( key, value ) { if ( key === "culture" || key === "numberFormat" ) { var prevValue = this._parse( this.element.val() ); this.options[ key ] = value; this.element.val( this._format( prevValue ) ); return; } if ( key === "max" || key === "min" || key === "step" ) { if ( typeof value === "string" ) { value = this._parse( value ); } } if ( key === "icons" ) { this.buttons.first().find( ".ui-icon" ) .removeClass( this.options.icons.up ) .addClass( value.up ); this.buttons.last().find( ".ui-icon" ) .removeClass( this.options.icons.down ) .addClass( value.down ); } this._super( key, value ); if ( key === "disabled" ) { this.widget().toggleClass( "ui-state-disabled", !!value ); this.element.prop( "disabled", !!value ); this.buttons.button( value ? "disable" : "enable" ); } }, _setOptions: spinner_modifier(function( options ) { this._super( options ); }), _parse: function( val ) { if ( typeof val === "string" && val !== "" ) { val = window.Globalize && this.options.numberFormat ? Globalize.parseFloat( val, 10, this.options.culture ) : +val; } return val === "" || isNaN( val ) ? null : val; }, _format: function( value ) { if ( value === "" ) { return ""; } return window.Globalize && this.options.numberFormat ? Globalize.format( value, this.options.numberFormat, this.options.culture ) : value; }, _refresh: function() { this.element.attr({ "aria-valuemin": this.options.min, "aria-valuemax": this.options.max, // TODO: what should we do with values that can't be parsed? "aria-valuenow": this._parse( this.element.val() ) }); }, isValid: function() { var value = this.value(); // null is invalid if ( value === null ) { return false; } // if value gets adjusted, it's invalid return value === this._adjustValue( value ); }, // update the value without triggering change _value: function( value, allowAny ) { var parsed; if ( value !== "" ) { parsed = this._parse( value ); if ( parsed !== null ) { if ( !allowAny ) { parsed = this._adjustValue( parsed ); } value = this._format( parsed ); } } this.element.val( value ); this._refresh(); }, _destroy: function() { this.element .removeClass( "ui-spinner-input" ) .prop( "disabled", false ) .removeAttr( "autocomplete" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.uiSpinner.replaceWith( this.element ); }, stepUp: spinner_modifier(function( steps ) { this._stepUp( steps ); }), _stepUp: function( steps ) { if ( this._start() ) { this._spin( (steps || 1) * this.options.step ); this._stop(); } }, stepDown: spinner_modifier(function( steps ) { this._stepDown( steps ); }), _stepDown: function( steps ) { if ( this._start() ) { this._spin( (steps || 1) * -this.options.step ); this._stop(); } }, pageUp: spinner_modifier(function( pages ) { this._stepUp( (pages || 1) * this.options.page ); }), pageDown: spinner_modifier(function( pages ) { this._stepDown( (pages || 1) * this.options.page ); }), value: function( newVal ) { if ( !arguments.length ) { return this._parse( this.element.val() ); } spinner_modifier( this._value ).call( this, newVal ); }, widget: function() { return this.uiSpinner; } }); /*! * jQuery UI Tabs 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/tabs/ */ var tabs = $.widget( "ui.tabs", { version: "1.11.0", delay: 300, options: { active: null, collapsible: false, event: "click", heightStyle: "content", hide: null, show: null, // callbacks activate: null, beforeActivate: null, beforeLoad: null, load: null }, _isLocal: (function() { var rhash = /#.*$/; return function( anchor ) { var anchorUrl, locationUrl; // support: IE7 // IE7 doesn't normalize the href property when set via script (#9317) anchor = anchor.cloneNode( false ); anchorUrl = anchor.href.replace( rhash, "" ); locationUrl = location.href.replace( rhash, "" ); // decoding may throw an error if the URL isn't UTF-8 (#9518) try { anchorUrl = decodeURIComponent( anchorUrl ); } catch ( error ) {} try { locationUrl = decodeURIComponent( locationUrl ); } catch ( error ) {} return anchor.hash.length > 1 && anchorUrl === locationUrl; }; })(), _create: function() { var that = this, options = this.options; this.running = false; this.element .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-tabs-collapsible", options.collapsible ) // Prevent users from focusing disabled tabs via click .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) { if ( $( this ).is( ".ui-state-disabled" ) ) { event.preventDefault(); } }) // support: IE <9 // Preventing the default action in mousedown doesn't prevent IE // from focusing the element, so if the anchor gets focused, blur. // We don't have to worry about focusing the previously focused // element since clicking on a non-focusable element should focus // the body anyway. .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { this.blur(); } }); this._processTabs(); options.active = this._initialActive(); // Take disabling tabs via class attribute from HTML // into account and update option properly. if ( $.isArray( options.disabled ) ) { options.disabled = $.unique( options.disabled.concat( $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { return that.tabs.index( li ); }) ) ).sort(); } // check for length avoids error when initializing empty list if ( this.options.active !== false && this.anchors.length ) { this.active = this._findActive( options.active ); } else { this.active = $(); } this._refresh(); if ( this.active.length ) { this.load( options.active ); } }, _initialActive: function() { var active = this.options.active, collapsible = this.options.collapsible, locationHash = location.hash.substring( 1 ); if ( active === null ) { // check the fragment identifier in the URL if ( locationHash ) { this.tabs.each(function( i, tab ) { if ( $( tab ).attr( "aria-controls" ) === locationHash ) { active = i; return false; } }); } // check for a tab marked active via a class if ( active === null ) { active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); } // no active tab, set to false if ( active === null || active === -1 ) { active = this.tabs.length ? 0 : false; } } // handle numbers: negative, out of range if ( active !== false ) { active = this.tabs.index( this.tabs.eq( active ) ); if ( active === -1 ) { active = collapsible ? false : 0; } } // don't allow collapsible: false and active: false if ( !collapsible && active === false && this.anchors.length ) { active = 0; } return active; }, _getCreateEventData: function() { return { tab: this.active, panel: !this.active.length ? $() : this._getPanelForTab( this.active ) }; }, _tabKeydown: function( event ) { var focusedTab = $( this.document[0].activeElement ).closest( "li" ), selectedIndex = this.tabs.index( focusedTab ), goingForward = true; if ( this._handlePageNav( event ) ) { return; } switch ( event.keyCode ) { case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: selectedIndex++; break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: goingForward = false; selectedIndex--; break; case $.ui.keyCode.END: selectedIndex = this.anchors.length - 1; break; case $.ui.keyCode.HOME: selectedIndex = 0; break; case $.ui.keyCode.SPACE: // Activate only, no collapsing event.preventDefault(); clearTimeout( this.activating ); this._activate( selectedIndex ); return; case $.ui.keyCode.ENTER: // Toggle (cancel delayed activation, allow collapsing) event.preventDefault(); clearTimeout( this.activating ); // Determine if we should collapse or activate this._activate( selectedIndex === this.options.active ? false : selectedIndex ); return; default: return; } // Focus the appropriate tab, based on which key was pressed event.preventDefault(); clearTimeout( this.activating ); selectedIndex = this._focusNextTab( selectedIndex, goingForward ); // Navigating with control key will prevent automatic activation if ( !event.ctrlKey ) { // Update aria-selected immediately so that AT think the tab is already selected. // Otherwise AT may confuse the user by stating that they need to activate the tab, // but the tab will already be activated by the time the announcement finishes. focusedTab.attr( "aria-selected", "false" ); this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); this.activating = this._delay(function() { this.option( "active", selectedIndex ); }, this.delay ); } }, _panelKeydown: function( event ) { if ( this._handlePageNav( event ) ) { return; } // Ctrl+up moves focus to the current tab if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { event.preventDefault(); this.active.focus(); } }, // Alt+page up/down moves focus to the previous/next tab (and activates) _handlePageNav: function( event ) { if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { this._activate( this._focusNextTab( this.options.active - 1, false ) ); return true; } if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { this._activate( this._focusNextTab( this.options.active + 1, true ) ); return true; } }, _findNextTab: function( index, goingForward ) { var lastTabIndex = this.tabs.length - 1; function constrain() { if ( index > lastTabIndex ) { index = 0; } if ( index < 0 ) { index = lastTabIndex; } return index; } while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { index = goingForward ? index + 1 : index - 1; } return index; }, _focusNextTab: function( index, goingForward ) { index = this._findNextTab( index, goingForward ); this.tabs.eq( index ).focus(); return index; }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "disabled" ) { // don't use the widget factory's disabled handling this._setupDisabled( value ); return; } this._super( key, value); if ( key === "collapsible" ) { this.element.toggleClass( "ui-tabs-collapsible", value ); // Setting collapsible: false while collapsed; open first panel if ( !value && this.options.active === false ) { this._activate( 0 ); } } if ( key === "event" ) { this._setupEvents( value ); } if ( key === "heightStyle" ) { this._setupHeightStyle( value ); } }, _sanitizeSelector: function( hash ) { return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; }, refresh: function() { var options = this.options, lis = this.tablist.children( ":has(a[href])" ); // get disabled tabs from class attribute from HTML // this will get converted to a boolean if needed in _refresh() options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { return lis.index( tab ); }); this._processTabs(); // was collapsed or no tabs if ( options.active === false || !this.anchors.length ) { options.active = false; this.active = $(); // was active, but active tab is gone } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { // all remaining tabs are disabled if ( this.tabs.length === options.disabled.length ) { options.active = false; this.active = $(); // activate previous tab } else { this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); } // was active, active tab still exists } else { // make sure active index is correct options.active = this.tabs.index( this.active ); } this._refresh(); }, _refresh: function() { this._setupDisabled( this.options.disabled ); this._setupEvents( this.options.event ); this._setupHeightStyle( this.options.heightStyle ); this.tabs.not( this.active ).attr({ "aria-selected": "false", "aria-expanded": "false", tabIndex: -1 }); this.panels.not( this._getPanelForTab( this.active ) ) .hide() .attr({ "aria-hidden": "true" }); // Make sure one tab is in the tab order if ( !this.active.length ) { this.tabs.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active .addClass( "ui-tabs-active ui-state-active" ) .attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }); this._getPanelForTab( this.active ) .show() .attr({ "aria-hidden": "false" }); } }, _processTabs: function() { var that = this; this.tablist = this._getList() .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .attr( "role", "tablist" ); this.tabs = this.tablist.find( "> li:has(a[href])" ) .addClass( "ui-state-default ui-corner-top" ) .attr({ role: "tab", tabIndex: -1 }); this.anchors = this.tabs.map(function() { return $( "a", this )[ 0 ]; }) .addClass( "ui-tabs-anchor" ) .attr({ role: "presentation", tabIndex: -1 }); this.panels = $(); this.anchors.each(function( i, anchor ) { var selector, panel, panelId, anchorId = $( anchor ).uniqueId().attr( "id" ), tab = $( anchor ).closest( "li" ), originalAriaControls = tab.attr( "aria-controls" ); // inline tab if ( that._isLocal( anchor ) ) { selector = anchor.hash; panelId = selector.substring( 1 ); panel = that.element.find( that._sanitizeSelector( selector ) ); // remote tab } else { // If the tab doesn't already have aria-controls, // generate an id by using a throw-away element panelId = tab.attr( "aria-controls" ) || $( {} ).uniqueId()[ 0 ].id; selector = "#" + panelId; panel = that.element.find( selector ); if ( !panel.length ) { panel = that._createPanel( panelId ); panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); } panel.attr( "aria-live", "polite" ); } if ( panel.length) { that.panels = that.panels.add( panel ); } if ( originalAriaControls ) { tab.data( "ui-tabs-aria-controls", originalAriaControls ); } tab.attr({ "aria-controls": panelId, "aria-labelledby": anchorId }); panel.attr( "aria-labelledby", anchorId ); }); this.panels .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .attr( "role", "tabpanel" ); }, // allow overriding how to find the list for rare usage scenarios (#7715) _getList: function() { return this.tablist || this.element.find( "ol,ul" ).eq( 0 ); }, _createPanel: function( id ) { return $( "<div>" ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); }, _setupDisabled: function( disabled ) { if ( $.isArray( disabled ) ) { if ( !disabled.length ) { disabled = false; } else if ( disabled.length === this.anchors.length ) { disabled = true; } } // disable tabs for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { $( li ) .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } else { $( li ) .removeClass( "ui-state-disabled" ) .removeAttr( "aria-disabled" ); } } this.options.disabled = disabled; }, _setupEvents: function( event ) { var events = {}; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.anchors.add( this.tabs ).add( this.panels ) ); // Always prevent the default action, even when disabled this._on( true, this.anchors, { click: function( event ) { event.preventDefault(); } }); this._on( this.anchors, events ); this._on( this.tabs, { keydown: "_tabKeydown" } ); this._on( this.panels, { keydown: "_panelKeydown" } ); this._focusable( this.tabs ); this._hoverable( this.tabs ); }, _setupHeightStyle: function( heightStyle ) { var maxHeight, parent = this.element.parent(); if ( heightStyle === "fill" ) { maxHeight = parent.height(); maxHeight -= this.element.outerHeight() - this.element.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.element.children().not( this.panels ).each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.panels.each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.panels.each(function() { maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); }).height( maxHeight ); } }, _eventHandler: function( event ) { var options = this.options, active = this.active, anchor = $( event.currentTarget ), tab = anchor.closest( "li" ), clickedIsActive = tab[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : this._getPanelForTab( tab ), toHide = !active.length ? $() : this._getPanelForTab( active ), eventData = { oldTab: active, oldPanel: toHide, newTab: collapsing ? $() : tab, newPanel: toShow }; event.preventDefault(); if ( tab.hasClass( "ui-state-disabled" ) || // tab is already loading tab.hasClass( "ui-tabs-loading" ) || // can't switch durning an animation this.running || // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.tabs.index( tab ); this.active = clickedIsActive ? $() : tab; if ( this.xhr ) { this.xhr.abort(); } if ( !toHide.length && !toShow.length ) { $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); } if ( toShow.length ) { this.load( this.tabs.index( tab ), event ); } this._toggle( event, eventData ); }, // handles show/hide for selecting tabs _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel; this.running = true; function complete() { that.running = false; that._trigger( "activate", event, eventData ); } function show() { eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); if ( toShow.length && that.options.show ) { that._show( toShow, that.options.show, complete ); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && this.options.hide ) { this._hide( toHide, this.options.hide, function() { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); show(); }); } else { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); toHide.hide(); show(); } toHide.attr( "aria-hidden", "true" ); eventData.oldTab.attr({ "aria-selected": "false", "aria-expanded": "false" }); // If we're switching tabs, remove the old tab from the tab order. // If we're opening from collapsed state, remove the previous tab from the tab order. // If we're collapsing, then keep the collapsing tab in the tab order. if ( toShow.length && toHide.length ) { eventData.oldTab.attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.tabs.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow.attr( "aria-hidden", "false" ); eventData.newTab.attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }); }, _activate: function( index ) { var anchor, active = this._findActive( index ); // trying to activate the already active panel if ( active[ 0 ] === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the current active header if ( !active.length ) { active = this.active; } anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; this._eventHandler({ target: anchor, currentTarget: anchor, preventDefault: $.noop }); }, _findActive: function( index ) { return index === false ? $() : this.tabs.eq( index ); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. if ( typeof index === "string" ) { index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); } return index; }, _destroy: function() { if ( this.xhr ) { this.xhr.abort(); } this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); this.tablist .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .removeAttr( "role" ); this.anchors .removeClass( "ui-tabs-anchor" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this.tabs.add( this.panels ).each(function() { if ( $.data( this, "ui-tabs-destroy" ) ) { $( this ).remove(); } else { $( this ) .removeClass( "ui-state-default ui-state-active ui-state-disabled " + "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-live" ) .removeAttr( "aria-busy" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-expanded" ) .removeAttr( "role" ); } }); this.tabs.each(function() { var li = $( this ), prev = li.data( "ui-tabs-aria-controls" ); if ( prev ) { li .attr( "aria-controls", prev ) .removeData( "ui-tabs-aria-controls" ); } else { li.removeAttr( "aria-controls" ); } }); this.panels.show(); if ( this.options.heightStyle !== "content" ) { this.panels.css( "height", "" ); } }, enable: function( index ) { var disabled = this.options.disabled; if ( disabled === false ) { return; } if ( index === undefined ) { disabled = false; } else { index = this._getIndex( index ); if ( $.isArray( disabled ) ) { disabled = $.map( disabled, function( num ) { return num !== index ? num : null; }); } else { disabled = $.map( this.tabs, function( li, num ) { return num !== index ? num : null; }); } } this._setupDisabled( disabled ); }, disable: function( index ) { var disabled = this.options.disabled; if ( disabled === true ) { return; } if ( index === undefined ) { disabled = true; } else { index = this._getIndex( index ); if ( $.inArray( index, disabled ) !== -1 ) { return; } if ( $.isArray( disabled ) ) { disabled = $.merge( [ index ], disabled ).sort(); } else { disabled = [ index ]; } } this._setupDisabled( disabled ); }, load: function( index, event ) { index = this._getIndex( index ); var that = this, tab = this.tabs.eq( index ), anchor = tab.find( ".ui-tabs-anchor" ), panel = this._getPanelForTab( tab ), eventData = { tab: tab, panel: panel }; // not remote if ( this._isLocal( anchor[ 0 ] ) ) { return; } this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); // support: jQuery <1.8 // jQuery <1.8 returns false if the request is canceled in beforeSend, // but as of 1.8, $.ajax() always returns a jqXHR object. if ( this.xhr && this.xhr.statusText !== "canceled" ) { tab.addClass( "ui-tabs-loading" ); panel.attr( "aria-busy", "true" ); this.xhr .success(function( response ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { panel.html( response ); that._trigger( "load", event, eventData ); }, 1 ); }) .complete(function( jqXHR, status ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { if ( status === "abort" ) { that.panels.stop( false, true ); } tab.removeClass( "ui-tabs-loading" ); panel.removeAttr( "aria-busy" ); if ( jqXHR === that.xhr ) { delete that.xhr; } }, 1 ); }); } }, _ajaxSettings: function( anchor, event, eventData ) { var that = this; return { url: anchor.attr( "href" ), beforeSend: function( jqXHR, settings ) { return that._trigger( "beforeLoad", event, $.extend( { jqXHR: jqXHR, ajaxSettings: settings }, eventData ) ); } }; }, _getPanelForTab: function( tab ) { var id = $( tab ).attr( "aria-controls" ); return this.element.find( this._sanitizeSelector( "#" + id ) ); } }); /*! * jQuery UI Tooltip 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/tooltip/ */ var tooltip = $.widget( "ui.tooltip", { version: "1.11.0", options: { content: function() { // support: IE<9, Opera in jQuery <1.7 // .text() can't accept undefined, so coerce to a string var title = $( this ).attr( "title" ) || ""; // Escape title, since we're going from an attribute to raw HTML return $( "<a>" ).text( title ).html(); }, hide: true, // Disabled elements have inconsistent behavior across browsers (#8661) items: "[title]:not([disabled])", position: { my: "left top+15", at: "left bottom", collision: "flipfit flip" }, show: true, tooltipClass: null, track: false, // callbacks close: null, open: null }, _addDescribedBy: function( elem, id ) { var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ); describedby.push( id ); elem .data( "ui-tooltip-id", id ) .attr( "aria-describedby", $.trim( describedby.join( " " ) ) ); }, _removeDescribedBy: function( elem ) { var id = elem.data( "ui-tooltip-id" ), describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ), index = $.inArray( id, describedby ); if ( index !== -1 ) { describedby.splice( index, 1 ); } elem.removeData( "ui-tooltip-id" ); describedby = $.trim( describedby.join( " " ) ); if ( describedby ) { elem.attr( "aria-describedby", describedby ); } else { elem.removeAttr( "aria-describedby" ); } }, _create: function() { this._on({ mouseover: "open", focusin: "open" }); // IDs of generated tooltips, needed for destroy this.tooltips = {}; // IDs of parent tooltips where we removed the title attribute this.parents = {}; if ( this.options.disabled ) { this._disable(); } // Append the aria-live region so tooltips announce correctly this.liveRegion = $( "<div>" ) .attr({ role: "log", "aria-live": "assertive", "aria-relevant": "additions" }) .addClass( "ui-helper-hidden-accessible" ) .appendTo( this.document[ 0 ].body ); }, _setOption: function( key, value ) { var that = this; if ( key === "disabled" ) { this[ value ? "_disable" : "_enable" ](); this.options[ key ] = value; // disable element style changes return; } this._super( key, value ); if ( key === "content" ) { $.each( this.tooltips, function( id, element ) { that._updateContent( element ); }); } }, _disable: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { var event = $.Event( "blur" ); event.target = event.currentTarget = element[0]; that.close( event, true ); }); // remove title attributes to prevent native tooltips this.element.find( this.options.items ).addBack().each(function() { var element = $( this ); if ( element.is( "[title]" ) ) { element .data( "ui-tooltip-title", element.attr( "title" ) ) .removeAttr( "title" ); } }); }, _enable: function() { // restore title attributes this.element.find( this.options.items ).addBack().each(function() { var element = $( this ); if ( element.data( "ui-tooltip-title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); } }); }, open: function( event ) { var that = this, target = $( event ? event.target : this.element ) // we need closest here due to mouseover bubbling, // but always pointing at the same event target .closest( this.options.items ); // No element to show a tooltip for or the tooltip is already open if ( !target.length || target.data( "ui-tooltip-id" ) ) { return; } if ( target.attr( "title" ) ) { target.data( "ui-tooltip-title", target.attr( "title" ) ); } target.data( "ui-tooltip-open", true ); // kill parent tooltips, custom or native, for hover if ( event && event.type === "mouseover" ) { target.parents().each(function() { var parent = $( this ), blurEvent; if ( parent.data( "ui-tooltip-open" ) ) { blurEvent = $.Event( "blur" ); blurEvent.target = blurEvent.currentTarget = this; that.close( blurEvent, true ); } if ( parent.attr( "title" ) ) { parent.uniqueId(); that.parents[ this.id ] = { element: this, title: parent.attr( "title" ) }; parent.attr( "title", "" ); } }); } this._updateContent( target, event ); }, _updateContent: function( target, event ) { var content, contentOption = this.options.content, that = this, eventType = event ? event.type : null; if ( typeof contentOption === "string" ) { return this._open( event, target, contentOption ); } content = contentOption.call( target[0], function( response ) { // ignore async response if tooltip was closed already if ( !target.data( "ui-tooltip-open" ) ) { return; } // IE may instantly serve a cached response for ajax requests // delay this call to _open so the other call to _open runs first that._delay(function() { // jQuery creates a special event for focusin when it doesn't // exist natively. To improve performance, the native event // object is reused and the type is changed. Therefore, we can't // rely on the type being correct after the event finished // bubbling, so we set it back to the previous value. (#8740) if ( event ) { event.type = eventType; } this._open( event, target, response ); }); }); if ( content ) { this._open( event, target, content ); } }, _open: function( event, target, content ) { var tooltip, events, delayedShow, a11yContent, positionOption = $.extend( {}, this.options.position ); if ( !content ) { return; } // Content can be updated multiple times. If the tooltip already // exists, then just update the content and bail. tooltip = this._find( target ); if ( tooltip.length ) { tooltip.find( ".ui-tooltip-content" ).html( content ); return; } // if we have a title, clear it to prevent the native tooltip // we have to check first to avoid defining a title if none exists // (we don't want to cause an element to start matching [title]) // // We use removeAttr only for key events, to allow IE to export the correct // accessible attributes. For mouse events, set to empty string to avoid // native tooltip showing up (happens only when removing inside mouseover). if ( target.is( "[title]" ) ) { if ( event && event.type === "mouseover" ) { target.attr( "title", "" ); } else { target.removeAttr( "title" ); } } tooltip = this._tooltip( target ); this._addDescribedBy( target, tooltip.attr( "id" ) ); tooltip.find( ".ui-tooltip-content" ).html( content ); // Support: Voiceover on OS X, JAWS on IE <= 9 // JAWS announces deletions even when aria-relevant="additions" // Voiceover will sometimes re-read the entire log region's contents from the beginning this.liveRegion.children().hide(); if ( content.clone ) { a11yContent = content.clone(); a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" ); } else { a11yContent = content; } $( "<div>" ).html( a11yContent ).appendTo( this.liveRegion ); function position( event ) { positionOption.of = event; if ( tooltip.is( ":hidden" ) ) { return; } tooltip.position( positionOption ); } if ( this.options.track && event && /^mouse/.test( event.type ) ) { this._on( this.document, { mousemove: position }); // trigger once to override element-relative positioning position( event ); } else { tooltip.position( $.extend({ of: target }, this.options.position ) ); } tooltip.hide(); this._show( tooltip, this.options.show ); // Handle tracking tooltips that are shown with a delay (#8644). As soon // as the tooltip is visible, position the tooltip using the most recent // event. if ( this.options.show && this.options.show.delay ) { delayedShow = this.delayedShow = setInterval(function() { if ( tooltip.is( ":visible" ) ) { position( positionOption.of ); clearInterval( delayedShow ); } }, $.fx.interval ); } this._trigger( "open", event, { tooltip: tooltip } ); events = { keyup: function( event ) { if ( event.keyCode === $.ui.keyCode.ESCAPE ) { var fakeEvent = $.Event(event); fakeEvent.currentTarget = target[0]; this.close( fakeEvent, true ); } } }; // Only bind remove handler for delegated targets. Non-delegated // tooltips will handle this in destroy. if ( target[ 0 ] !== this.element[ 0 ] ) { events.remove = function() { this._removeTooltip( tooltip ); }; } if ( !event || event.type === "mouseover" ) { events.mouseleave = "close"; } if ( !event || event.type === "focusin" ) { events.focusout = "close"; } this._on( true, target, events ); }, close: function( event ) { var that = this, target = $( event ? event.currentTarget : this.element ), tooltip = this._find( target ); // disabling closes the tooltip, so we need to track when we're closing // to avoid an infinite loop in case the tooltip becomes disabled on close if ( this.closing ) { return; } // Clear the interval for delayed tracking tooltips clearInterval( this.delayedShow ); // only set title if we had one before (see comment in _open()) // If the title attribute has changed since open(), don't restore if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) { target.attr( "title", target.data( "ui-tooltip-title" ) ); } this._removeDescribedBy( target ); tooltip.stop( true ); this._hide( tooltip, this.options.hide, function() { that._removeTooltip( $( this ) ); }); target.removeData( "ui-tooltip-open" ); this._off( target, "mouseleave focusout keyup" ); // Remove 'remove' binding only on delegated targets if ( target[ 0 ] !== this.element[ 0 ] ) { this._off( target, "remove" ); } this._off( this.document, "mousemove" ); if ( event && event.type === "mouseleave" ) { $.each( this.parents, function( id, parent ) { $( parent.element ).attr( "title", parent.title ); delete that.parents[ id ]; }); } this.closing = true; this._trigger( "close", event, { tooltip: tooltip } ); this.closing = false; }, _tooltip: function( element ) { var tooltip = $( "<div>" ) .attr( "role", "tooltip" ) .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " + ( this.options.tooltipClass || "" ) ), id = tooltip.uniqueId().attr( "id" ); $( "<div>" ) .addClass( "ui-tooltip-content" ) .appendTo( tooltip ); tooltip.appendTo( this.document[0].body ); this.tooltips[ id ] = element; return tooltip; }, _find: function( target ) { var id = target.data( "ui-tooltip-id" ); return id ? $( "#" + id ) : $(); }, _removeTooltip: function( tooltip ) { tooltip.remove(); delete this.tooltips[ tooltip.attr( "id" ) ]; }, _destroy: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { // Delegate to close method to handle common cleanup var event = $.Event( "blur" ); event.target = event.currentTarget = element[0]; that.close( event, true ); // Remove immediately; destroying an open tooltip doesn't use the // hide animation $( "#" + id ).remove(); // Restore the title if ( element.data( "ui-tooltip-title" ) ) { // If the title attribute has changed since open(), don't restore if ( !element.attr( "title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); } element.removeData( "ui-tooltip-title" ); } }); this.liveRegion.remove(); } }); }));
{ "content_hash": "d96be95dd48ad7409c9c329943adfd54", "timestamp": "", "source": "github", "line_count": 16147, "max_line_length": 315, "avg_line_length": 28.53204929708305, "alnum_prop": 0.6166261854063428, "repo_name": "darthluzifer/citeapp", "id": "2b653229bd6c08452a1c089c3df9d8ecda2c234e", "size": "461388", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "autocomplete/jquery_ui.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "43860" }, { "name": "JavaScript", "bytes": "1110083" }, { "name": "PHP", "bytes": "69780" } ], "symlink_target": "" }
<?php namespace App\Http\Controllers\Auth; use Session; use Validator; use App\Models\User; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\AuthenticatesUsers; class AuthController extends Controller { /* |-------------------------------------------------------------------------- | Registration & Login Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users, as well as the | authentication of existing users. By default, this controller uses | a simple trait to add these behaviors. Why don't you explore it? | */ use AuthenticatesUsers, ThrottlesLogins; protected $redirectAfterLogout = 'auth/login'; protected $redirectTo = 'admin/post'; /** * Create a new authentication controller instance. * * @return void */ public function __construct() { $this->middleware('guest', ['except' => 'getLogout']); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|confirmed|min:6', ]); } /** * Create a new user instance after a valid registration. * * @param array $data * @return User */ protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); } public function authenticated(\Illuminate\Http\Request $request, User $user) { Session::set('_login', trans('messages.login', ['first_name' => $user->first_name, 'last_name' => $user->last_name])); return redirect()->intended($this->redirectPath()); } }
{ "content_hash": "6068297d4201133e056a1e6fe8e587f7", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 126, "avg_line_length": 28.25, "alnum_prop": 0.5654401490451794, "repo_name": "nticaric/Canvas", "id": "4522366ef5535ffa5ae4d2a855a43395a8662f11", "size": "2147", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Http/Controllers/Auth/AuthController.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "PHP", "bytes": "196693" } ], "symlink_target": "" }
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>de.hpi.fgis</groupId> <artifactId>tpch-task_java8</artifactId> <version>0.0.1-SNAPSHOT</version> <name>tpch-task_java8</name> <description>Example-Spark-Job solving one TPC-H query</description> <dependencies> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-core_2.10</artifactId> <version>1.3.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> </project>
{ "content_hash": "be37c95c12226eac848553c68d37319e", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 204, "avg_line_length": 34.56666666666667, "alnum_prop": 0.6595949855351977, "repo_name": "DBDA15/hands-on", "id": "108e688eb2e39b9c0706ecc5a8d3f5bddc9d8f99", "size": "1037", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spark/tpch-task_java8/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "32345" }, { "name": "Scala", "bytes": "5176" }, { "name": "Shell", "bytes": "244" } ], "symlink_target": "" }
using namespace Ogre; // use the Ogre namespace using namespace std; // use the Standard C namespace #include <OgreAL.h> // OgreAL class definition #include <OgreStringConverter.h> // OgreStringConverter class definition #include <OIS/OISEvents.h> // OISEvents class definition #include <OIS/OISInputManager.h> // OISInputManager class definition #include <OIS/OISKeyboard.h> // OISKeyboard class definition #include "Ball.h" // Ball class definition #include "Paddle.h" // Paddle class definition #include "Pong.h" // Pong class definition int Pong::player1Score = 0; // initialize player 1's score to 0 int Pong::player2Score = 0; // initialize player 2's score to 0 bool Pong::wait = false; // initialize wait to false // directions to move the Paddles const Vector3 PADDLE_DOWN = Vector3( 0, -15, 0 ); const Vector3 PADDLE_UP = Vector3( 0, 15, 0 ); // constructor Pong::Pong() { #ifdef _DEBUG rootPtr = new Root("Plugins_d.cfg"); // initialize Root object #else rootPtr = new Root("Plugins.cfg"); // initialize Root object #endif // use the Ogre Config Dialog Box to choose the settings if ( !( rootPtr->showConfigDialog() ) ) // user canceled the dialog box throw runtime_error( "User Canceled Ogre Setup Dialog Box." ); // get a pointer to the RenderWindow windowPtr = rootPtr->initialise( true, "Pong" ); // create the SceneManager sceneManagerPtr = rootPtr->createSceneManager( ST_GENERIC ); // create the Camera cameraPtr = sceneManagerPtr->createCamera( "PongCamera" ); cameraPtr->setPosition( Vector3( 0, 0, 200 ) ); // set Camera position cameraPtr->lookAt( Vector3( 0, 0, 0 ) ); // set where Camera looks cameraPtr->setNearClipDistance( 5 ); // near distance Camera can see cameraPtr->setFarClipDistance( 1000 ); // far distance Camera can see // create the Viewport viewportPtr = windowPtr->addViewport( cameraPtr ); viewportPtr->setBackgroundColour( ColourValue( 0, 0, 0 ) ); // set the Camera's aspect ratio cameraPtr->setAspectRatio( Real( viewportPtr->getActualWidth() ) / ( viewportPtr->getActualHeight() ) ); // set the scene's ambient light sceneManagerPtr->setAmbientLight( ColourValue( 0.75, 0.75, 0.75 ) ); // create the Light Light *lightPtr = sceneManagerPtr->createLight( "Light" ); // a Light lightPtr->setPosition( 0, 0, 50 ); // set the Light's position unsigned long hWnd; // variable to hold the window handle windowPtr->getCustomAttribute( "WINDOW", &hWnd ); // get window handle OIS::ParamList paramList; // create an OIS ParamList // add the window to the ParamList paramList.insert( OIS::ParamList::value_type( "WINDOW", Ogre::StringConverter::toString( hWnd ) ) ); // create the InputManager inputManagerPtr = OIS::InputManager::createInputSystem( paramList ); keyboardPtr = static_cast< OIS::Keyboard* >( inputManagerPtr-> createInputObject( OIS::OISKeyboard, true ) ); // create a Keyboard keyboardPtr->setEventCallback( this ); // add a KeyListener rootPtr->addFrameListener( this ); // add this Pong as a FrameListener // load resources for Pong ResourceGroupManager::getSingleton().addResourceLocation( "resources", "FileSystem", "Pong" ); ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); quit = pause = false; // player has not quit or paused the game time = 0; // initialize the time since Ball was reset to 0 } // end Pong constructor // Pong destructor erases objects contained in a Pong object Pong::~Pong() { // free dynamically allocated memory for Keyboard inputManagerPtr->destroyInputObject( keyboardPtr ); OIS::InputManager::destroyInputSystem( inputManagerPtr ); // free dynamically allocated memory for Root delete rootPtr; // release memory pointer points to rootPtr = 0; // point pointer at 0 // free dynamically allocated memory for Ball delete ballPtr; // release memory pointer points to ballPtr = 0; // point pointer at 0 // free dynamically allocated memory for Paddle delete leftPaddlePtr; // release memory pointer points to leftPaddlePtr = 0; // point pointer at 0 // free dynamically allocated memory for Paddle delete rightPaddlePtr; // release memory pointer points to rightPaddlePtr = 0; // point pointer at 0 } // end Pong destructor // create the scene to be displayed void Pong::createScene() { // get a pointer to the Score Overlay Overlay *scoreOverlayPtr = OverlayManager::getSingleton().getByName( "Score" ); scoreOverlayPtr->show(); // show the Overlay // make the game objects ballPtr = new Ball( sceneManagerPtr ); // make the Ball ballPtr->addToScene(); // add the Ball to the scene rightPaddlePtr = new Paddle( sceneManagerPtr, "RightPaddle", 90 ); rightPaddlePtr->addToScene(); // add a Paddle to the scene leftPaddlePtr = new Paddle( sceneManagerPtr, "LeftPaddle", -90 ); leftPaddlePtr->addToScene(); // add a Paddle to the scene // create the walls Entity *entityPtr = sceneManagerPtr-> createEntity( "WallLeft", "cube.mesh" ); // create the left wall entityPtr->setMaterialName( "wall" ); // set material for left wall entityPtr->setNormaliseNormals( true ); // fix the normals when scaled // create the SceneNode for the left wall SceneNode *nodePtr = sceneManagerPtr->getRootSceneNode()-> createChildSceneNode( "WallLeft" ); nodePtr->attachObject( entityPtr ); // attach left wall to SceneNode nodePtr->setPosition( -95, 0, 0 ); // set the left wall's position nodePtr->setScale( .05, 1.45, .1 ); // set the left wall's size entityPtr = sceneManagerPtr->createEntity( "WallRight", "cube.mesh" ); entityPtr->setMaterialName( "wall" ); // set material for right wall entityPtr->setNormaliseNormals( true ); // fix the normals when scaled // create the SceneNode for the right wall nodePtr = sceneManagerPtr->getRootSceneNode()-> createChildSceneNode( "WallRight" ); nodePtr->attachObject( entityPtr ); // attach right wall to SceneNode nodePtr->setPosition( 95, 0, 0 ); // set the right wall's position nodePtr->setScale( .05, 1.45, .1 ); // set the right wall's size entityPtr = sceneManagerPtr->createEntity( "WallBottom", "cube.mesh" ); entityPtr->setMaterialName( "wall" ); // set material for bottom wall entityPtr->setNormaliseNormals( true ); // fix the normals when scaled // create the SceneNode for the bottom wall nodePtr = sceneManagerPtr->getRootSceneNode()-> createChildSceneNode( "WallBottom" ); nodePtr->attachObject( entityPtr ); // attach bottom wall to SceneNode nodePtr->setPosition( 0, -70, 0 ); // set the bottom wall's position nodePtr->setScale( 1.95, .05, .1 ); // set bottom wall's size entityPtr = sceneManagerPtr->createEntity( "WallTop", "cube.mesh" ); entityPtr->setMaterialName( "wall" ); // set the material for wall entityPtr->setNormaliseNormals( true ); // fix the normals when scaled // create the SceneNode for the top wall nodePtr = sceneManagerPtr->getRootSceneNode()-> createChildSceneNode( "WallTop" ); nodePtr->attachObject( entityPtr ); // attach top wall to SceneNode nodePtr->setPosition( 0, 70, 0 ); // set the top wall's position nodePtr->setScale( 1.95, .05, .1 ); // set the top wall's size } // end function createScene // start a game of Pong void Pong::run() { createScene(); // create the scene rootPtr->startRendering(); // start rendering frames } // end function run // update the score void Pong::updateScore( Players player ) { // increase the correct player's score if ( player == Players::PLAYER1 ) player1Score++; else player2Score++; wait = true; // the game should wait to restart the Ball updateScoreText(); // update the score text on the screen } // end function updateScore // update the score text void Pong::updateScoreText() { ostringstream scoreText; // text to be displayed scoreText << "P2: " << player2Score; // make the text // get the right player's TextArea OverlayElement *textElementPtr = OverlayManager::getSingletonPtr()->getOverlayElement( "right" ); textElementPtr->setCaption( scoreText.str() ); // set the text scoreText.str( "" ); // reset the text in scoreText scoreText << "P1: " << player1Score; // make the text // get the left player's TextArea textElementPtr = OverlayManager::getSingletonPtr()->getOverlayElement( "left" ); textElementPtr->setCaption( scoreText.str() ); // set the text } // end function updateScoreText // respond to user keyboard input bool Pong::keyPressed( const OIS::KeyEvent &keyEventRef ) { // if the game is not paused if ( !pause ) { // process KeyEvents that apply when the game is not paused switch ( keyEventRef.key ) { case OIS::KC_ESCAPE: // escape key hit: quit quit = true; break; case OIS::KC_UP: // up-arrow key hit: move the right Paddle up rightPaddlePtr->movePaddle( PADDLE_UP ); break; case OIS::KC_DOWN: // down-arrow key hit: move the right Paddle down rightPaddlePtr->movePaddle( PADDLE_DOWN ); break; case OIS::KC_A: // A key hit: move left Paddle up leftPaddlePtr->movePaddle( PADDLE_UP ); break; case OIS::KC_Z: // Z key hit: move left Paddle down leftPaddlePtr->movePaddle( PADDLE_DOWN ); break; case OIS::KC_P: // P key hit: pause the game pause = true; // set pause to true when the user pauses the game Overlay *pauseOverlayPtr = OverlayManager::getSingleton().getByName( "PauseOverlay" ); pauseOverlayPtr->show(); // show the pause Overlay break; } // end switch } // end if else // game is paused { // user hit 'R' on the keyboard if ( keyEventRef.key == OIS::KC_R ) { pause = false; // set pause to false when user resumes the game Overlay *pauseOverlayPtr = OverlayManager::getSingleton().getByName( "PauseOverlay" ); pauseOverlayPtr->hide(); // hide the pause Overlay } // end if } // end else return true; } // end function keyPressed // process key released events bool Pong::keyReleased( const OIS::KeyEvent &keyEventRef ) { return true; } // end function keyReleased // return true if the program should render the next frame bool Pong::frameEnded( const FrameEvent &frameEvent ) { return !quit; // quit = false if the user hasn't quit yet } // end function frameEnded // process game logic, return true if the next frame should be rendered bool Pong::frameStarted( const FrameEvent &frameEvent ) { keyboardPtr->capture(); // get keyboard events // the game is not paused and the Ball should move if ( !wait && !pause ) { // move the Ball ballPtr->moveBall( frameEvent.timeSinceLastFrame ); } // end if // don't move the Ball if wait is true else if ( wait ) { // increase time if it is less than 4 seconds if ( time < 4 ) // add the seconds since the last frame time += frameEvent.timeSinceLastFrame; else { wait = false; // shouldn't wait to move the Ball any more time = 0; // reset the control variable to 0 } // end else } // end else return !quit; // quit = false if the user hasn't quit yet } // end function frameStarted
{ "content_hash": "d6aa4c66f339ef8d860f34509b86890b", "timestamp": "", "source": "github", "line_count": 298, "max_line_length": 74, "avg_line_length": 38.506711409395976, "alnum_prop": 0.6795642701525054, "repo_name": "Neo-Desktop/Coleman-Code", "id": "0bfbba2bf6ff50cdff6e986029f9aceca4914d8d", "size": "11613", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "COM203/2013-05/Ogre Project - 77260/Ogre Project/Pong.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "18356" }, { "name": "Assembly", "bytes": "747" }, { "name": "Batchfile", "bytes": "1794" }, { "name": "C", "bytes": "123387" }, { "name": "C#", "bytes": "179078" }, { "name": "C++", "bytes": "652938" }, { "name": "CSS", "bytes": "84264" }, { "name": "HTML", "bytes": "35458" }, { "name": "Java", "bytes": "252330" }, { "name": "JavaScript", "bytes": "3171" }, { "name": "Objective-C", "bytes": "472" }, { "name": "PHP", "bytes": "54" }, { "name": "Perl", "bytes": "21921" }, { "name": "Shell", "bytes": "3906" }, { "name": "Visual Basic", "bytes": "186480" } ], "symlink_target": "" }
package edu.utah.ece.async.ibiosim.analysis.simulation; import java.io.IOException; import javax.xml.stream.XMLStreamException; import edu.utah.ece.async.ibiosim.analysis.properties.AnalysisProperties; import edu.utah.ece.async.ibiosim.analysis.properties.SimulationProperties; import edu.utah.ece.async.ibiosim.analysis.simulation.flattened.SimulatorODERK; import edu.utah.ece.async.ibiosim.analysis.simulation.flattened.SimulatorSSACR; import edu.utah.ece.async.ibiosim.analysis.simulation.flattened.SimulatorSSADirect; import edu.utah.ece.async.ibiosim.analysis.simulation.hierarchical.methods.HierarchicalMixedSimulator; import edu.utah.ece.async.ibiosim.analysis.simulation.hierarchical.methods.HierarchicalODERKSimulator; import edu.utah.ece.async.ibiosim.analysis.simulation.hierarchical.methods.HierarchicalSSADirectSimulator; import edu.utah.ece.async.ibiosim.dataModels.util.Message; import edu.utah.ece.async.ibiosim.dataModels.util.exceptions.BioSimException; import edu.utah.ece.async.ibiosim.dataModels.util.observe.CoreObservable; /** * Used to run a simulation method. * * @author Leandro Watanabe * @author Chris Myers * @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a> * @version %I% */ public class DynamicSimulation extends CoreObservable { // simulator type private final SimulationType simulatorType; private final Message message; // the simulator object private AbstractSimulator simulator; private boolean cancelFlag; private boolean statisticsFlag; public static enum SimulationType { CR, DIRECT, RK, HIERARCHICAL_DIRECT, HIERARCHICAL_HYBRID, HIERARCHICAL_RK, HIERARCHICAL_MIXED; } /** * Constructs a dynamic simulation object. */ public DynamicSimulation(SimulationType type) { simulatorType = type; message = new Message(); } /** * Runs simulation using the given analysis properties. * * @param properties * - specifies the configurations to setup simulation. * @param filename * - the model to simulate. */ public void simulate(AnalysisProperties properties, String filename) { SimulationProperties simProperties = properties.getSimulationProperties(); try { String SBMLFileName = filename, outputDirectory = properties.getOutDir().equals(".") ? properties.getDirectory() : properties.getOutDir(); properties.getRoot(); String quantityType = simProperties.getPrinter_track_quantity(); double timeLimit = simProperties.getTimeLimit(), maxTimeStep = simProperties.getMaxTimeStep(), minTimeStep = simProperties.getMinTimeStep(), printInterval = simProperties.getPrintInterval(), stoichAmpValue = properties.getAdvancedProperties().getStoichAmp(); simProperties.getOutputStartTime(); double absError = simProperties.getAbsError(), relError = simProperties.getRelError(); simProperties.getInitialTime(); long randomSeed = simProperties.getRndSeed(); String[] interestingSpecies = simProperties.getIntSpecies().toArray(new String[simProperties.getIntSpecies().size()]); int runs = simProperties.getRun(), numSteps = simProperties.getNumSteps(); if (numSteps == 0) { numSteps = (int) (timeLimit / printInterval); } switch (simulatorType) { case RK: simulator = new SimulatorODERK(SBMLFileName, outputDirectory, runs, timeLimit, maxTimeStep, randomSeed, printInterval, stoichAmpValue, interestingSpecies, numSteps, relError, absError, quantityType); simulator.addObservable(this); break; case CR: simulator = new SimulatorSSACR(SBMLFileName, outputDirectory, runs, timeLimit, maxTimeStep, minTimeStep, randomSeed, printInterval, stoichAmpValue, interestingSpecies, quantityType); simulator.addObservable(this); break; case DIRECT: simulator = new SimulatorSSADirect(SBMLFileName, outputDirectory, runs, timeLimit, maxTimeStep, minTimeStep, randomSeed, printInterval, stoichAmpValue, interestingSpecies, quantityType); simulator.addObservable(this); break; case HIERARCHICAL_DIRECT: simulator = new HierarchicalSSADirectSimulator(properties); simulator.addObservable(this); break; case HIERARCHICAL_RK: simulator = new HierarchicalODERKSimulator(properties); simulator.addObservable(this); break; case HIERARCHICAL_HYBRID: break; case HIERARCHICAL_MIXED: simulator = new HierarchicalMixedSimulator(properties); simulator.addObservable(this); break; default: message.setLog("The simulation selection was invalid."); notifyObservers(message); return; } for (int run = 1; run <= runs; ++run) { if (cancelFlag == true) { break; } if (simulator != null) { simulator.simulate(); if ((runs - run) >= 1) { simulator.setupForNewRun(run + 1); } } if (cancelFlag == false && statisticsFlag == true) { if (simulator != null) { simulator.printStatisticsTSD(); } } } } catch (IOException e) { e.printStackTrace(); return; } catch (XMLStreamException e) { e.printStackTrace(); return; } catch (BioSimException e) { e.printStackTrace(); return; } } /** * Cancels the simulation on the next iteration called from outside the * class when the user closes the progress bar dialog */ public void cancel() { if (simulator != null) { simulator.cancel(); cancelFlag = true; message.setCancel(); notifyObservers(message); } } @Override public boolean send(RequestType type, Message message) { if (parent != null) { return parent.send(type, message); } return true; } }
{ "content_hash": "527338c2f0af03206fd404bff4947c90", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 264, "avg_line_length": 36.714285714285715, "alnum_prop": 0.7019116900693622, "repo_name": "MyersResearchGroup/iBioSim", "id": "bc73862eeb7243a58eaebd0a9df988b2da5db521", "size": "6568", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "analysis/src/main/java/edu/utah/ece/async/ibiosim/analysis/simulation/DynamicSimulation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "47356" }, { "name": "Batchfile", "bytes": "791" }, { "name": "Dockerfile", "bytes": "1274" }, { "name": "GAP", "bytes": "107727" }, { "name": "Java", "bytes": "9683199" }, { "name": "Perl", "bytes": "52804" }, { "name": "Shell", "bytes": "3226" }, { "name": "Verilog", "bytes": "37331" } ], "symlink_target": "" }
While we certainly have been busy getting our [hands dirty](http://www.wintellect.com/devcenter/tag/xamarin) with Xamarin I've been doing some of my own. However, I've been messing around with using Xamarin with F#. I mentioned in a previous post that F# can be used very well for [enterprise applications](http://www.wintellect.com/devcenter/jwood/using-f-for-enterprise-applications). Here's an in depth look at F# with Xamarin for mobile applications. But why F# with Xamarin, you ask? Well, it just turns out that I love working with both of these technologies and I got lucky that the awesome folks at Xamarin and [Dave Thomas](http://7sharpnine.com/) - who does most of the great work with F# for Xamarin - decided to take on F# as a [first class language](http://developer.xamarin.com/guides/cross-platform/fsharp/). > Before we get started, it's helpful to remember that, in F#, if you reference any other part of your code, whether it's in the same file or not, the part you are referencing needs to be defined *before* you reference it. More info can be found at the wonderful [F# for Fun and Profit](http://fsharpforfunandprofit.com/posts/cyclic-dependencies/) site. Currently in Xamarin (at the time of this writing - version 5.9) there aren't any actual Xamarin Forms or PCL templates. Though, it is rumored there will be more templates in 6.0. ![Available F# Projects](https://dl.dropboxusercontent.com/s/mxdnb6gfnxbhbs0/FSharp-Solution.jpg?dl=0) ### Using Xamarin Forms Larry O'Brien already has a fantastic [tutorial](http://www.knowing.net/index.php/2014/08/27/xamarin-forms-programming-in-f/) on how to use Xamarin Forms in an F# iOS or Android project. Though, I did notice that I didn't have to bring in the `FSharp.Core Mono delay signed` NuGet package as F# is already included with Xamarin Studio. I just needed to bring in `Xamarin.Forms` from NuGet and add the following references from the Mono library as the post also describes: - System.ObjectModel.dll - System.Runtime.dll After you have all that, you're ready to roll with Xamarin Forms in F#. To help understand a bit more of combining F# with Xamarin I ported the Phoneword application that we work with quite a bit in [Xamarin University](https://xamarin.com/university) to F#. The results are the same if it was a C# project. This fairly simple app takes in a phone number and, if the number includes any letters, it translates the letters into the appropriate numbers and allows you to call that number. ### Adding an F# PCL Unfortunately, one of the things Xamarin Studio isn't able to do yet (again, it's definitely being worked on and will be out fairly soon) is the ability to add an F# Portable Class Library to the project. To do this you'll have to open the solution up in Visual Studio and add it through there. ![F# PCL in Visual Studio](https://dl.dropboxusercontent.com/s/91wpconrqy7oh83/FSharpPCL.jpg?dl=0) >At this time, there seems to be an issue of opening this in Xamarin Studio (currently already being fixed), so I'll continue using Visual Studio throughout the rest of this post. For the most part I followed Larry O'Brien's example from above. However, I did separate out the Xamarin Forms stuff from the `AppDelegate` file into the PCL project. With the very generous help from [Dave Thomas](http://7sharpnine.com/), we were able to get a running sample all in F# and Xamarin Forms. Here is the full Xamarin Forms code in F#. ```fsharp [<Extension>] type IListExtensions () = [<Extension>] static member inline AddRange(xs:'a IList, range) = range |> Seq.iter xs.Add type IOpenUrlService = abstract member OpenUrl: string -> bool type MainPage() = static member GetMainPage() = let contentPage = ContentPage(Padding = Thickness(20., Device.OnPlatform(40., 20., 20.), 20., 20.)) let panel = StackLayout(VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, Orientation = StackOrientation.Vertical, Spacing = 15.) let phoneNumberText = Entry(Text = "1-855-XAMARIN") let translateButton = Button(Text = "Translate") let callButton = Button(Text = "Call", IsEnabled = false) translateButton.Clicked.Add(fun _ -> callButton.Text <- PhoneTranslator.toNumber phoneNumberText.Text callButton.IsEnabled <- true) callButton.Clicked.Add(fun _ -> let isCalling = contentPage.DisplayAlert("Dial a number", "Would you like to call " + phoneNumberText.Text, "Yes", "No").Result if isCalling then let dialer = DependencyService.Get<IOpenUrlService>() dialer.OpenUrl phoneNumberText.Text |> ignore) panel.Children.AddRange([Label(Text = "Enter a Phoneword:") phoneNumberText translateButton callButton]) contentPage.Content <- panel contentPage type App() = inherit Application(MainPage = MainPage.GetMainPage()) ``` The `type IOpenUrlService` there is to create our interface so we can use shared code in our Xamarin Forms page and implement it separately in each platform specific project. You may notice we call this lower down and use Xamarin Forms dependency service locator. Also the `string -> bool` statement there simply states that the `OpenUrl` method takes in a `string` parameter and the return type is `bool`. Very similar to C#'s `Func` type where the last type in the signature represents the return type. ```fsharp DependencyService.Get<IOpenUrlService>() dialer.OpenUrl phoneNumberText.Text |> ignore ``` > Note that we pipe into the built-in F# function `ignore` since we don't need to do anything with the return type of `dialer.OpenUrl` at this point. We also have to actually add our `App` that our `MainPage` will be set to. Surprisingly, this is very simple and concise. So much so that, you may have noticed, that it was just added to the end of our file that contains the `MainPage`. ```fsharp type App() = inherit Application(MainPage = MainPage.GetMainPage) ``` As you can see, we can use Xamarin Forms just like we would use them in C#. #### iOS And in our `AppDelegate` for iOS we can do the same as if we were in a C# project. ```fsharp [<assembly: Dependency(typeof<OpenUrlService>)>] do () [<Register("AppDelegate")>] type AppDelegate() = inherit FormsApplicationDelegate() override val Window = null with get, set // This method is invoked when the application is ready to run. override this.FinishedLaunching(app, options) = this.Window <- new UIWindow(UIScreen.MainScreen.Bounds) Xamarin.Forms.Forms.Init() this.LoadApplication(App()) base.FinishedLaunching(app, options) ``` With our iOS implementation of `OpenUrlService`. ```fsharp type OpenUrlService() = interface IOpenUrlService with member this.OpenUrl url = UIApplication.SharedApplication.OpenUrl(new NSUrl("tel:" + url)) ``` All we needed to include here is to set our dependency to let Xamarin Forms know where the platform specific code is, initialize Xamarin Forms, and tell it what application to load. #### Android Similar to iOS, we just have our `MainActivity` like we would in C# and we basically add the same from iOS. ```fsharp [<assembly: Dependency(typeof<OpenUrlService>)>] do () [<Activity (Label = "PhoneWordFSharp.Droid", MainLauncher = true)>] type MainActivity () = inherit FormsApplicationActivity () override this.OnCreate (bundle) = base.OnCreate (bundle) Forms.Init(this, bundle) this.LoadApplication(App()) ``` With our Android implementation of `OpenUrlService`. ```fsharp type OpenUrlService() = let isIntentAvailable (context:Context) (intent:Intent) = let packageManager = context.PackageManager let list = packageManager.QueryIntentServices(intent, PM.PackageInfoFlags.Services).Union(packageManager.QueryIntentActivities(intent, PM.PackageInfoFlags.Activities)) if list.Any() then true else false interface IOpenUrlService with member this.OpenUrl url = let context = Forms.Context let intent = new Intent(Intent.ActionCall) match context = null with | true -> () | false -> intent.SetData(Uri.Parse("tel:" + url)) |> ignore isIntentAvailable context intent ``` --- This gives a brief introduction to using F# with Xamarin to make full mobile applications and without the need for using any C#. This will only get easier in the future so look out for updates to Xamarin Studio for all the good stuff. The full code can be found on [GitHub](https://github.com/Wintellect/XamarinSamples/tree/master/PhoneWordFSharp) --- [![Xamarin Partner][2]][1] [1]: http://www.wintellect.com/certified-xamarin-mobile-consultants [2]: http://www.wintellect.com/devcenter/wp-content/uploads/2015/05/xamarin-partner_thumb1.png (Xamarin Partner)
{ "content_hash": "d930b7f99f162fefd25e54e8e7f45ac1", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 471, "avg_line_length": 52.884393063583815, "alnum_prop": 0.7164717455459613, "repo_name": "jwood803/Markdown", "id": "8c84ee3ed3db192edfffafe879583a7eec96817f", "size": "9149", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Blog Posts/fSharpXamarin.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package ppc64 implements a PPC64 assembler that assembles Go asm into the corresponding PPC64 instructions as defined by the Power ISA 3.0B. This document provides information on how to write code in Go assembler for PPC64, focusing on the differences between Go and PPC64 assembly language. It assumes some knowledge of PPC64 assembler. The original implementation of PPC64 in Go defined many opcodes that are different from PPC64 opcodes, but updates to the Go assembly language used mnemonics that are mostly similar if not identical to the PPC64 mneumonics, such as VMX and VSX instructions. Not all detail is included here; refer to the Power ISA document if interested in more detail. Starting with Go 1.15 the Go objdump supports the -gnu option, which provides a side by side view of the Go assembler and the PPC64 assembler output. This is extremely helpful in determining what final PPC64 assembly is generated from the corresponding Go assembly. In the examples below, the Go assembly is on the left, PPC64 assembly on the right. 1. Operand ordering In Go asm, the last operand (right) is the target operand, but with PPC64 asm, the first operand (left) is the target. The order of the remaining operands is not consistent: in general opcodes with 3 operands that perform math or logical operations have their operands in reverse order. Opcodes for vector instructions and those with more than 3 operands usually have operands in the same order except for the target operand, which is first in PPC64 asm and last in Go asm. Example: ADD R3, R4, R5 <=> add r5, r4, r3 2. Constant operands In Go asm, an operand that starts with '$' indicates a constant value. If the instruction using the constant has an immediate version of the opcode, then an immediate value is used with the opcode if possible. Example: ADD $1, R3, R4 <=> addi r4, r3, 1 3. Opcodes setting condition codes In PPC64 asm, some instructions other than compares have variations that can set the condition code where meaningful. This is indicated by adding '.' to the end of the PPC64 instruction. In Go asm, these instructions have 'CC' at the end of the opcode. The possible settings of the condition code depend on the instruction. CR0 is the default for fixed-point instructions; CR1 for floating point; CR6 for vector instructions. Example: ANDCC R3, R4, R5 <=> and. r5, r3, r4 (set CR0) 4. Loads and stores from memory In Go asm, opcodes starting with 'MOV' indicate a load or store. When the target is a memory reference, then it is a store; when the target is a register and the source is a memory reference, then it is a load. MOV{B,H,W,D} variations identify the size as byte, halfword, word, doubleword. Adding 'Z' to the opcode for a load indicates zero extend; if omitted it is sign extend. Adding 'U' to a load or store indicates an update of the base register with the offset. Adding 'BR' to an opcode indicates byte-reversed load or store, or the order opposite of the expected endian order. If 'BR' is used then zero extend is assumed. Memory references n(Ra) indicate the address in Ra + n. When used with an update form of an opcode, the value in Ra is incremented by n. Memory references (Ra+Rb) or (Ra)(Rb) indicate the address Ra + Rb, used by indexed loads or stores. Both forms are accepted. When used with an update then the base register is updated by the value in the index register. Examples: MOVD (R3), R4 <=> ld r4,0(r3) MOVW (R3), R4 <=> lwa r4,0(r3) MOVWZU 4(R3), R4 <=> lwzu r4,4(r3) MOVWZ (R3+R5), R4 <=> lwzx r4,r3,r5 MOVHZ (R3), R4 <=> lhz r4,0(r3) MOVHU 2(R3), R4 <=> lhau r4,2(r3) MOVBZ (R3), R4 <=> lbz r4,0(r3) MOVD R4,(R3) <=> std r4,0(r3) MOVW R4,(R3) <=> stw r4,0(r3) MOVW R4,(R3+R5) <=> stwx r4,r3,r5 MOVWU R4,4(R3) <=> stwu r4,4(r3) MOVH R4,2(R3) <=> sth r4,2(r3) MOVBU R4,(R3)(R5) <=> stbux r4,r3,r5 4. Compares When an instruction does a compare or other operation that might result in a condition code, then the resulting condition is set in a field of the condition register. The condition register consists of 8 4-bit fields named CR0 - CR7. When a compare instruction identifies a CR then the resulting condition is set in that field to be read by a later branch or isel instruction. Within these fields, bits are set to indicate less than, greater than, or equal conditions. Once an instruction sets a condition, then a subsequent branch, isel or other instruction can read the condition field and operate based on the bit settings. Examples: CMP R3, R4 <=> cmp r3, r4 (CR0 assumed) CMP R3, R4, CR1 <=> cmp cr1, r3, r4 Note that the condition register is the target operand of compare opcodes, so the remaining operands are in the same order for Go asm and PPC64 asm. When CR0 is used then it is implicit and does not need to be specified. 5. Branches Many branches are represented as a form of the BC instruction. There are other extended opcodes to make it easier to see what type of branch is being used. The following is a brief description of the BC instruction and its commonly used operands. BC op1, op2, op3 op1: type of branch 16 -> bctr (branch on ctr) 12 -> bcr (branch if cr bit is set) 8 -> bcr+bctr (branch on ctr and cr values) 4 -> bcr != 0 (branch if specified cr bit is not set) There are more combinations but these are the most common. op2: condition register field and condition bit This contains an immediate value indicating which condition field to read and what bits to test. Each field is 4 bits long with CR0 at bit 0, CR1 at bit 4, etc. The value is computed as 4*CR+condition with these condition values: 0 -> LT 1 -> GT 2 -> EQ 3 -> OVG Thus 0 means test CR0 for LT, 5 means CR1 for GT, 30 means CR7 for EQ. op3: branch target Examples: BC 12, 0, target <=> blt cr0, target BC 12, 2, target <=> beq cr0, target BC 12, 5, target <=> bgt cr1, target BC 12, 30, target <=> beq cr7, target BC 4, 6, target <=> bne cr1, target BC 4, 1, target <=> ble cr1, target The following extended opcodes are available for ease of use and readability: BNE CR2, target <=> bne cr2, target BEQ CR4, target <=> beq cr4, target BLT target <=> blt target (cr0 default) BGE CR7, target <=> bge cr7, target Refer to the ISA for more information on additional values for the BC instruction, how to handle OVG information, and much more. 5. Align directive Starting with Go 1.12, Go asm supports the PCALIGN directive, which indicates that the next instruction should be aligned to the specified value. Currently 8 and 16 are the only supported values, and a maximum of 2 NOPs will be added to align the code. That means in the case where the code is aligned to 4 but PCALIGN $16 is at that location, the code will only be aligned to 8 to avoid adding 3 NOPs. The purpose of this directive is to improve performance for cases like loops where better alignment (8 or 16 instead of 4) might be helpful. This directive exists in PPC64 assembler and is frequently used by PPC64 assembler writers. PCALIGN $16 PCALIGN $8 Functions in Go are aligned to 16 bytes, as is the case in all other compilers for PPC64. 6. Shift instructions The simple scalar shifts on PPC64 expect a shift count that fits in 5 bits for 32-bit values or 6 bit for 64-bit values. If the shift count is a constant value greater than the max then the assembler sets it to the max for that size (31 for 32 bit values, 63 for 64 bit values). If the shift count is in a register, then only the low 5 or 6 bits of the register will be used as the shift count. The Go compiler will add appropriate code to compare the shift value to achieve the the correct result, and the assembler does not add extra checking. Examples: SRAD $8,R3,R4 => sradi r4,r3,8 SRD $8,R3,R4 => rldicl r4,r3,56,8 SLD $8,R3,R4 => rldicr r4,r3,8,55 SRAW $16,R4,R5 => srawi r5,r4,16 SRW $40,R4,R5 => rlwinm r5,r4,0,0,31 SLW $12,R4,R5 => rlwinm r5,r4,12,0,19 Some non-simple shifts have operands in the Go assembly which don't map directly onto operands in the PPC64 assembly. When an operand in a shift instruction in the Go assembly is a bit mask, that mask is represented as a start and end bit in the PPC64 assembly instead of a mask. See the ISA for more detail on these types of shifts. Here are a few examples: RLWMI $7,R3,$65535,R6 => rlwimi r6,r3,7,16,31 RLDMI $0,R4,$7,R6 => rldimi r6,r4,0,61 More recently, Go opcodes were added which map directly onto the PPC64 opcodes. It is recommended to use the newer opcodes to avoid confusion. RLDICL $0,R4,$15,R6 => rldicl r6,r4,0,15 RLDICR $0,R4,$15,R6 => rldicr r6.r4,0,15 Register naming 1. Special register usage in Go asm The following registers should not be modified by user Go assembler code. R0: Go code expects this register to contain the value 0. R1: Stack pointer R2: TOC pointer when compiled with -shared or -dynlink (a.k.a position independent code) R13: TLS pointer R30: g (goroutine) Register names: Rn is used for general purpose registers. (0-31) Fn is used for floating point registers. (0-31) Vn is used for vector registers. Slot 0 of Vn overlaps with Fn. (0-31) VSn is used for vector-scalar registers. V0-V31 overlap with VS32-VS63. (0-63) CTR represents the count register. LR represents the link register. CR represents the condition register CRn represents a condition register field. (0-7) CRnLT represents CR bit 0 of CR field n. (0-7) CRnGT represents CR bit 1 of CR field n. (0-7) CRnEQ represents CR bit 2 of CR field n. (0-7) CRnSO represents CR bit 3 of CR field n. (0-7) */ package ppc64
{ "content_hash": "9aaac3a0dbbff7d8a637954cdd24527a", "timestamp": "", "source": "github", "line_count": 255, "max_line_length": 90, "avg_line_length": 38.8, "alnum_prop": 0.7368101879927229, "repo_name": "CAFxX/go", "id": "bdaeaf69e1dc74c02d45f3f144ead18f51814c44", "size": "9894", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/cmd/internal/obj/ppc64/doc.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "2544097" }, { "name": "Awk", "bytes": "450" }, { "name": "Batchfile", "bytes": "8202" }, { "name": "C", "bytes": "107970" }, { "name": "C++", "bytes": "917" }, { "name": "Dockerfile", "bytes": "506" }, { "name": "Fortran", "bytes": "394" }, { "name": "Go", "bytes": "44135746" }, { "name": "HTML", "bytes": "2621340" }, { "name": "JavaScript", "bytes": "20486" }, { "name": "Makefile", "bytes": "748" }, { "name": "Perl", "bytes": "31365" }, { "name": "Python", "bytes": "15702" }, { "name": "Shell", "bytes": "54296" } ], "symlink_target": "" }
package com.amazonaws.services.chimesdkmeetings.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.chimesdkmeetings.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import static com.fasterxml.jackson.core.JsonToken.*; /** * StopMeetingTranscriptionResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class StopMeetingTranscriptionResultJsonUnmarshaller implements Unmarshaller<StopMeetingTranscriptionResult, JsonUnmarshallerContext> { public StopMeetingTranscriptionResult unmarshall(JsonUnmarshallerContext context) throws Exception { StopMeetingTranscriptionResult stopMeetingTranscriptionResult = new StopMeetingTranscriptionResult(); return stopMeetingTranscriptionResult; } private static StopMeetingTranscriptionResultJsonUnmarshaller instance; public static StopMeetingTranscriptionResultJsonUnmarshaller getInstance() { if (instance == null) instance = new StopMeetingTranscriptionResultJsonUnmarshaller(); return instance; } }
{ "content_hash": "7ea856103f71344548fd9ac8a2db97b5", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 142, "avg_line_length": 35.15151515151515, "alnum_prop": 0.8068965517241379, "repo_name": "aws/aws-sdk-java", "id": "aa28e25d38ffeef83e4302092b5f1dfbb7214366", "size": "1740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-chimesdkmeetings/src/main/java/com/amazonaws/services/chimesdkmeetings/model/transform/StopMeetingTranscriptionResultJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace gpu { namespace { static const base::FilePath::CharType kGpuCachePath[] = FILE_PATH_LITERAL("GPUCache"); } // namespace // ShaderDiskCacheEntry handles the work of caching/updating the cached // shaders. class ShaderDiskCacheEntry : public base::ThreadChecker { public: ShaderDiskCacheEntry(ShaderDiskCache* cache, const std::string& key, const std::string& shader); ~ShaderDiskCacheEntry(); void Cache(); private: enum OpType { OPEN_ENTRY, WRITE_DATA, CREATE_ENTRY, }; void OnOpComplete(int rv); int OpenCallback(int rv); int WriteCallback(int rv); int IOComplete(int rv); ShaderDiskCache* cache_; OpType op_type_; std::string key_; std::string shader_; disk_cache::Entry* entry_; base::WeakPtr<ShaderDiskCacheEntry> weak_ptr_; base::WeakPtrFactory<ShaderDiskCacheEntry> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ShaderDiskCacheEntry); }; // ShaderDiskReadHelper is used to load all of the cached shaders from the // disk cache and send to the memory cache. class ShaderDiskReadHelper : public base::ThreadChecker { public: using ShaderLoadedCallback = ShaderDiskCache::ShaderLoadedCallback; ShaderDiskReadHelper(ShaderDiskCache* cache, const ShaderLoadedCallback& callback); ~ShaderDiskReadHelper(); void LoadCache(); private: enum OpType { TERMINATE, OPEN_NEXT, OPEN_NEXT_COMPLETE, READ_COMPLETE, ITERATION_FINISHED }; void OnOpComplete(int rv); int OpenNextEntry(); int OpenNextEntryComplete(int rv); int ReadComplete(int rv); int IterationComplete(int rv); ShaderDiskCache* cache_; ShaderLoadedCallback shader_loaded_callback_; OpType op_type_; std::unique_ptr<disk_cache::Backend::Iterator> iter_; scoped_refptr<net::IOBufferWithSize> buf_; disk_cache::Entry* entry_; base::WeakPtrFactory<ShaderDiskReadHelper> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ShaderDiskReadHelper); }; class ShaderClearHelper : public base::ThreadChecker { public: ShaderClearHelper(ShaderCacheFactory* factory, scoped_refptr<ShaderDiskCache> cache, const base::FilePath& path, const base::Time& delete_begin, const base::Time& delete_end, const base::Closure& callback); ~ShaderClearHelper(); void Clear(); private: enum OpType { TERMINATE, VERIFY_CACHE_SETUP, DELETE_CACHE }; void DoClearShaderCache(int rv); ShaderCacheFactory* factory_; scoped_refptr<ShaderDiskCache> cache_; OpType op_type_; base::FilePath path_; base::Time delete_begin_; base::Time delete_end_; base::Closure callback_; base::WeakPtrFactory<ShaderClearHelper> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ShaderClearHelper); }; //////////////////////////////////////////////////////////////////////////////// // ShaderDiskCacheEntry ShaderDiskCacheEntry::ShaderDiskCacheEntry(ShaderDiskCache* cache, const std::string& key, const std::string& shader) : cache_(cache), op_type_(OPEN_ENTRY), key_(key), shader_(shader), entry_(nullptr), weak_ptr_factory_(this) { weak_ptr_ = weak_ptr_factory_.GetWeakPtr(); } ShaderDiskCacheEntry::~ShaderDiskCacheEntry() { DCHECK(CalledOnValidThread()); if (entry_) entry_->Close(); } void ShaderDiskCacheEntry::Cache() { DCHECK(CalledOnValidThread()); int rv = cache_->backend()->OpenEntry( key_, &entry_, base::Bind(&ShaderDiskCacheEntry::OnOpComplete, weak_ptr_factory_.GetWeakPtr())); if (rv != net::ERR_IO_PENDING) OnOpComplete(rv); } void ShaderDiskCacheEntry::OnOpComplete(int rv) { DCHECK(CalledOnValidThread()); // The function calls inside the switch block below can end up destroying // |this|. So hold on to a WeakPtr<>, and terminate the while loop if |this| // has been destroyed. auto weak_ptr = std::move(weak_ptr_); do { switch (op_type_) { case OPEN_ENTRY: rv = OpenCallback(rv); break; case CREATE_ENTRY: rv = WriteCallback(rv); break; case WRITE_DATA: rv = IOComplete(rv); break; } } while (rv != net::ERR_IO_PENDING && weak_ptr); if (weak_ptr) weak_ptr_ = std::move(weak_ptr); } int ShaderDiskCacheEntry::OpenCallback(int rv) { DCHECK(CalledOnValidThread()); if (rv == net::OK) { cache_->backend()->OnExternalCacheHit(key_); cache_->EntryComplete(this); return rv; } op_type_ = CREATE_ENTRY; return cache_->backend()->CreateEntry( key_, &entry_, base::Bind(&ShaderDiskCacheEntry::OnOpComplete, weak_ptr_factory_.GetWeakPtr())); } int ShaderDiskCacheEntry::WriteCallback(int rv) { DCHECK(CalledOnValidThread()); if (rv != net::OK) { LOG(ERROR) << "Failed to create shader cache entry: " << rv; cache_->EntryComplete(this); return rv; } op_type_ = WRITE_DATA; scoped_refptr<net::StringIOBuffer> io_buf = new net::StringIOBuffer(shader_); return entry_->WriteData(1, 0, io_buf.get(), shader_.length(), base::Bind(&ShaderDiskCacheEntry::OnOpComplete, weak_ptr_factory_.GetWeakPtr()), false); } int ShaderDiskCacheEntry::IOComplete(int rv) { DCHECK(CalledOnValidThread()); cache_->EntryComplete(this); return rv; } //////////////////////////////////////////////////////////////////////////////// // ShaderDiskReadHelper ShaderDiskReadHelper::ShaderDiskReadHelper(ShaderDiskCache* cache, const ShaderLoadedCallback& callback) : cache_(cache), shader_loaded_callback_(callback), op_type_(OPEN_NEXT), buf_(NULL), entry_(NULL), weak_ptr_factory_(this) {} ShaderDiskReadHelper::~ShaderDiskReadHelper() { DCHECK(CalledOnValidThread()); if (entry_) entry_->Close(); iter_ = nullptr; } void ShaderDiskReadHelper::LoadCache() { DCHECK(CalledOnValidThread()); OnOpComplete(net::OK); } void ShaderDiskReadHelper::OnOpComplete(int rv) { DCHECK(CalledOnValidThread()); do { switch (op_type_) { case OPEN_NEXT: rv = OpenNextEntry(); break; case OPEN_NEXT_COMPLETE: rv = OpenNextEntryComplete(rv); break; case READ_COMPLETE: rv = ReadComplete(rv); break; case ITERATION_FINISHED: rv = IterationComplete(rv); break; case TERMINATE: cache_->ReadComplete(); rv = net::ERR_IO_PENDING; // break the loop break; } } while (rv != net::ERR_IO_PENDING); } int ShaderDiskReadHelper::OpenNextEntry() { DCHECK(CalledOnValidThread()); op_type_ = OPEN_NEXT_COMPLETE; if (!iter_) iter_ = cache_->backend()->CreateIterator(); return iter_->OpenNextEntry(&entry_, base::Bind(&ShaderDiskReadHelper::OnOpComplete, weak_ptr_factory_.GetWeakPtr())); } int ShaderDiskReadHelper::OpenNextEntryComplete(int rv) { DCHECK(CalledOnValidThread()); if (rv == net::ERR_FAILED) { iter_.reset(); op_type_ = ITERATION_FINISHED; return net::OK; } if (rv < 0) return rv; op_type_ = READ_COMPLETE; buf_ = new net::IOBufferWithSize(entry_->GetDataSize(1)); return entry_->ReadData(1, 0, buf_.get(), buf_->size(), base::Bind(&ShaderDiskReadHelper::OnOpComplete, weak_ptr_factory_.GetWeakPtr())); } int ShaderDiskReadHelper::ReadComplete(int rv) { DCHECK(CalledOnValidThread()); if (rv && rv == buf_->size() && !shader_loaded_callback_.is_null()) { shader_loaded_callback_.Run(entry_->GetKey(), std::string(buf_->data(), buf_->size())); } buf_ = NULL; entry_->Close(); entry_ = NULL; op_type_ = OPEN_NEXT; return net::OK; } int ShaderDiskReadHelper::IterationComplete(int rv) { DCHECK(CalledOnValidThread()); iter_.reset(); op_type_ = TERMINATE; return net::OK; } //////////////////////////////////////////////////////////////////////////////// // ShaderClearHelper ShaderClearHelper::ShaderClearHelper(ShaderCacheFactory* factory, scoped_refptr<ShaderDiskCache> cache, const base::FilePath& path, const base::Time& delete_begin, const base::Time& delete_end, const base::Closure& callback) : factory_(factory), cache_(std::move(cache)), op_type_(VERIFY_CACHE_SETUP), path_(path), delete_begin_(delete_begin), delete_end_(delete_end), callback_(callback), weak_ptr_factory_(this) {} ShaderClearHelper::~ShaderClearHelper() { DCHECK(CalledOnValidThread()); } void ShaderClearHelper::Clear() { DCHECK(CalledOnValidThread()); DoClearShaderCache(net::OK); } void ShaderClearHelper::DoClearShaderCache(int rv) { DCHECK(CalledOnValidThread()); while (rv != net::ERR_IO_PENDING) { switch (op_type_) { case VERIFY_CACHE_SETUP: rv = cache_->SetAvailableCallback( base::Bind(&ShaderClearHelper::DoClearShaderCache, weak_ptr_factory_.GetWeakPtr())); op_type_ = DELETE_CACHE; break; case DELETE_CACHE: rv = cache_->Clear(delete_begin_, delete_end_, base::Bind(&ShaderClearHelper::DoClearShaderCache, weak_ptr_factory_.GetWeakPtr())); op_type_ = TERMINATE; break; case TERMINATE: callback_.Run(); // Calling CacheCleared() destroys |this|. factory_->CacheCleared(path_); rv = net::ERR_IO_PENDING; // Break the loop. break; } } } //////////////////////////////////////////////////////////////////////////////// // ShaderCacheFactory ShaderCacheFactory::ShaderCacheFactory( scoped_refptr<base::SingleThreadTaskRunner> cache_task_runner) : cache_task_runner_(std::move(cache_task_runner)) {} ShaderCacheFactory::~ShaderCacheFactory() {} void ShaderCacheFactory::SetCacheInfo(int32_t client_id, const base::FilePath& path) { DCHECK(CalledOnValidThread()); client_id_to_path_map_[client_id] = path; } void ShaderCacheFactory::RemoveCacheInfo(int32_t client_id) { DCHECK(CalledOnValidThread()); client_id_to_path_map_.erase(client_id); } scoped_refptr<ShaderDiskCache> ShaderCacheFactory::Get(int32_t client_id) { DCHECK(CalledOnValidThread()); ClientIdToPathMap::iterator iter = client_id_to_path_map_.find(client_id); if (iter == client_id_to_path_map_.end()) return NULL; return ShaderCacheFactory::GetByPath(iter->second); } scoped_refptr<ShaderDiskCache> ShaderCacheFactory::GetByPath( const base::FilePath& path) { DCHECK(CalledOnValidThread()); ShaderCacheMap::iterator iter = shader_cache_map_.find(path); if (iter != shader_cache_map_.end()) return iter->second; ShaderDiskCache* cache = new ShaderDiskCache(this, path); cache->Init(cache_task_runner_); return cache; } void ShaderCacheFactory::AddToCache(const base::FilePath& key, ShaderDiskCache* cache) { DCHECK(CalledOnValidThread()); shader_cache_map_[key] = cache; } void ShaderCacheFactory::RemoveFromCache(const base::FilePath& key) { DCHECK(CalledOnValidThread()); shader_cache_map_.erase(key); } void ShaderCacheFactory::ClearByPath(const base::FilePath& path, const base::Time& delete_begin, const base::Time& delete_end, const base::Closure& callback) { DCHECK(CalledOnValidThread()); DCHECK(!callback.is_null()); auto helper = base::MakeUnique<ShaderClearHelper>( this, GetByPath(path), path, delete_begin, delete_end, callback); // We could receive requests to clear the same path with different // begin/end times. So, we keep a list of requests. If we haven't seen this // path before we kick off the clear and add it to the list. If we have see it // already, then we already have a clear running. We add this clear to the // list and wait for any previous clears to finish. ShaderClearMap::iterator iter = shader_clear_map_.find(path); if (iter != shader_clear_map_.end()) { iter->second.push(std::move(helper)); return; } // Insert the helper in the map before calling Clear(), since it can lead to a // call back into CacheCleared(). ShaderClearHelper* helper_ptr = helper.get(); shader_clear_map_.insert( std::pair<base::FilePath, ShaderClearQueue>(path, ShaderClearQueue())); shader_clear_map_[path].push(std::move(helper)); helper_ptr->Clear(); } void ShaderCacheFactory::CacheCleared(const base::FilePath& path) { DCHECK(CalledOnValidThread()); ShaderClearMap::iterator iter = shader_clear_map_.find(path); if (iter == shader_clear_map_.end()) { LOG(ERROR) << "Completed clear but missing clear helper."; return; } iter->second.pop(); // If there are remaining items in the list we trigger the Clear on the // next one. if (!iter->second.empty()) { iter->second.front()->Clear(); return; } shader_clear_map_.erase(iter); } //////////////////////////////////////////////////////////////////////////////// // ShaderDiskCache ShaderDiskCache::ShaderDiskCache(ShaderCacheFactory* factory, const base::FilePath& cache_path) : factory_(factory), cache_available_(false), cache_path_(cache_path), is_initialized_(false) { factory_->AddToCache(cache_path_, this); } ShaderDiskCache::~ShaderDiskCache() { factory_->RemoveFromCache(cache_path_); } void ShaderDiskCache::Init( scoped_refptr<base::SingleThreadTaskRunner> cache_task_runner) { if (is_initialized_) { NOTREACHED(); // can't initialize disk cache twice. return; } is_initialized_ = true; int rv = disk_cache::CreateCacheBackend( net::SHADER_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path_.Append(kGpuCachePath), gpu::kDefaultMaxProgramCacheMemoryBytes, true, cache_task_runner, NULL, &backend_, base::Bind(&ShaderDiskCache::CacheCreatedCallback, this)); if (rv == net::OK) cache_available_ = true; } void ShaderDiskCache::Cache(const std::string& key, const std::string& shader) { if (!cache_available_) return; auto shim = base::MakeUnique<ShaderDiskCacheEntry>(this, key, shader); shim->Cache(); auto* raw_ptr = shim.get(); entries_.insert(std::make_pair(raw_ptr, std::move(shim))); } int ShaderDiskCache::Clear(const base::Time begin_time, const base::Time end_time, const net::CompletionCallback& completion_callback) { int rv; if (begin_time.is_null()) { rv = backend_->DoomAllEntries(completion_callback); } else { rv = backend_->DoomEntriesBetween(begin_time, end_time, completion_callback); } return rv; } int32_t ShaderDiskCache::Size() { if (!cache_available_) return -1; return backend_->GetEntryCount(); } int ShaderDiskCache::SetAvailableCallback( const net::CompletionCallback& callback) { if (cache_available_) return net::OK; available_callback_ = callback; return net::ERR_IO_PENDING; } void ShaderDiskCache::CacheCreatedCallback(int rv) { if (rv != net::OK) { LOG(ERROR) << "Shader Cache Creation failed: " << rv; return; } helper_ = base::MakeUnique<ShaderDiskReadHelper>(this, shader_loaded_callback_); helper_->LoadCache(); } void ShaderDiskCache::EntryComplete(ShaderDiskCacheEntry* entry) { entries_.erase(entry); if (entries_.empty() && !cache_complete_callback_.is_null()) cache_complete_callback_.Run(net::OK); } void ShaderDiskCache::ReadComplete() { helper_ = nullptr; // The cache is considered available after we have finished reading any // of the old cache values off disk. This prevents a potential race where we // are reading from disk and execute a cache clear at the same time. cache_available_ = true; if (!available_callback_.is_null()) { available_callback_.Run(net::OK); available_callback_.Reset(); } } int ShaderDiskCache::SetCacheCompleteCallback( const net::CompletionCallback& callback) { if (entries_.empty()) { return net::OK; } cache_complete_callback_ = callback; return net::ERR_IO_PENDING; } } // namespace gpu
{ "content_hash": "71ba364476c0399759bacf3d3ab07312", "timestamp": "", "source": "github", "line_count": 563, "max_line_length": 80, "avg_line_length": 29.733570159857905, "alnum_prop": 0.6234767025089606, "repo_name": "google-ar/WebARonARCore", "id": "ff09ae77771c4b557301200bd71521e0f63d9ba1", "size": "17249", "binary": false, "copies": "2", "ref": "refs/heads/webarcore_57.0.2987.5", "path": "gpu/ipc/host/shader_disk_cache.cc", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "5149ccdf8fa4db53cc1b6dde4f204c03", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "189a51f5858d1625aa952e0a0a82279fae25e6c9", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carex/Carex mannii/ Syn. Carex boryana simplicissima/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Mon Aug 31 23:15:49 CEST 2015 --> <title>IObjectStringWithPostfixCheck (FailFast v.1.3)</title> <meta name="date" content="2015-08-31"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="IObjectStringWithPostfixCheck (FailFast v.1.3)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/IObjectStringWithPostfixCheck.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../starkcoder/failfast/checks/objects/strings/IObjectStringWithoutSubstringCheck.html" title="interface in starkcoder.failfast.checks.objects.strings"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../starkcoder/failfast/checks/objects/strings/IObjectStringWithPrefixCheck.html" title="interface in starkcoder.failfast.checks.objects.strings"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?starkcoder/failfast/checks/objects/strings/IObjectStringWithPostfixCheck.html" target="_top">Frames</a></li> <li><a href="IObjectStringWithPostfixCheck.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">starkcoder.failfast.checks.objects.strings</div> <h2 title="Interface IObjectStringWithPostfixCheck" class="title">Interface IObjectStringWithPostfixCheck</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Superinterfaces:</dt> <dd><a href="../../../../../starkcoder/failfast/checks/ICheck.html" title="interface in starkcoder.failfast.checks">ICheck</a></dd> </dl> <dl> <dt>All Known Subinterfaces:</dt> <dd><a href="../../../../../starkcoder/failfast/checks/IChecker.html" title="interface in starkcoder.failfast.checks">IChecker</a>, <a href="../../../../../starkcoder/failfast/checks/objects/IObjectChecker.html" title="interface in starkcoder.failfast.checks.objects">IObjectChecker</a>, <a href="../../../../../starkcoder/failfast/checks/objects/strings/IObjectStringChecker.html" title="interface in starkcoder.failfast.checks.objects.strings">IObjectStringChecker</a></dd> </dl> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../../starkcoder/failfast/checks/AChecker.html" title="class in starkcoder.failfast.checks">AChecker</a>, <a href="../../../../../starkcoder/failfast/checks/Checker.html" title="class in starkcoder.failfast.checks">Checker</a></dd> </dl> <hr> <br> <pre>public interface <span class="strong">IObjectStringWithPostfixCheck</span> extends <a href="../../../../../starkcoder/failfast/checks/ICheck.html" title="interface in starkcoder.failfast.checks">ICheck</a></pre> <div class="block">Specifies a postfix check for String.</div> <dl><dt><span class="strong">Author:</span></dt> <dd>Keld Oelykke</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../starkcoder/failfast/checks/objects/strings/IObjectStringWithPostfixCheck.html#isStringWithPostfix(java.lang.Object, java.lang.String, java.lang.String)">isStringWithPostfix</a></strong>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;caller, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;referenceA, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;postfix)</code> <div class="block">Checks if A ends with postfix.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="isStringWithPostfix(java.lang.Object, java.lang.String, java.lang.String)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>isStringWithPostfix</h4> <pre>boolean&nbsp;isStringWithPostfix(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;caller, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;referenceA, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;postfix)</pre> <div class="block">Checks if A ends with postfix. <p> The empty string is a postfix to all string instances. </p> <p> null has no postfixes and is not a postfix. </p></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>caller</code> - end-user instance initiating the check</dd><dd><code>referenceA</code> - reference to check for postfix reference B</dd><dd><code>postfix</code> - potential postfix of reference A</dd> <dt><span class="strong">Returns:</span></dt><dd>true, if referenced postfix is a postfix of A - otherwise false</dd> <dt><span class="strong">Throws:</span></dt> <dd><code><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html?is-external=true" title="class or interface in java.lang">IllegalArgumentException</a></code> - if caller is null</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/IObjectStringWithPostfixCheck.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../starkcoder/failfast/checks/objects/strings/IObjectStringWithoutSubstringCheck.html" title="interface in starkcoder.failfast.checks.objects.strings"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../starkcoder/failfast/checks/objects/strings/IObjectStringWithPrefixCheck.html" title="interface in starkcoder.failfast.checks.objects.strings"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?starkcoder/failfast/checks/objects/strings/IObjectStringWithPostfixCheck.html" target="_top">Frames</a></li> <li><a href="IObjectStringWithPostfixCheck.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><i>The MIT License (MIT) - Copyright &#169; 2014-2015 Keld Oelykke. All Rights Reserved.</i></small></p> </body> </html>
{ "content_hash": "6590b1690b14bf87072a009ef0f3e92d", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 475, "avg_line_length": 44.35, "alnum_prop": 0.661499436302142, "repo_name": "KeldOelykke/FailFast", "id": "7b9f514534b27ca8b16b652f19953c4845e9f4a6", "size": "10644", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Java/Web/war/releases/1.3/api/starkcoder/failfast/checks/objects/strings/IObjectStringWithPostfixCheck.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18114" }, { "name": "HTML", "bytes": "41796564" }, { "name": "Java", "bytes": "3601840" }, { "name": "JavaScript", "bytes": "21775" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- --> <widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd"> <widget id="sales_widget_guestform" class="Magento\Sales\Block\Widget\Guest\Form" is_email_compatible="true" > <label translate="true">Orders and Returns</label> <description translate="true">Orders and Returns Search Form</description> <parameters> <parameter name="title" xsi:type="text" visible="false"> <label translate="true">Anchor Custom Title</label> </parameter> <parameter name="template" xsi:type="select" visible="false"> <options> <option name="default" value="hierarchy/widget/link/link_block.phtml" selected="true"> <label translate="true">CMS Page Link Block Template</label> </option> <option name="link_inline" value="hierarchy/widget/link/link_inline.phtml"> <label translate="true">CMS Page Link Inline Template</label> </option> </options> </parameter> <parameter name="link_display" xsi:type="select" visible="true" sort_order="10" source_model="Magento\Config\Model\Config\Source\Yesno"> <label translate="true">Display a Link to Loading a Spreadsheet</label> <description translate="true">Defines whether a link to My Account</description> </parameter> <parameter name="link_text" xsi:type="text" required="true" visible="true" sort_order="20"> <label translate="true">Link Text</label> <description translate="true">The text of the link to the My Account &amp;gt; Order by SKU page</description> <depends> <parameter name="link_display" value="1" /> </depends> <value translate="true">Load a list of SKUs</value> </parameter> <parameter name="id_path" xsi:type="block" visible="true" required="true" sort_order="10"> <label translate="true">Product</label> <block class="Magento\Catalog\Block\Adminhtml\Product\Widget\Chooser"> <data> <item name="button" xsi:type="array"> <item name="open" xsi:type="string">Select Product...</item> </item> </data> </block> </parameter> </parameters> <containers> <container name="left"> <template name="default" value="default_template" /> </container> <container name="right"> <template name="default" value="default_template" /> </container> </containers> </widget> </widgets>
{ "content_hash": "85ba2c6e35dba3129814ac1a6d9a3096", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 125, "avg_line_length": 52.526315789473685, "alnum_prop": 0.5534402137608551, "repo_name": "andrewhowdencom/m2onk8s", "id": "82a9d0e89126eb09db795cdddbc3fc7e452b48cd", "size": "3102", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "app/dev/tests/integration/testsuite/Magento/Widget/Model/Config/_files/orders_and_returns.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "16901" }, { "name": "CSS", "bytes": "1736429" }, { "name": "HTML", "bytes": "6151083" }, { "name": "JavaScript", "bytes": "2413949" }, { "name": "Makefile", "bytes": "4212" }, { "name": "PHP", "bytes": "12463878" }, { "name": "Shell", "bytes": "8784" }, { "name": "Smarty", "bytes": "1089" }, { "name": "XSLT", "bytes": "19979" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_console_w32_spawnvp_44.c Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-44.tmpl.c */ /* * @description * CWE: 78 OS Command Injection * BadSource: console Read input from the console * GoodSource: Fixed string * Sinks: w32_spawnvp * BadSink : execute command with wspawnvp * Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT L"cmd.exe" #define COMMAND_ARG1 L"/c" #define COMMAND_ARG2 L"dir " #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH L"/bin/sh" #define COMMAND_INT L"sh" #define COMMAND_ARG1 L"-c" #define COMMAND_ARG2 L"ls " #define COMMAND_ARG3 data #endif #include <process.h> #ifndef OMITBAD static void badSink(wchar_t * data) { { wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL}; /* wspawnvp - searches for the location of the command among * the directories specified by the PATH environment variable */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ _wspawnvp(_P_WAIT, COMMAND_INT, args); } } void CWE78_OS_Command_Injection__wchar_t_console_w32_spawnvp_44_bad() { wchar_t * data; /* define a function pointer */ void (*funcPtr) (wchar_t *) = badSink; wchar_t dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; { /* Read input from the console */ size_t dataLen = wcslen(data); /* if there is room in data, read into it from the console */ if (100-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgetws() */ dataLen = wcslen(data); if (dataLen > 0 && data[dataLen-1] == L'\n') { data[dataLen-1] = L'\0'; } } else { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } } } /* use the function pointer */ funcPtr(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSink(wchar_t * data) { { wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL}; /* wspawnvp - searches for the location of the command among * the directories specified by the PATH environment variable */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ _wspawnvp(_P_WAIT, COMMAND_INT, args); } } static void goodG2B() { wchar_t * data; void (*funcPtr) (wchar_t *) = goodG2BSink; wchar_t dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); funcPtr(data); } void CWE78_OS_Command_Injection__wchar_t_console_w32_spawnvp_44_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE78_OS_Command_Injection__wchar_t_console_w32_spawnvp_44_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE78_OS_Command_Injection__wchar_t_console_w32_spawnvp_44_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "ae5342f9beadaadff0d0d8bf6c4978b7", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 151, "avg_line_length": 31, "alnum_prop": 0.6111234705228031, "repo_name": "JianpingZeng/xcc", "id": "344cf7307e9bc58e2ef0f16458bf80b2d45c12bb", "size": "4495", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s06/CWE78_OS_Command_Injection__wchar_t_console_w32_spawnvp_44.c", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
// Copyright 2020, Google LLC // // 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 // // https://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. using CloudNative.CloudEvents; using Google.Cloud.Functions.Framework; using Google.Events.Protobuf.Cloud.Storage.V1; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Google.Cloud.Functions.Hosting.Tests { public class FunctionTargetTest { [Fact] public void NonFunctionType() { var services = new ServiceCollection(); Assert.Throws<InvalidOperationException>(() => HostingInternals.AddServicesForFunctionTarget(services, typeof(NonFunction))); } [Fact] public void NonInstantiableFunctionType() { var services = new ServiceCollection(); services.AddLogging(); HostingInternals.AddServicesForFunctionTarget(services, typeof(NonInstantiableFunction)); // We only find out when we try to get an IHttpFunction that we can't actually instantiate the function. var provider = services.BuildServiceProvider(); Assert.Throws<InvalidOperationException>(() => provider.GetRequiredService<IHttpFunction>()); } [Fact] public void FunctionTypeImplementsMultipleInterfaces() { var services = new ServiceCollection(); Assert.Throws<InvalidOperationException>(() => HostingInternals.AddServicesForFunctionTarget(services, typeof(MultipleCloudEventTypes))); } [Fact] public async Task NonGenericCloudEventFunction() { var services = new ServiceCollection(); services.AddLogging(); HostingInternals.AddServicesForFunctionTarget(services, typeof(EventIdRememberingFunction)); var provider = services.BuildServiceProvider(); var function = provider.GetRequiredService<IHttpFunction>(); Assert.Equal(typeof(EventIdRememberingFunction), provider.GetRequiredService<HostingInternals.FunctionTypeProvider>().FunctionType); string eventId = Guid.NewGuid().ToString(); var context = new DefaultHttpContext { Request = { // No actual content, but that's okay. ContentType = "application/json", Headers = { { "ce-specversion", "1.0" }, { "ce-source", "test" }, { "ce-type", "test" }, { "ce-id", eventId } } } }; await function.HandleAsync(context); Assert.Equal(eventId, EventIdRememberingFunction.LastEventId); } [Fact] public async Task TargetFunction_EventFunction_Generic() { var services = new ServiceCollection(); services.AddLogging(); HostingInternals.AddServicesForFunctionTarget(services, typeof(StorageCloudEventFunction)); var provider = services.BuildServiceProvider(); var function = provider.GetRequiredService<IHttpFunction>(); Assert.Equal(typeof(StorageCloudEventFunction), provider.GetRequiredService<HostingInternals.FunctionTypeProvider>().FunctionType); var eventId = Guid.NewGuid().ToString(); var context = new DefaultHttpContext { Request = { ContentType = "application/json", Body = new MemoryStream(Encoding.UTF8.GetBytes("{\"name\": \"testdata\"}")), Headers = { { "ce-specversion", "1.0" }, { "ce-source", "test" }, { "ce-type", "test" }, { "ce-id", eventId } } }, }; await function.HandleAsync(context); Assert.Equal(eventId, StorageCloudEventFunction.LastEventId); Assert.Equal("testdata", StorageCloudEventFunction.LastData.Name); } [Fact] public void FindDefaultFunctionType_NoFunctionTypes() => Assert.Throws<ArgumentException>(() => HostingInternals.FindDefaultFunctionType( typeof(FunctionTargetTest), typeof(FunctionsEnvironmentVariablesConfigurationSourceTest), typeof(AbstractHttpFunction), // Abstract, doesn't count typeof(INamedHttpFunction) // Interface, doesn't count )); [Fact] public void FindDefaultFunctionType_MultipleFunctionTypes() => Assert.Throws<ArgumentException>(() => HostingInternals.FindDefaultFunctionType( typeof(DefaultFunction), typeof(EventIdRememberingFunction))); [Fact] public void FindDefaultFunctionType_SingleFunctionType() { var expected = typeof(DefaultFunction); var actual = HostingInternals.FindDefaultFunctionType( typeof(FunctionTargetTest), typeof(FunctionsEnvironmentVariablesConfigurationSourceTest), typeof(AbstractHttpFunction), // Abstract, doesn't count typeof(INamedHttpFunction), // Interface, doesn't count typeof(DefaultFunction)); Assert.Equal(expected, actual); } [Fact] public void FindDefaultFunctionType_TypedCloudEventFunction() { var expected = typeof(StorageCloudEventFunction); var actual = HostingInternals.FindDefaultFunctionType(typeof(StorageCloudEventFunction)); Assert.Equal(expected, actual); } [Fact] public void FindDefaultFunctionType_MultipleCloudEventTypesFunction() => Assert.Throws<ArgumentException>(() => HostingInternals.FindDefaultFunctionType( typeof(MultipleCloudEventTypes))); public class DefaultFunction : IHttpFunction { public Task HandleAsync(HttpContext context) => Task.CompletedTask; } public class EventIdRememberingFunction : ICloudEventFunction { /// <summary> /// Horrible way of testing which function was actually used: remember the last event ID. /// Currently we only have a single test using this; if we have more, we'll need to disable /// parallelism. /// </summary> public static string LastEventId { get; private set; } public Task HandleAsync(CloudEvent cloudEvent, CancellationToken cancellationToken) { LastEventId = cloudEvent.Id; return Task.CompletedTask; } } public class StorageCloudEventFunction : ICloudEventFunction<StorageObjectData> { public static string LastEventId { get; set; } public static StorageObjectData LastData { get; set; } public Task HandleAsync(CloudEvent cloudEvent, StorageObjectData data, CancellationToken cancellationToken) { LastEventId = cloudEvent.Id; LastData = data; return Task.CompletedTask; } } public class NonFunction { } public class NonInstantiableFunction : IHttpFunction { private NonInstantiableFunction() { } public Task HandleAsync(HttpContext context) => Task.CompletedTask; } // Just a sample interface extending a function interface. public interface INamedHttpFunction : IHttpFunction { public string Name { get; } } public abstract class AbstractHttpFunction : IHttpFunction { public abstract Task HandleAsync(HttpContext context); } public class MultipleCloudEventTypes : ICloudEventFunction<string>, ICloudEventFunction<object> { public Task HandleAsync(CloudEvent cloudEvent, string data, CancellationToken cancellationToken) => Task.CompletedTask; public Task HandleAsync(CloudEvent cloudEvent, object data, CancellationToken cancellationToken) => Task.CompletedTask; } } }
{ "content_hash": "3be441d256a3b4edb4fd4db2e1b796d3", "timestamp": "", "source": "github", "line_count": 227, "max_line_length": 149, "avg_line_length": 39.72687224669603, "alnum_prop": 0.6119982257706809, "repo_name": "GoogleCloudPlatform/functions-framework-dotnet", "id": "ca998246eebf46df7dbae83dc4f4cc5d1656352b", "size": "9020", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/Google.Cloud.Functions.Hosting.Tests/FunctionTargetTest.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "110" }, { "name": "C#", "bytes": "240562" }, { "name": "F#", "bytes": "4651" }, { "name": "Shell", "bytes": "14174" }, { "name": "Visual Basic .NET", "bytes": "4715" } ], "symlink_target": "" }
package io.fabric8.openshift.client.dsl.internal; import io.fabric8.kubernetes.client.dsl.Resource; import okhttp3.OkHttpClient; import io.fabric8.openshift.api.model.DoneableImageStream; import io.fabric8.openshift.api.model.ImageStream; import io.fabric8.openshift.api.model.ImageStreamList; import io.fabric8.openshift.client.OpenShiftConfig; import java.util.Map; import java.util.TreeMap; public class ImageStreamOperationsImpl extends OpenShiftOperation<ImageStream, ImageStreamList, DoneableImageStream, Resource<ImageStream, DoneableImageStream>> { public ImageStreamOperationsImpl(OkHttpClient client, OpenShiftConfig config, String namespace) { this(client, config, null, namespace, null, true, null, null, false, -1, new TreeMap<String, String>(), new TreeMap<String, String>(), new TreeMap<String, String[]>(), new TreeMap<String, String[]>(), new TreeMap<String, String>()); } public ImageStreamOperationsImpl(OkHttpClient client, OpenShiftConfig config, String apiVersion, String namespace, String name, Boolean cascading, ImageStream item, String resourceVersion, Boolean reloadingFromServer, long gracePeriodSeconds, Map<String, String> labels, Map<String, String> labelsNot, Map<String, String[]> labelsIn, Map<String, String[]> labelsNotIn, Map<String, String> fields) { super(client, config, null, apiVersion, "imagestreams", namespace, name, cascading, item, resourceVersion, reloadingFromServer, gracePeriodSeconds, labels, labelsNot, labelsIn, labelsNotIn, fields); } }
{ "content_hash": "1b3e4cb8af84acf33b1a64e3e3f997f7", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 400, "avg_line_length": 63.166666666666664, "alnum_prop": 0.7981530343007915, "repo_name": "jimmidyson/kubernetes-client", "id": "e29e55ccdd007a943d7d1ebfd9a58ad1979f2617", "size": "2121", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/ImageStreamOperationsImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1948" }, { "name": "Java", "bytes": "1320025" } ], "symlink_target": "" }
''' Created on 2015年3月4日 @author: wanhao01 ''' from ConfigParser import NoSectionError from ConfigParser import NoOptionError from ConfigParser import DuplicateSectionError import ConfigParser import sys from crawler.minispider import logwarning class SpiderConfig(object): ''' spider configuration file encapsulation. ''' def __init__(self, configName): ''' Constructor ''' self.__spiderSection = 'spider' self.__cf = ConfigParser.ConfigParser() self.__configFile = configName self.__options = {'url_list_file': './urls', 'output_directory': './output', 'max_depth': '1', 'crawl_interval': '1', 'crawl_timeout': '1', 'target_url': '.*\.(gif|png|jpg|bmp)$', '__thread_count': '8', 'email': 'wanhao01@baidu.com' } def loadConfigFile(self): ''' load and initialize the attributes of the Spider Config entity. ''' config_files = self.__cf.read(self.__configFile) if(len(config_files) == 0): raise NoConfigError(self.__cur_file_dir() + '\\' + self.__configFile) self.__initOption('url_list_file') self.__initOption('output_directory') self.__initOption('max_depth') self.__initOption('crawl_interval') self.__initOption('crawl_timeout') self.__initOption('target_url') self.__initOption('thread_count') self.__initOption('email') def __initOption(self, option): ''' initialize the option.whenever there's any exception using the default value for the specific option. ''' exp = Exception() try: option_value = self.__cf.get(self.__spiderSection, option) self.__options[option] = option_value except NoSectionError as exception: exp = exception except NoOptionError as exception: exp = exception except DuplicateSectionError as exception: exp = exception except Error as exception: exp = exception exp.message = exp.message + ', using the default option value for:' finally: if(type(exp) != Exception): logwarning(str(type(exp)) + ',' + exp.message + option) def getUrlListFile(self): ''' get the seed dir. ''' return self.__options['url_list_file'] def getOutputDir(self): ''' path to store the output the result. ''' return self.__options['output_directory'] def getMaxDepth(self): ''' the max crawl depth. ''' return int(self.__options['max_depth']) def getCrawlInterval(self): ''' ge the crawling interval. ''' return int(self.__options['crawl_interval']) def getTimeOut(self): ''' get timeout. ''' return int(self.__options['crawl_timeout']) def getTargetUrlPattern(self): ''' get the target url pattern. ''' return self.__options['target_url'] def getThreadCount(self): ''' get the max number of thread to crawl ''' return int(self.__options['thread_count']) def getEmail(self): ''' send the result to the specific email address,the email addresses should be separated by ';' ''' return self.__options['output_directory'] def __cur_file_dir(self): ''' get the script file path. ''' #script file path return sys.path[0] class Error(Exception): ''' Base class for SpiderConfigParser exceptions. ''' def _get_message(self): '''Getter for 'message'; needed only to override deprecation in BaseException. ''' return self.__message def _set_message(self, value): '''Setter for 'message'; needed only to override deprecation in BaseException. ''' self.__message = value message = property(_get_message, _set_message) def __init__(self, msg='error during parsing the config file'): self.message = msg Exception.__init__(self, msg) def __repr__(self): return self.message __str__ = __repr__ class NoConfigError(Error): ''' Raised when no configuration file has been loaded. ''' def __init__(self, path): Error.__init__(self, 'config file can not be found or read in the path: ' + path)
{ "content_hash": "8998fb1d439a63ac8fd7399b3c7387c9", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 109, "avg_line_length": 29.69090909090909, "alnum_prop": 0.5260257195345989, "repo_name": "onehao/opensource", "id": "ecd29cf0eaf5f1dae22a865e3e1c276afe1707fe", "size": "4929", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pyml/crawler/minispider/SpiderConfigParser.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "64" }, { "name": "C#", "bytes": "3517" }, { "name": "HTML", "bytes": "17382" }, { "name": "Java", "bytes": "1253532" }, { "name": "Python", "bytes": "635324" }, { "name": "XSLT", "bytes": "2464" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <title>Maruti Admin</title><meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="css/bootstrap.min.css" /> <link rel="stylesheet" href="css/bootstrap-responsive.min.css" /> <link rel="stylesheet" href="css/maruti-style.css" /> <link rel="stylesheet" href="css/maruti-media.css" class="skin-color" /> </head> <body> <!--Header-part--> <div id="header"> <h1><a href="dashboard.html">Maruti Admin</a></h1> </div> <!--close-Header-part--> <!--top-Header-messaages--> <div class="btn-group rightzero"> <a class="top_message tip-left" title="Manage Files"><i class="icon-file"></i></a> <a class="top_message tip-bottom" title="Manage Users"><i class="icon-user"></i></a> <a class="top_message tip-bottom" title="Manage Comments"><i class="icon-comment"></i><span class="label label-important">5</span></a> <a class="top_message tip-bottom" title="Manage Orders"><i class="icon-shopping-cart"></i></a> </div> <!--close-top-Header-messaages--> <!--top-Header-menu--> <div id="user-nav" class="navbar navbar-inverse"><ul class="nav"> <li class="" ><a title="" href="#"><i class="icon icon-user"></i> <span class="text">Profile</span></a></li> <li class=" dropdown" id="menu-messages"><a href="#" data-toggle="dropdown" data-target="#menu-messages" class="dropdown-toggle"><i class="icon icon-envelope"></i> <span class="text">Messages</span> <span class="label label-important">5</span> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a class="sAdd" title="" href="#">new message</a></li> <li><a class="sInbox" title="" href="#">inbox</a></li> <li><a class="sOutbox" title="" href="#">outbox</a></li> <li><a class="sTrash" title="" href="#">trash</a></li> </ul> </li> <li class=""><a title="" href="#"><i class="icon icon-cog"></i> <span class="text">Settings</span></a></li> <li class=""><a title="" href="login.html"><i class="icon icon-share-alt"></i> <span class="text">Logout</span></a></li> </ul> </div> <div id="search"> <input type="text" placeholder="Search here..."/> <button type="submit" class="tip-left" title="Search"><i class="icon-search icon-white"></i></button> </div> <!--close-top-Header-menu--> <div id="sidebar"> <a href="#" class="visible-phone"><i class="icon icon-file"></i> Gallery</a> <ul> <li class="active"><a href="index.html"><i class="icon icon-home"></i> <span>Dashboard</span></a></li> <li> <a href="charts.html"><i class="icon icon-signal"></i> <span>Charts &amp; graphs</span></a> </li> <li> <a href="widgets.html"><i class="icon icon-inbox"></i> <span>Widgets</span></a> </li> <li><a href="tables.html"><i class="icon icon-th"></i> <span>Tables</span></a></li> <li><a href="grid.html"><i class="icon icon-fullscreen"></i> <span>Full width</span></a></li> <li class="submenu"> <a href="#"><i class="icon icon-th-list"></i> <span>Forms</span> <span class="label">3</span></a> <ul> <li><a href="form-common.html">Basic Form</a></li> <li><a href="form-validation.html">Form with Validation</a></li> <li><a href="form-wizard.html">Form with Wizard</a></li> </ul> </li> <li><a href="buttons.html"><i class="icon icon-tint"></i> <span>Buttons &amp; icons</span></a></li> <li><a href="interface.html"><i class="icon icon-pencil"></i> <span>Eelements</span></a></li> <li class="submenu"> <a href="#"><i class="icon icon-file"></i> <span>Addons</span> <span class="label">3</span></a> <ul> <li><a href="gallery.html">Gallery</a></li> <li><a href="calendar.html">Calendar</a></li> <li><a href="chat.html">Chat option</a></li> </ul> </li> </ul> </div> <div id="content"> <div id="content-header"> <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="icon-home"></i> Home</a> <a href="#">Sample pages</a> <a href="#" class="current">Gallery</a> </div> <h1>Gallery</h1> </div> <div class="container-fluid"> <div class="row-fluid"> <div class="span12"> <div class="widget-box"> <div class="widget-title"> <span class="icon"> <i class="icon-picture"></i> </span> <h5>Gallery</h5> </div> <div class="widget-content"> <ul class="thumbnails"> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox3.jpg"> <img src="images/gallery/imgbox3.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox4.jpg"> <img src="images/gallery/imgbox4.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox5.jpg"> <img src="images/gallery/imgbox5.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox1.jpg"> <img src="images/gallery/imgbox1.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox2.jpg"> <img src="images/gallery/imgbox2.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox3.jpg"> <img src="images/gallery/imgbox3.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox4.jpg"> <img src="images/gallery/imgbox4.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox5.jpg"> <img src="images/gallery/imgbox5.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox1.jpg"> <img src="images/gallery/imgbox1.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox2.jpg"> <img src="images/gallery/imgbox2.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox3.jpg"> <img src="images/gallery/imgbox3.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox4.jpg"> <img src="images/gallery/imgbox4.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox5.jpg"> <img src="images/gallery/imgbox5.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox1.jpg"> <img src="images/gallery/imgbox1.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox2.jpg"> <img src="images/gallery/imgbox2.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox3.jpg"> <img src="images/gallery/imgbox3.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox4.jpg"> <img src="images/gallery/imgbox4.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span2"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox5.jpg"> <img src="images/gallery/imgbox5.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> </ul> <ul class="thumbnails"> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox1.jpg"> <img src="images/gallery/imgbox1.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox2.jpg"> <img src="images/gallery/imgbox2.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox3.jpg"> <img src="images/gallery/imgbox3.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox4.jpg"> <img src="images/gallery/imgbox4.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox5.jpg"> <img src="images/gallery/imgbox5.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox1.jpg"> <img src="images/gallery/imgbox1.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox2.jpg"> <img src="images/gallery/imgbox2.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox3.jpg"> <img src="images/gallery/imgbox3.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox4.jpg"> <img src="images/gallery/imgbox4.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox5.jpg"> <img src="images/gallery/imgbox5.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox1.jpg"> <img src="images/gallery/imgbox1.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox2.jpg"> <img src="images/gallery/imgbox2.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox3.jpg"> <img src="images/gallery/imgbox3.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox4.jpg"> <img src="images/gallery/imgbox4.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox5.jpg"> <img src="images/gallery/imgbox5.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox1.jpg"> <img src="images/gallery/imgbox1.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox2.jpg"> <img src="images/gallery/imgbox2.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox3.jpg"> <img src="images/gallery/imgbox3.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox4.jpg"> <img src="images/gallery/imgbox4.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox5.jpg"> <img src="images/gallery/imgbox5.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox1.jpg"> <img src="images/gallery/imgbox1.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox2.jpg"> <img src="images/gallery/imgbox2.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox3.jpg"> <img src="images/gallery/imgbox3.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox4.jpg"> <img src="images/gallery/imgbox4.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox5.jpg"> <img src="images/gallery/imgbox5.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox1.jpg"> <img src="images/gallery/imgbox1.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> <li class="span1"> <a class="thumbnail lightbox_trigger" href="images/gallery/imgbox2.jpg"> <img src="images/gallery/imgbox2.jpg" alt="" > </a> <div class="actions"> <a title="" href="#"><i class="icon-pencil icon-white"></i></a> <a title="" href="#"><i class="icon-remove icon-white"></i></a> </div> </li> </ul> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div id="footer" class="span12"> 2012 &copy; Marutii Admin. Brought to you by <a href="http://themedesigner.in">Themedesigner.in</a> </div> </div> <script src="js/jquery.min.js"></script> <script src="js/jquery.ui.custom.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/maruti.js"></script> </body> </html>
{ "content_hash": "f9daf11e1b2196b70cceab9a087387cf", "timestamp": "", "source": "github", "line_count": 554, "max_line_length": 438, "avg_line_length": 43.93682310469314, "alnum_prop": 0.48227270859866067, "repo_name": "ray0324/irayid", "id": "0946cb8e0df28a791db027172f876f14f940b444", "size": "24341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Public/HTML/gallery.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "10209" }, { "name": "CSS", "bytes": "309239" }, { "name": "JavaScript", "bytes": "1497485" }, { "name": "PHP", "bytes": "2485596" } ], "symlink_target": "" }
DEF_PRIMITIVE(bool_not) { RETURN_BOOL(!AS_BOOL(args[0])); } DEF_PRIMITIVE(bool_toString) { if (AS_BOOL(args[0])) { RETURN_VAL(CONST_STRING(vm, "true")); } else { RETURN_VAL(CONST_STRING(vm, "false")); } } DEF_PRIMITIVE(class_name) { RETURN_OBJ(AS_CLASS(args[0])->name); } DEF_PRIMITIVE(class_supertype) { ObjClass* classObj = AS_CLASS(args[0]); // Object has no superclass. if (classObj->superclass == NULL) RETURN_NULL; RETURN_OBJ(classObj->superclass); } DEF_PRIMITIVE(class_toString) { RETURN_OBJ(AS_CLASS(args[0])->name); } DEF_PRIMITIVE(class_attributes) { RETURN_VAL(AS_CLASS(args[0])->attributes); } DEF_PRIMITIVE(fiber_new) { if (!validateFn(vm, args[1], "Argument")) return false; ObjClosure* closure = AS_CLOSURE(args[1]); if (closure->fn->arity > 1) { RETURN_ERROR("Function cannot take more than one parameter."); } RETURN_OBJ(wrenNewFiber(vm, closure)); } DEF_PRIMITIVE(fiber_abort) { vm->fiber->error = args[1]; // If the error is explicitly null, it's not really an abort. return IS_NULL(args[1]); } // Transfer execution to [fiber] coming from the current fiber whose stack has // [args]. // // [isCall] is true if [fiber] is being called and not transferred. // // [hasValue] is true if a value in [args] is being passed to the new fiber. // Otherwise, `null` is implicitly being passed. static bool runFiber(WrenVM* vm, ObjFiber* fiber, Value* args, bool isCall, bool hasValue, const char* verb) { if (wrenHasError(fiber)) { RETURN_ERROR_FMT("Cannot $ an aborted fiber.", verb); } if (isCall) { // You can't call a called fiber, but you can transfer directly to it, // which is why this check is gated on `isCall`. This way, after resuming a // suspended fiber, it will run and then return to the fiber that called it // and so on. if (fiber->caller != NULL) RETURN_ERROR("Fiber has already been called."); if (fiber->state == FIBER_ROOT) RETURN_ERROR("Cannot call root fiber."); // Remember who ran it. fiber->caller = vm->fiber; } if (fiber->numFrames == 0) { RETURN_ERROR_FMT("Cannot $ a finished fiber.", verb); } // When the calling fiber resumes, we'll store the result of the call in its // stack. If the call has two arguments (the fiber and the value), we only // need one slot for the result, so discard the other slot now. if (hasValue) vm->fiber->stackTop--; if (fiber->numFrames == 1 && fiber->frames[0].ip == fiber->frames[0].closure->fn->code.data) { // The fiber is being started for the first time. If its function takes a // parameter, bind an argument to it. if (fiber->frames[0].closure->fn->arity == 1) { fiber->stackTop[0] = hasValue ? args[1] : NULL_VAL; fiber->stackTop++; } } else { // The fiber is being resumed, make yield() or transfer() return the result. fiber->stackTop[-1] = hasValue ? args[1] : NULL_VAL; } vm->fiber = fiber; return false; } DEF_PRIMITIVE(fiber_call) { return runFiber(vm, AS_FIBER(args[0]), args, true, false, "call"); } DEF_PRIMITIVE(fiber_call1) { return runFiber(vm, AS_FIBER(args[0]), args, true, true, "call"); } DEF_PRIMITIVE(fiber_current) { RETURN_OBJ(vm->fiber); } DEF_PRIMITIVE(fiber_error) { RETURN_VAL(AS_FIBER(args[0])->error); } DEF_PRIMITIVE(fiber_isDone) { ObjFiber* runFiber = AS_FIBER(args[0]); RETURN_BOOL(runFiber->numFrames == 0 || wrenHasError(runFiber)); } DEF_PRIMITIVE(fiber_suspend) { // Switching to a null fiber tells the interpreter to stop and exit. vm->fiber = NULL; vm->apiStack = NULL; return false; } DEF_PRIMITIVE(fiber_transfer) { return runFiber(vm, AS_FIBER(args[0]), args, false, false, "transfer to"); } DEF_PRIMITIVE(fiber_transfer1) { return runFiber(vm, AS_FIBER(args[0]), args, false, true, "transfer to"); } DEF_PRIMITIVE(fiber_transferError) { runFiber(vm, AS_FIBER(args[0]), args, false, true, "transfer to"); vm->fiber->error = args[1]; return false; } DEF_PRIMITIVE(fiber_try) { runFiber(vm, AS_FIBER(args[0]), args, true, false, "try"); // If we're switching to a valid fiber to try, remember that we're trying it. if (!wrenHasError(vm->fiber)) vm->fiber->state = FIBER_TRY; return false; } DEF_PRIMITIVE(fiber_try1) { runFiber(vm, AS_FIBER(args[0]), args, true, true, "try"); // If we're switching to a valid fiber to try, remember that we're trying it. if (!wrenHasError(vm->fiber)) vm->fiber->state = FIBER_TRY; return false; } DEF_PRIMITIVE(fiber_yield) { ObjFiber* current = vm->fiber; vm->fiber = current->caller; // Unhook this fiber from the one that called it. current->caller = NULL; current->state = FIBER_OTHER; if (vm->fiber != NULL) { // Make the caller's run method return null. vm->fiber->stackTop[-1] = NULL_VAL; } return false; } DEF_PRIMITIVE(fiber_yield1) { ObjFiber* current = vm->fiber; vm->fiber = current->caller; // Unhook this fiber from the one that called it. current->caller = NULL; current->state = FIBER_OTHER; if (vm->fiber != NULL) { // Make the caller's run method return the argument passed to yield. vm->fiber->stackTop[-1] = args[1]; // When the yielding fiber resumes, we'll store the result of the yield // call in its stack. Since Fiber.yield(value) has two arguments (the Fiber // class and the value) and we only need one slot for the result, discard // the other slot now. current->stackTop--; } return false; } DEF_PRIMITIVE(fn_new) { if (!validateFn(vm, args[1], "Argument")) return false; // The block argument is already a function, so just return it. RETURN_VAL(args[1]); } DEF_PRIMITIVE(fn_arity) { RETURN_NUM(AS_CLOSURE(args[0])->fn->arity); } static void call_fn(WrenVM* vm, Value* args, int numArgs) { // +1 to include the function itself. wrenCallFunction(vm, vm->fiber, AS_CLOSURE(args[0]), numArgs + 1); } #define DEF_FN_CALL(numArgs) \ DEF_PRIMITIVE(fn_call##numArgs) \ { \ call_fn(vm, args, numArgs); \ return false; \ } DEF_FN_CALL(0) DEF_FN_CALL(1) DEF_FN_CALL(2) DEF_FN_CALL(3) DEF_FN_CALL(4) DEF_FN_CALL(5) DEF_FN_CALL(6) DEF_FN_CALL(7) DEF_FN_CALL(8) DEF_FN_CALL(9) DEF_FN_CALL(10) DEF_FN_CALL(11) DEF_FN_CALL(12) DEF_FN_CALL(13) DEF_FN_CALL(14) DEF_FN_CALL(15) DEF_FN_CALL(16) DEF_PRIMITIVE(fn_toString) { RETURN_VAL(CONST_STRING(vm, "<fn>")); } // Creates a new list of size args[1], with all elements initialized to args[2]. DEF_PRIMITIVE(list_filled) { if (!validateInt(vm, args[1], "Size")) return false; if (AS_NUM(args[1]) < 0) RETURN_ERROR("Size cannot be negative."); uint32_t size = (uint32_t)AS_NUM(args[1]); ObjList* list = wrenNewList(vm, size); for (uint32_t i = 0; i < size; i++) { list->elements.data[i] = args[2]; } RETURN_OBJ(list); } DEF_PRIMITIVE(list_new) { RETURN_OBJ(wrenNewList(vm, 0)); } DEF_PRIMITIVE(list_add) { wrenValueBufferWrite(vm, &AS_LIST(args[0])->elements, args[1]); RETURN_VAL(args[1]); } // Adds an element to the list and then returns the list itself. This is called // by the compiler when compiling list literals instead of using add() to // minimize stack churn. DEF_PRIMITIVE(list_addCore) { wrenValueBufferWrite(vm, &AS_LIST(args[0])->elements, args[1]); // Return the list. RETURN_VAL(args[0]); } DEF_PRIMITIVE(list_clear) { wrenValueBufferClear(vm, &AS_LIST(args[0])->elements); RETURN_NULL; } DEF_PRIMITIVE(list_count) { RETURN_NUM(AS_LIST(args[0])->elements.count); } DEF_PRIMITIVE(list_insert) { ObjList* list = AS_LIST(args[0]); // count + 1 here so you can "insert" at the very end. uint32_t index = validateIndex(vm, args[1], list->elements.count + 1, "Index"); if (index == UINT32_MAX) return false; wrenListInsert(vm, list, args[2], index); RETURN_VAL(args[2]); } DEF_PRIMITIVE(list_iterate) { ObjList* list = AS_LIST(args[0]); // If we're starting the iteration, return the first index. if (IS_NULL(args[1])) { if (list->elements.count == 0) RETURN_FALSE; RETURN_NUM(0); } if (!validateInt(vm, args[1], "Iterator")) return false; // Stop if we're out of bounds. double index = AS_NUM(args[1]); if (index < 0 || index >= list->elements.count - 1) RETURN_FALSE; // Otherwise, move to the next index. RETURN_NUM(index + 1); } DEF_PRIMITIVE(list_iteratorValue) { ObjList* list = AS_LIST(args[0]); uint32_t index = validateIndex(vm, args[1], list->elements.count, "Iterator"); if (index == UINT32_MAX) return false; RETURN_VAL(list->elements.data[index]); } DEF_PRIMITIVE(list_removeAt) { ObjList* list = AS_LIST(args[0]); uint32_t index = validateIndex(vm, args[1], list->elements.count, "Index"); if (index == UINT32_MAX) return false; RETURN_VAL(wrenListRemoveAt(vm, list, index)); } DEF_PRIMITIVE(list_removeValue) { ObjList* list = AS_LIST(args[0]); int index = wrenListIndexOf(vm, list, args[1]); if(index == -1) RETURN_NULL; RETURN_VAL(wrenListRemoveAt(vm, list, index)); } DEF_PRIMITIVE(list_indexOf) { ObjList* list = AS_LIST(args[0]); RETURN_NUM(wrenListIndexOf(vm, list, args[1])); } DEF_PRIMITIVE(list_swap) { ObjList* list = AS_LIST(args[0]); uint32_t indexA = validateIndex(vm, args[1], list->elements.count, "Index 0"); if (indexA == UINT32_MAX) return false; uint32_t indexB = validateIndex(vm, args[2], list->elements.count, "Index 1"); if (indexB == UINT32_MAX) return false; Value a = list->elements.data[indexA]; list->elements.data[indexA] = list->elements.data[indexB]; list->elements.data[indexB] = a; RETURN_NULL; } DEF_PRIMITIVE(list_subscript) { ObjList* list = AS_LIST(args[0]); if (IS_NUM(args[1])) { uint32_t index = validateIndex(vm, args[1], list->elements.count, "Subscript"); if (index == UINT32_MAX) return false; RETURN_VAL(list->elements.data[index]); } if (!IS_RANGE(args[1])) { RETURN_ERROR("Subscript must be a number or a range."); } int step; uint32_t count = list->elements.count; uint32_t start = calculateRange(vm, AS_RANGE(args[1]), &count, &step); if (start == UINT32_MAX) return false; ObjList* result = wrenNewList(vm, count); for (uint32_t i = 0; i < count; i++) { result->elements.data[i] = list->elements.data[start + i * step]; } RETURN_OBJ(result); } DEF_PRIMITIVE(list_subscriptSetter) { ObjList* list = AS_LIST(args[0]); uint32_t index = validateIndex(vm, args[1], list->elements.count, "Subscript"); if (index == UINT32_MAX) return false; list->elements.data[index] = args[2]; RETURN_VAL(args[2]); } DEF_PRIMITIVE(map_new) { RETURN_OBJ(wrenNewMap(vm)); } DEF_PRIMITIVE(map_subscript) { if (!validateKey(vm, args[1])) return false; ObjMap* map = AS_MAP(args[0]); Value value = wrenMapGet(map, args[1]); if (IS_UNDEFINED(value)) RETURN_NULL; RETURN_VAL(value); } DEF_PRIMITIVE(map_subscriptSetter) { if (!validateKey(vm, args[1])) return false; wrenMapSet(vm, AS_MAP(args[0]), args[1], args[2]); RETURN_VAL(args[2]); } // Adds an entry to the map and then returns the map itself. This is called by // the compiler when compiling map literals instead of using [_]=(_) to // minimize stack churn. DEF_PRIMITIVE(map_addCore) { if (!validateKey(vm, args[1])) return false; wrenMapSet(vm, AS_MAP(args[0]), args[1], args[2]); // Return the map itself. RETURN_VAL(args[0]); } DEF_PRIMITIVE(map_clear) { wrenMapClear(vm, AS_MAP(args[0])); RETURN_NULL; } DEF_PRIMITIVE(map_containsKey) { if (!validateKey(vm, args[1])) return false; RETURN_BOOL(!IS_UNDEFINED(wrenMapGet(AS_MAP(args[0]), args[1]))); } DEF_PRIMITIVE(map_count) { RETURN_NUM(AS_MAP(args[0])->count); } DEF_PRIMITIVE(map_iterate) { ObjMap* map = AS_MAP(args[0]); if (map->count == 0) RETURN_FALSE; // If we're starting the iteration, start at the first used entry. uint32_t index = 0; // Otherwise, start one past the last entry we stopped at. if (!IS_NULL(args[1])) { if (!validateInt(vm, args[1], "Iterator")) return false; if (AS_NUM(args[1]) < 0) RETURN_FALSE; index = (uint32_t)AS_NUM(args[1]); if (index >= map->capacity) RETURN_FALSE; // Advance the iterator. index++; } // Find a used entry, if any. for (; index < map->capacity; index++) { if (!IS_UNDEFINED(map->entries[index].key)) RETURN_NUM(index); } // If we get here, walked all of the entries. RETURN_FALSE; } DEF_PRIMITIVE(map_remove) { if (!validateKey(vm, args[1])) return false; RETURN_VAL(wrenMapRemoveKey(vm, AS_MAP(args[0]), args[1])); } DEF_PRIMITIVE(map_keyIteratorValue) { ObjMap* map = AS_MAP(args[0]); uint32_t index = validateIndex(vm, args[1], map->capacity, "Iterator"); if (index == UINT32_MAX) return false; MapEntry* entry = &map->entries[index]; if (IS_UNDEFINED(entry->key)) { RETURN_ERROR("Invalid map iterator."); } RETURN_VAL(entry->key); } DEF_PRIMITIVE(map_valueIteratorValue) { ObjMap* map = AS_MAP(args[0]); uint32_t index = validateIndex(vm, args[1], map->capacity, "Iterator"); if (index == UINT32_MAX) return false; MapEntry* entry = &map->entries[index]; if (IS_UNDEFINED(entry->key)) { RETURN_ERROR("Invalid map iterator."); } RETURN_VAL(entry->value); } DEF_PRIMITIVE(null_not) { RETURN_VAL(TRUE_VAL); } DEF_PRIMITIVE(null_toString) { RETURN_VAL(CONST_STRING(vm, "null")); } DEF_PRIMITIVE(num_fromString) { if (!validateString(vm, args[1], "Argument")) return false; ObjString* string = AS_STRING(args[1]); // Corner case: Can't parse an empty string. if (string->length == 0) RETURN_NULL; errno = 0; char* end; double number = strtod(string->value, &end); // Skip past any trailing whitespace. while (*end != '\0' && isspace((unsigned char)*end)) end++; if (errno == ERANGE) RETURN_ERROR("Number literal is too large."); // We must have consumed the entire string. Otherwise, it contains non-number // characters and we can't parse it. if (end < string->value + string->length) RETURN_NULL; RETURN_NUM(number); } // Defines a primitive on Num that calls infix [op] and returns [type]. #define DEF_NUM_CONSTANT(name, value) \ DEF_PRIMITIVE(num_##name) \ { \ RETURN_NUM(value); \ } DEF_NUM_CONSTANT(infinity, INFINITY) DEF_NUM_CONSTANT(nan, WREN_DOUBLE_NAN) DEF_NUM_CONSTANT(pi, 3.14159265358979323846264338327950288) DEF_NUM_CONSTANT(tau, 6.28318530717958647692528676655900577) DEF_NUM_CONSTANT(largest, DBL_MAX) DEF_NUM_CONSTANT(smallest, DBL_MIN) DEF_NUM_CONSTANT(maxSafeInteger, 9007199254740991.0) DEF_NUM_CONSTANT(minSafeInteger, -9007199254740991.0) // Defines a primitive on Num that calls infix [op] and returns [type]. #define DEF_NUM_INFIX(name, op, type) \ DEF_PRIMITIVE(num_##name) \ { \ if (!validateNum(vm, args[1], "Right operand")) return false; \ RETURN_##type(AS_NUM(args[0]) op AS_NUM(args[1])); \ } DEF_NUM_INFIX(minus, -, NUM) DEF_NUM_INFIX(plus, +, NUM) DEF_NUM_INFIX(multiply, *, NUM) DEF_NUM_INFIX(divide, /, NUM) DEF_NUM_INFIX(lt, <, BOOL) DEF_NUM_INFIX(gt, >, BOOL) DEF_NUM_INFIX(lte, <=, BOOL) DEF_NUM_INFIX(gte, >=, BOOL) // Defines a primitive on Num that call infix bitwise [op]. #define DEF_NUM_BITWISE(name, op) \ DEF_PRIMITIVE(num_bitwise##name) \ { \ if (!validateNum(vm, args[1], "Right operand")) return false; \ uint32_t left = (uint32_t)AS_NUM(args[0]); \ uint32_t right = (uint32_t)AS_NUM(args[1]); \ RETURN_NUM(left op right); \ } DEF_NUM_BITWISE(And, &) DEF_NUM_BITWISE(Or, |) DEF_NUM_BITWISE(Xor, ^) DEF_NUM_BITWISE(LeftShift, <<) DEF_NUM_BITWISE(RightShift, >>) // Defines a primitive method on Num that returns the result of [fn]. #define DEF_NUM_FN(name, fn) \ DEF_PRIMITIVE(num_##name) \ { \ RETURN_NUM(fn(AS_NUM(args[0]))); \ } DEF_NUM_FN(abs, fabs) DEF_NUM_FN(acos, acos) DEF_NUM_FN(asin, asin) DEF_NUM_FN(atan, atan) DEF_NUM_FN(cbrt, cbrt) DEF_NUM_FN(ceil, ceil) DEF_NUM_FN(cos, cos) DEF_NUM_FN(floor, floor) DEF_NUM_FN(negate, -) DEF_NUM_FN(round, round) DEF_NUM_FN(sin, sin) DEF_NUM_FN(sqrt, sqrt) DEF_NUM_FN(tan, tan) DEF_NUM_FN(log, log) DEF_NUM_FN(log2, log2) DEF_NUM_FN(exp, exp) DEF_PRIMITIVE(num_mod) { if (!validateNum(vm, args[1], "Right operand")) return false; RETURN_NUM(fmod(AS_NUM(args[0]), AS_NUM(args[1]))); } DEF_PRIMITIVE(num_eqeq) { if (!IS_NUM(args[1])) RETURN_FALSE; RETURN_BOOL(AS_NUM(args[0]) == AS_NUM(args[1])); } DEF_PRIMITIVE(num_bangeq) { if (!IS_NUM(args[1])) RETURN_TRUE; RETURN_BOOL(AS_NUM(args[0]) != AS_NUM(args[1])); } DEF_PRIMITIVE(num_bitwiseNot) { // Bitwise operators always work on 32-bit unsigned ints. RETURN_NUM(~(uint32_t)AS_NUM(args[0])); } DEF_PRIMITIVE(num_dotDot) { if (!validateNum(vm, args[1], "Right hand side of range")) return false; double from = AS_NUM(args[0]); double to = AS_NUM(args[1]); RETURN_VAL(wrenNewRange(vm, from, to, true)); } DEF_PRIMITIVE(num_dotDotDot) { if (!validateNum(vm, args[1], "Right hand side of range")) return false; double from = AS_NUM(args[0]); double to = AS_NUM(args[1]); RETURN_VAL(wrenNewRange(vm, from, to, false)); } DEF_PRIMITIVE(num_atan2) { if (!validateNum(vm, args[1], "x value")) return false; RETURN_NUM(atan2(AS_NUM(args[0]), AS_NUM(args[1]))); } DEF_PRIMITIVE(num_min) { if (!validateNum(vm, args[1], "Other value")) return false; double value = AS_NUM(args[0]); double other = AS_NUM(args[1]); RETURN_NUM(value <= other ? value : other); } DEF_PRIMITIVE(num_max) { if (!validateNum(vm, args[1], "Other value")) return false; double value = AS_NUM(args[0]); double other = AS_NUM(args[1]); RETURN_NUM(value > other ? value : other); } DEF_PRIMITIVE(num_clamp) { if (!validateNum(vm, args[1], "Min value")) return false; if (!validateNum(vm, args[2], "Max value")) return false; double value = AS_NUM(args[0]); double min = AS_NUM(args[1]); double max = AS_NUM(args[2]); double result = (value < min) ? min : ((value > max) ? max : value); RETURN_NUM(result); } DEF_PRIMITIVE(num_pow) { if (!validateNum(vm, args[1], "Power value")) return false; RETURN_NUM(pow(AS_NUM(args[0]), AS_NUM(args[1]))); } DEF_PRIMITIVE(num_fraction) { double unused; RETURN_NUM(modf(AS_NUM(args[0]) , &unused)); } DEF_PRIMITIVE(num_isInfinity) { RETURN_BOOL(isinf(AS_NUM(args[0]))); } DEF_PRIMITIVE(num_isInteger) { double value = AS_NUM(args[0]); if (isnan(value) || isinf(value)) RETURN_FALSE; RETURN_BOOL(trunc(value) == value); } DEF_PRIMITIVE(num_isNan) { RETURN_BOOL(isnan(AS_NUM(args[0]))); } DEF_PRIMITIVE(num_sign) { double value = AS_NUM(args[0]); if (value > 0) { RETURN_NUM(1); } else if (value < 0) { RETURN_NUM(-1); } else { RETURN_NUM(0); } } DEF_PRIMITIVE(num_toString) { RETURN_VAL(wrenNumToString(vm, AS_NUM(args[0]))); } DEF_PRIMITIVE(num_truncate) { double integer; modf(AS_NUM(args[0]) , &integer); RETURN_NUM(integer); } DEF_PRIMITIVE(object_same) { RETURN_BOOL(wrenValuesEqual(args[1], args[2])); } DEF_PRIMITIVE(object_not) { RETURN_VAL(FALSE_VAL); } DEF_PRIMITIVE(object_eqeq) { RETURN_BOOL(wrenValuesEqual(args[0], args[1])); } DEF_PRIMITIVE(object_bangeq) { RETURN_BOOL(!wrenValuesEqual(args[0], args[1])); } DEF_PRIMITIVE(object_is) { if (!IS_CLASS(args[1])) { RETURN_ERROR("Right operand must be a class."); } ObjClass *classObj = wrenGetClass(vm, args[0]); ObjClass *baseClassObj = AS_CLASS(args[1]); // Walk the superclass chain looking for the class. do { if (baseClassObj == classObj) RETURN_BOOL(true); classObj = classObj->superclass; } while (classObj != NULL); RETURN_BOOL(false); } DEF_PRIMITIVE(object_toString) { Obj* obj = AS_OBJ(args[0]); Value name = OBJ_VAL(obj->classObj->name); RETURN_VAL(wrenStringFormat(vm, "instance of @", name)); } DEF_PRIMITIVE(object_type) { RETURN_OBJ(wrenGetClass(vm, args[0])); } DEF_PRIMITIVE(range_from) { RETURN_NUM(AS_RANGE(args[0])->from); } DEF_PRIMITIVE(range_to) { RETURN_NUM(AS_RANGE(args[0])->to); } DEF_PRIMITIVE(range_min) { ObjRange* range = AS_RANGE(args[0]); RETURN_NUM(fmin(range->from, range->to)); } DEF_PRIMITIVE(range_max) { ObjRange* range = AS_RANGE(args[0]); RETURN_NUM(fmax(range->from, range->to)); } DEF_PRIMITIVE(range_isInclusive) { RETURN_BOOL(AS_RANGE(args[0])->isInclusive); } DEF_PRIMITIVE(range_iterate) { ObjRange* range = AS_RANGE(args[0]); // Special case: empty range. if (range->from == range->to && !range->isInclusive) RETURN_FALSE; // Start the iteration. if (IS_NULL(args[1])) RETURN_NUM(range->from); if (!validateNum(vm, args[1], "Iterator")) return false; double iterator = AS_NUM(args[1]); // Iterate towards [to] from [from]. if (range->from < range->to) { iterator++; if (iterator > range->to) RETURN_FALSE; } else { iterator--; if (iterator < range->to) RETURN_FALSE; } if (!range->isInclusive && iterator == range->to) RETURN_FALSE; RETURN_NUM(iterator); } DEF_PRIMITIVE(range_iteratorValue) { // Assume the iterator is a number so that is the value of the range. RETURN_VAL(args[1]); } DEF_PRIMITIVE(range_toString) { ObjRange* range = AS_RANGE(args[0]); Value from = wrenNumToString(vm, range->from); wrenPushRoot(vm, AS_OBJ(from)); Value to = wrenNumToString(vm, range->to); wrenPushRoot(vm, AS_OBJ(to)); Value result = wrenStringFormat(vm, "@$@", from, range->isInclusive ? ".." : "...", to); wrenPopRoot(vm); wrenPopRoot(vm); RETURN_VAL(result); } DEF_PRIMITIVE(string_fromCodePoint) { if (!validateInt(vm, args[1], "Code point")) return false; int codePoint = (int)AS_NUM(args[1]); if (codePoint < 0) { RETURN_ERROR("Code point cannot be negative."); } else if (codePoint > 0x10ffff) { RETURN_ERROR("Code point cannot be greater than 0x10ffff."); } RETURN_VAL(wrenStringFromCodePoint(vm, codePoint)); } DEF_PRIMITIVE(string_fromByte) { if (!validateInt(vm, args[1], "Byte")) return false; int byte = (int) AS_NUM(args[1]); if (byte < 0) { RETURN_ERROR("Byte cannot be negative."); } else if (byte > 0xff) { RETURN_ERROR("Byte cannot be greater than 0xff."); } RETURN_VAL(wrenStringFromByte(vm, (uint8_t) byte)); } DEF_PRIMITIVE(string_byteAt) { ObjString* string = AS_STRING(args[0]); uint32_t index = validateIndex(vm, args[1], string->length, "Index"); if (index == UINT32_MAX) return false; RETURN_NUM((uint8_t)string->value[index]); } DEF_PRIMITIVE(string_byteCount) { RETURN_NUM(AS_STRING(args[0])->length); } DEF_PRIMITIVE(string_codePointAt) { ObjString* string = AS_STRING(args[0]); uint32_t index = validateIndex(vm, args[1], string->length, "Index"); if (index == UINT32_MAX) return false; // If we are in the middle of a UTF-8 sequence, indicate that. const uint8_t* bytes = (uint8_t*)string->value; if ((bytes[index] & 0xc0) == 0x80) RETURN_NUM(-1); // Decode the UTF-8 sequence. RETURN_NUM(wrenUtf8Decode((uint8_t*)string->value + index, string->length - index)); } DEF_PRIMITIVE(string_contains) { if (!validateString(vm, args[1], "Argument")) return false; ObjString* string = AS_STRING(args[0]); ObjString* search = AS_STRING(args[1]); RETURN_BOOL(wrenStringFind(string, search, 0) != UINT32_MAX); } DEF_PRIMITIVE(string_endsWith) { if (!validateString(vm, args[1], "Argument")) return false; ObjString* string = AS_STRING(args[0]); ObjString* search = AS_STRING(args[1]); // Edge case: If the search string is longer then return false right away. if (search->length > string->length) RETURN_FALSE; RETURN_BOOL(memcmp(string->value + string->length - search->length, search->value, search->length) == 0); } DEF_PRIMITIVE(string_indexOf1) { if (!validateString(vm, args[1], "Argument")) return false; ObjString* string = AS_STRING(args[0]); ObjString* search = AS_STRING(args[1]); uint32_t index = wrenStringFind(string, search, 0); RETURN_NUM(index == UINT32_MAX ? -1 : (int)index); } DEF_PRIMITIVE(string_indexOf2) { if (!validateString(vm, args[1], "Argument")) return false; ObjString* string = AS_STRING(args[0]); ObjString* search = AS_STRING(args[1]); uint32_t start = validateIndex(vm, args[2], string->length, "Start"); if (start == UINT32_MAX) return false; uint32_t index = wrenStringFind(string, search, start); RETURN_NUM(index == UINT32_MAX ? -1 : (int)index); } DEF_PRIMITIVE(string_iterate) { ObjString* string = AS_STRING(args[0]); // If we're starting the iteration, return the first index. if (IS_NULL(args[1])) { if (string->length == 0) RETURN_FALSE; RETURN_NUM(0); } if (!validateInt(vm, args[1], "Iterator")) return false; if (AS_NUM(args[1]) < 0) RETURN_FALSE; uint32_t index = (uint32_t)AS_NUM(args[1]); // Advance to the beginning of the next UTF-8 sequence. do { index++; if (index >= string->length) RETURN_FALSE; } while ((string->value[index] & 0xc0) == 0x80); RETURN_NUM(index); } DEF_PRIMITIVE(string_iterateByte) { ObjString* string = AS_STRING(args[0]); // If we're starting the iteration, return the first index. if (IS_NULL(args[1])) { if (string->length == 0) RETURN_FALSE; RETURN_NUM(0); } if (!validateInt(vm, args[1], "Iterator")) return false; if (AS_NUM(args[1]) < 0) RETURN_FALSE; uint32_t index = (uint32_t)AS_NUM(args[1]); // Advance to the next byte. index++; if (index >= string->length) RETURN_FALSE; RETURN_NUM(index); } DEF_PRIMITIVE(string_iteratorValue) { ObjString* string = AS_STRING(args[0]); uint32_t index = validateIndex(vm, args[1], string->length, "Iterator"); if (index == UINT32_MAX) return false; RETURN_VAL(wrenStringCodePointAt(vm, string, index)); } DEF_PRIMITIVE(string_startsWith) { if (!validateString(vm, args[1], "Argument")) return false; ObjString* string = AS_STRING(args[0]); ObjString* search = AS_STRING(args[1]); // Edge case: If the search string is longer then return false right away. if (search->length > string->length) RETURN_FALSE; RETURN_BOOL(memcmp(string->value, search->value, search->length) == 0); } DEF_PRIMITIVE(string_plus) { if (!validateString(vm, args[1], "Right operand")) return false; RETURN_VAL(wrenStringFormat(vm, "@@", args[0], args[1])); } DEF_PRIMITIVE(string_subscript) { ObjString* string = AS_STRING(args[0]); if (IS_NUM(args[1])) { int index = validateIndex(vm, args[1], string->length, "Subscript"); if (index == -1) return false; RETURN_VAL(wrenStringCodePointAt(vm, string, index)); } if (!IS_RANGE(args[1])) { RETURN_ERROR("Subscript must be a number or a range."); } int step; uint32_t count = string->length; int start = calculateRange(vm, AS_RANGE(args[1]), &count, &step); if (start == -1) return false; RETURN_VAL(wrenNewStringFromRange(vm, string, start, count, step)); } DEF_PRIMITIVE(string_toString) { RETURN_VAL(args[0]); } DEF_PRIMITIVE(system_clock) { RETURN_NUM((double)clock() / CLOCKS_PER_SEC); } DEF_PRIMITIVE(system_gc) { wrenCollectGarbage(vm); RETURN_NULL; } DEF_PRIMITIVE(system_writeString) { if (vm->config.writeFn != NULL) { vm->config.writeFn(vm, AS_CSTRING(args[1])); } RETURN_VAL(args[1]); } // Creates either the Object or Class class in the core module with [name]. static ObjClass* defineClass(WrenVM* vm, ObjModule* module, const char* name) { ObjString* nameString = AS_STRING(wrenNewString(vm, name)); wrenPushRoot(vm, (Obj*)nameString); ObjClass* classObj = wrenNewSingleClass(vm, 0, nameString); wrenDefineVariable(vm, module, name, nameString->length, OBJ_VAL(classObj), NULL); wrenPopRoot(vm); return classObj; } void wrenInitializeCore(WrenVM* vm) { ObjModule* coreModule = wrenNewModule(vm, NULL); wrenPushRoot(vm, (Obj*)coreModule); // The core module's key is null in the module map. wrenMapSet(vm, vm->modules, NULL_VAL, OBJ_VAL(coreModule)); wrenPopRoot(vm); // coreModule. // Define the root Object class. This has to be done a little specially // because it has no superclass. vm->objectClass = defineClass(vm, coreModule, "Object"); PRIMITIVE(vm->objectClass, "!", object_not); PRIMITIVE(vm->objectClass, "==(_)", object_eqeq); PRIMITIVE(vm->objectClass, "!=(_)", object_bangeq); PRIMITIVE(vm->objectClass, "is(_)", object_is); PRIMITIVE(vm->objectClass, "toString", object_toString); PRIMITIVE(vm->objectClass, "type", object_type); // Now we can define Class, which is a subclass of Object. vm->classClass = defineClass(vm, coreModule, "Class"); wrenBindSuperclass(vm, vm->classClass, vm->objectClass); PRIMITIVE(vm->classClass, "name", class_name); PRIMITIVE(vm->classClass, "supertype", class_supertype); PRIMITIVE(vm->classClass, "toString", class_toString); PRIMITIVE(vm->classClass, "attributes", class_attributes); // Finally, we can define Object's metaclass which is a subclass of Class. ObjClass* objectMetaclass = defineClass(vm, coreModule, "Object metaclass"); // Wire up the metaclass relationships now that all three classes are built. vm->objectClass->obj.classObj = objectMetaclass; objectMetaclass->obj.classObj = vm->classClass; vm->classClass->obj.classObj = vm->classClass; // Do this after wiring up the metaclasses so objectMetaclass doesn't get // collected. wrenBindSuperclass(vm, objectMetaclass, vm->classClass); PRIMITIVE(objectMetaclass, "same(_,_)", object_same); // The core class diagram ends up looking like this, where single lines point // to a class's superclass, and double lines point to its metaclass: // // .------------------------------------. .====. // | .---------------. | # # // v | v | v # // .---------. .-------------------. .-------. # // | Object |==>| Object metaclass |==>| Class |==" // '---------' '-------------------' '-------' // ^ ^ ^ ^ ^ // | .--------------' # | # // | | # | # // .---------. .-------------------. # | # -. // | Base |==>| Base metaclass |======" | # | // '---------' '-------------------' | # | // ^ | # | // | .------------------' # | Example classes // | | # | // .---------. .-------------------. # | // | Derived |==>| Derived metaclass |==========" | // '---------' '-------------------' -' // The rest of the classes can now be defined normally. wrenInterpret(vm, NULL, coreModuleSource); vm->boolClass = AS_CLASS(wrenFindVariable(vm, coreModule, "Bool")); PRIMITIVE(vm->boolClass, "toString", bool_toString); PRIMITIVE(vm->boolClass, "!", bool_not); vm->fiberClass = AS_CLASS(wrenFindVariable(vm, coreModule, "Fiber")); PRIMITIVE(vm->fiberClass->obj.classObj, "new(_)", fiber_new); PRIMITIVE(vm->fiberClass->obj.classObj, "abort(_)", fiber_abort); PRIMITIVE(vm->fiberClass->obj.classObj, "current", fiber_current); PRIMITIVE(vm->fiberClass->obj.classObj, "suspend()", fiber_suspend); PRIMITIVE(vm->fiberClass->obj.classObj, "yield()", fiber_yield); PRIMITIVE(vm->fiberClass->obj.classObj, "yield(_)", fiber_yield1); PRIMITIVE(vm->fiberClass, "call()", fiber_call); PRIMITIVE(vm->fiberClass, "call(_)", fiber_call1); PRIMITIVE(vm->fiberClass, "error", fiber_error); PRIMITIVE(vm->fiberClass, "isDone", fiber_isDone); PRIMITIVE(vm->fiberClass, "transfer()", fiber_transfer); PRIMITIVE(vm->fiberClass, "transfer(_)", fiber_transfer1); PRIMITIVE(vm->fiberClass, "transferError(_)", fiber_transferError); PRIMITIVE(vm->fiberClass, "try()", fiber_try); PRIMITIVE(vm->fiberClass, "try(_)", fiber_try1); vm->fnClass = AS_CLASS(wrenFindVariable(vm, coreModule, "Fn")); PRIMITIVE(vm->fnClass->obj.classObj, "new(_)", fn_new); PRIMITIVE(vm->fnClass, "arity", fn_arity); FUNCTION_CALL(vm->fnClass, "call()", fn_call0); FUNCTION_CALL(vm->fnClass, "call(_)", fn_call1); FUNCTION_CALL(vm->fnClass, "call(_,_)", fn_call2); FUNCTION_CALL(vm->fnClass, "call(_,_,_)", fn_call3); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_)", fn_call4); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_)", fn_call5); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_)", fn_call6); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_,_)", fn_call7); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_,_,_)", fn_call8); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_,_,_,_)", fn_call9); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_,_,_,_,_)", fn_call10); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_,_,_,_,_,_)", fn_call11); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_,_,_,_,_,_,_)", fn_call12); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_,_,_,_,_,_,_,_)", fn_call13); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_,_,_,_,_,_,_,_,_)", fn_call14); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_,_,_,_,_,_,_,_,_,_)", fn_call15); FUNCTION_CALL(vm->fnClass, "call(_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_)", fn_call16); PRIMITIVE(vm->fnClass, "toString", fn_toString); vm->nullClass = AS_CLASS(wrenFindVariable(vm, coreModule, "Null")); PRIMITIVE(vm->nullClass, "!", null_not); PRIMITIVE(vm->nullClass, "toString", null_toString); vm->numClass = AS_CLASS(wrenFindVariable(vm, coreModule, "Num")); PRIMITIVE(vm->numClass->obj.classObj, "fromString(_)", num_fromString); PRIMITIVE(vm->numClass->obj.classObj, "infinity", num_infinity); PRIMITIVE(vm->numClass->obj.classObj, "nan", num_nan); PRIMITIVE(vm->numClass->obj.classObj, "pi", num_pi); PRIMITIVE(vm->numClass->obj.classObj, "tau", num_tau); PRIMITIVE(vm->numClass->obj.classObj, "largest", num_largest); PRIMITIVE(vm->numClass->obj.classObj, "smallest", num_smallest); PRIMITIVE(vm->numClass->obj.classObj, "maxSafeInteger", num_maxSafeInteger); PRIMITIVE(vm->numClass->obj.classObj, "minSafeInteger", num_minSafeInteger); PRIMITIVE(vm->numClass, "-(_)", num_minus); PRIMITIVE(vm->numClass, "+(_)", num_plus); PRIMITIVE(vm->numClass, "*(_)", num_multiply); PRIMITIVE(vm->numClass, "/(_)", num_divide); PRIMITIVE(vm->numClass, "<(_)", num_lt); PRIMITIVE(vm->numClass, ">(_)", num_gt); PRIMITIVE(vm->numClass, "<=(_)", num_lte); PRIMITIVE(vm->numClass, ">=(_)", num_gte); PRIMITIVE(vm->numClass, "&(_)", num_bitwiseAnd); PRIMITIVE(vm->numClass, "|(_)", num_bitwiseOr); PRIMITIVE(vm->numClass, "^(_)", num_bitwiseXor); PRIMITIVE(vm->numClass, "<<(_)", num_bitwiseLeftShift); PRIMITIVE(vm->numClass, ">>(_)", num_bitwiseRightShift); PRIMITIVE(vm->numClass, "abs", num_abs); PRIMITIVE(vm->numClass, "acos", num_acos); PRIMITIVE(vm->numClass, "asin", num_asin); PRIMITIVE(vm->numClass, "atan", num_atan); PRIMITIVE(vm->numClass, "cbrt", num_cbrt); PRIMITIVE(vm->numClass, "ceil", num_ceil); PRIMITIVE(vm->numClass, "cos", num_cos); PRIMITIVE(vm->numClass, "floor", num_floor); PRIMITIVE(vm->numClass, "-", num_negate); PRIMITIVE(vm->numClass, "round", num_round); PRIMITIVE(vm->numClass, "min(_)", num_min); PRIMITIVE(vm->numClass, "max(_)", num_max); PRIMITIVE(vm->numClass, "clamp(_,_)", num_clamp); PRIMITIVE(vm->numClass, "sin", num_sin); PRIMITIVE(vm->numClass, "sqrt", num_sqrt); PRIMITIVE(vm->numClass, "tan", num_tan); PRIMITIVE(vm->numClass, "log", num_log); PRIMITIVE(vm->numClass, "log2", num_log2); PRIMITIVE(vm->numClass, "exp", num_exp); PRIMITIVE(vm->numClass, "%(_)", num_mod); PRIMITIVE(vm->numClass, "~", num_bitwiseNot); PRIMITIVE(vm->numClass, "..(_)", num_dotDot); PRIMITIVE(vm->numClass, "...(_)", num_dotDotDot); PRIMITIVE(vm->numClass, "atan(_)", num_atan2); PRIMITIVE(vm->numClass, "pow(_)", num_pow); PRIMITIVE(vm->numClass, "fraction", num_fraction); PRIMITIVE(vm->numClass, "isInfinity", num_isInfinity); PRIMITIVE(vm->numClass, "isInteger", num_isInteger); PRIMITIVE(vm->numClass, "isNan", num_isNan); PRIMITIVE(vm->numClass, "sign", num_sign); PRIMITIVE(vm->numClass, "toString", num_toString); PRIMITIVE(vm->numClass, "truncate", num_truncate); // These are defined just so that 0 and -0 are equal, which is specified by // IEEE 754 even though they have different bit representations. PRIMITIVE(vm->numClass, "==(_)", num_eqeq); PRIMITIVE(vm->numClass, "!=(_)", num_bangeq); vm->stringClass = AS_CLASS(wrenFindVariable(vm, coreModule, "String")); PRIMITIVE(vm->stringClass->obj.classObj, "fromCodePoint(_)", string_fromCodePoint); PRIMITIVE(vm->stringClass->obj.classObj, "fromByte(_)", string_fromByte); PRIMITIVE(vm->stringClass, "+(_)", string_plus); PRIMITIVE(vm->stringClass, "[_]", string_subscript); PRIMITIVE(vm->stringClass, "byteAt_(_)", string_byteAt); PRIMITIVE(vm->stringClass, "byteCount_", string_byteCount); PRIMITIVE(vm->stringClass, "codePointAt_(_)", string_codePointAt); PRIMITIVE(vm->stringClass, "contains(_)", string_contains); PRIMITIVE(vm->stringClass, "endsWith(_)", string_endsWith); PRIMITIVE(vm->stringClass, "indexOf(_)", string_indexOf1); PRIMITIVE(vm->stringClass, "indexOf(_,_)", string_indexOf2); PRIMITIVE(vm->stringClass, "iterate(_)", string_iterate); PRIMITIVE(vm->stringClass, "iterateByte_(_)", string_iterateByte); PRIMITIVE(vm->stringClass, "iteratorValue(_)", string_iteratorValue); PRIMITIVE(vm->stringClass, "startsWith(_)", string_startsWith); PRIMITIVE(vm->stringClass, "toString", string_toString); vm->listClass = AS_CLASS(wrenFindVariable(vm, coreModule, "List")); PRIMITIVE(vm->listClass->obj.classObj, "filled(_,_)", list_filled); PRIMITIVE(vm->listClass->obj.classObj, "new()", list_new); PRIMITIVE(vm->listClass, "[_]", list_subscript); PRIMITIVE(vm->listClass, "[_]=(_)", list_subscriptSetter); PRIMITIVE(vm->listClass, "add(_)", list_add); PRIMITIVE(vm->listClass, "addCore_(_)", list_addCore); PRIMITIVE(vm->listClass, "clear()", list_clear); PRIMITIVE(vm->listClass, "count", list_count); PRIMITIVE(vm->listClass, "insert(_,_)", list_insert); PRIMITIVE(vm->listClass, "iterate(_)", list_iterate); PRIMITIVE(vm->listClass, "iteratorValue(_)", list_iteratorValue); PRIMITIVE(vm->listClass, "removeAt(_)", list_removeAt); PRIMITIVE(vm->listClass, "remove(_)", list_removeValue); PRIMITIVE(vm->listClass, "indexOf(_)", list_indexOf); PRIMITIVE(vm->listClass, "swap(_,_)", list_swap); vm->mapClass = AS_CLASS(wrenFindVariable(vm, coreModule, "Map")); PRIMITIVE(vm->mapClass->obj.classObj, "new()", map_new); PRIMITIVE(vm->mapClass, "[_]", map_subscript); PRIMITIVE(vm->mapClass, "[_]=(_)", map_subscriptSetter); PRIMITIVE(vm->mapClass, "addCore_(_,_)", map_addCore); PRIMITIVE(vm->mapClass, "clear()", map_clear); PRIMITIVE(vm->mapClass, "containsKey(_)", map_containsKey); PRIMITIVE(vm->mapClass, "count", map_count); PRIMITIVE(vm->mapClass, "remove(_)", map_remove); PRIMITIVE(vm->mapClass, "iterate(_)", map_iterate); PRIMITIVE(vm->mapClass, "keyIteratorValue_(_)", map_keyIteratorValue); PRIMITIVE(vm->mapClass, "valueIteratorValue_(_)", map_valueIteratorValue); vm->rangeClass = AS_CLASS(wrenFindVariable(vm, coreModule, "Range")); PRIMITIVE(vm->rangeClass, "from", range_from); PRIMITIVE(vm->rangeClass, "to", range_to); PRIMITIVE(vm->rangeClass, "min", range_min); PRIMITIVE(vm->rangeClass, "max", range_max); PRIMITIVE(vm->rangeClass, "isInclusive", range_isInclusive); PRIMITIVE(vm->rangeClass, "iterate(_)", range_iterate); PRIMITIVE(vm->rangeClass, "iteratorValue(_)", range_iteratorValue); PRIMITIVE(vm->rangeClass, "toString", range_toString); ObjClass* systemClass = AS_CLASS(wrenFindVariable(vm, coreModule, "System")); PRIMITIVE(systemClass->obj.classObj, "clock", system_clock); PRIMITIVE(systemClass->obj.classObj, "gc()", system_gc); PRIMITIVE(systemClass->obj.classObj, "writeString_(_)", system_writeString); // While bootstrapping the core types and running the core module, a number // of string objects have been created, many of which were instantiated // before stringClass was stored in the VM. Some of them *must* be created // first -- the ObjClass for string itself has a reference to the ObjString // for its name. // // These all currently have a NULL classObj pointer, so go back and assign // them now that the string class is known. for (Obj* obj = vm->first; obj != NULL; obj = obj->next) { if (obj->type == OBJ_STRING) obj->classObj = vm->stringClass; } }
{ "content_hash": "9be6f767632ecb7587f02aca28cd98b9", "timestamp": "", "source": "github", "line_count": 1472, "max_line_length": 85, "avg_line_length": 28.65149456521739, "alnum_prop": 0.6226437462951986, "repo_name": "munificent/wren", "id": "d0a121f8cf92c215aaf2aa461407d8174fb57856", "size": "42444", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "src/vm/wren_core.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "394440" }, { "name": "C++", "bytes": "93025" }, { "name": "Dart", "bytes": "25499" }, { "name": "Lua", "bytes": "10909" }, { "name": "Makefile", "bytes": "12250" }, { "name": "Python", "bytes": "72428" }, { "name": "Ruby", "bytes": "9694" }, { "name": "Shell", "bytes": "698" } ], "symlink_target": "" }
package eu.leads.processor.common.infinispan; /** * Created by vagvaz on 5/18/14. */ public enum KVSType { LOCAL, CLUSTER, ENSEMBLE; public static KVSType stringToKVSType(String type) { if (type.toUpperCase().equals(LOCAL.toString())) { return LOCAL; } else if (type.toUpperCase().equals(CLUSTER.toString())) { return CLUSTER; } else if (type.toUpperCase().equals(ENSEMBLE.toString())) return ENSEMBLE; else return LOCAL; } }
{ "content_hash": "e3f6f8f3c877a51982f51f14cdabc525", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 67, "avg_line_length": 24.952380952380953, "alnum_prop": 0.6030534351145038, "repo_name": "leads-project/multicloud-mr", "id": "7cfe1d460c4d4775e593aade6d45951f197e4cdc", "size": "524", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/main/java/eu/leads/processor/common/infinispan/KVSType.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1374696" }, { "name": "Shell", "bytes": "188" } ], "symlink_target": "" }
package com.khartec.waltz.model.custom_environment; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.khartec.waltz.model.CustomEnvironmentAsset; import com.khartec.waltz.model.application.Application; import org.immutables.value.Value; @Value.Immutable @JsonSerialize(as = ImmutableCustomEnvironmentUsageInfo.class) public abstract class CustomEnvironmentUsageInfo<T extends CustomEnvironmentAsset> { public abstract CustomEnvironmentUsage usage(); public abstract Application owningApplication(); public abstract T asset(); }
{ "content_hash": "c3b7f6513a9b540c24192b4beb4cbc87", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 84, "avg_line_length": 31.72222222222222, "alnum_prop": 0.8266199649737302, "repo_name": "kamransaleem/waltz", "id": "8f74a6db68b9827e77632e7d341cae9ee88fd735", "size": "1208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "waltz-model/src/main/java/com/khartec/waltz/model/custom_environment/CustomEnvironmentUsageInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "154572" }, { "name": "HTML", "bytes": "1360149" }, { "name": "Java", "bytes": "3346006" }, { "name": "JavaScript", "bytes": "2246024" }, { "name": "Shell", "bytes": "305" } ], "symlink_target": "" }
Searchisko REST API documentation ================================= Searchisko REST API on-line documentation & Server Mock are available at [http://docs.jbossorg.apiary.io](http://docs.jbossorg.apiary.io/) ##Searchisko Content object/Document Searchisko content (Document) is the main reason why Searchisko exists. It can be pushed into the Searchisko by the registered providers over 'Content Push API' and searched over 'Search API' and 'Feed API'. The Searchisko content can be characterized by a type (e.g. e-mails, blog posts, forum posts, issues, etc...). Content for one *sys_type* can originate from distinct source systems (e.g. an issue may be from JIRA or Bugzilla). Each *sys_type* has its own logical structure and will require specific fields to be filled. All types also share some common [system data fields](content/dcp_content_object.md). You can find a description of each content type available in jboss.org Searchisko instance (sometimes called DCP) in the [`content`](content) subfolder of this directory. **Note:** If you run your own instance of the Searchisko, consider the documents in this folder as an inspiration. You will have your own content. ###List of available *sys_type*s + [project_info](content/project_info.md) the basic data about the [community project](https://www.jboss.org/projects.html). + [contributor_profile](content/contributor_profile.md) the data about contributor profiles + [blogpost](content/blogpost.md) the data about blog posts related to the project + [issue](content/issue.md) the data from project's issue tracker (JIRA, Bugzilla, etc...) about project bugs, feature requests etc. + [forumthread](content/forumthread.md) the data from project's discussion forum + [article](content/article.md) articles from project's wiki + [webpage](content/webpage.md) web page + [video](content/video.md) metadata about video available for project + [mailing_list_message](content/mailing_list_message.md) mbox message from project's mailing list + [addon](content/addon.md) description of some Addon or Plugin for the project + [solution](content/solution.md) description of some problem solution from knowledgebase + [download](content/download.md) downloads data based on Apache access logs entries Additional `sys_type`s can be found in [jboss-developer](https://github.com/jboss-developer/www.jboss.org/blob/master/_dcp/data/provider/jboss-developer.json) provider configuration. Other data types considered in the future: + documentation page + source code repository commit + IRC/IM conversation + maven repository artifact ##Data structures for Management API A bunch of other information is necessary to run the Searchisko. This is managed using a 'Management API' and is not public. The [`management`](management) subfolder in this directory contains files with descriptions of document structures for the management API: + [content provider](management/content_provider.md) - document type used by 'Management API - content providers' + [project](management/project.md) - document type used by 'Management API - projects' + [contributor](management/contributor.md) - document type used by 'Management API - contributors' + [query](management/query.md) - document type used by 'Management API - registered queries' + [config_*](management) - document types used by 'Management API - configuration' to configure Searchisko instance ## Authentication and Roles based REST API security User or client can be authenticated via two mechanisms where each is supposed for different use cases. 1. *Provider* authentication happens via HTTP Basic authentication. 2. *Contributor* (called *user* sometimes) authentication via `/rest/auth/status` REST API call (which provides CAS SSO integration for now). Once provider/user is authenticated then it can be granted by following roles which control access to distinct parts of REST API. ### Roles 1. `provider` - `default role` for authenticated *provider*. It is mainly used to control `/rest/content` API access. 2. `contributor` - `default role` for authenticated *contributor* 3. `admin` - system administrator with access to whole Management API 4. `contributors_manager` - full access to `/rest/contributor` Management API 5. `projects_manager` - full access to `/rest/project` Management API 6. `tasks_manager` - full access to `/rest/tasks` Management API 7. `tags_manager` - full acces to /rest/tagging API for all content types 8. `tags_manager_x` - access to /rest/tagging API for content type x *Provider* can have only default `provider` role or can have `admin` role if defined in [provider configuration](management/content_provider.md). *Contributors* can get any roles except `provider` by explicitly defining them in [contributor document](management/contributor.md). ## [Expert] Mapping to Elasticsearch indices In the end of the day every indexed document is mapped and indexed into specific Elasticsearch index/type according on content provider configuration. Read more details about [Mapping from 'sys\_*' fields to Elasticsearch \_index, \_type and \_id fields](sys_fields_to_es_fields_mapping.md).
{ "content_hash": "d230aa7a94d8e603876210ff68a92be7", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 172, "avg_line_length": 57.32222222222222, "alnum_prop": 0.7722426826904439, "repo_name": "ollyjshaw/searchisko", "id": "20c74ac22e96c2d867f1d3888a848bd55ddc95bc", "size": "5159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documentation/rest-api/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "API Blueprint", "bytes": "70155" }, { "name": "CSS", "bytes": "531" }, { "name": "HTML", "bytes": "963" }, { "name": "Java", "bytes": "1854001" }, { "name": "Shell", "bytes": "63" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace BbsSample.Models { public class Comment { public int Id { get; set; } public string UserName { get; set; } [DataType(DataType.MultilineText)] public string Body { get; set; } public DateTime Created { get; set; } } }
{ "content_hash": "018b7a27a493a0e94cb90253bf71b046", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 45, "avg_line_length": 22.05, "alnum_prop": 0.673469387755102, "repo_name": "aspnet-mvc-samples/BbsSample", "id": "f90a3c4d66a85ac1958a9456476801a93ae419a1", "size": "443", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BbsSample/Models/Comment.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "100" }, { "name": "C#", "bytes": "88365" }, { "name": "CSS", "bytes": "3643" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "10918" } ], "symlink_target": "" }
package fetcher import ( "io" "os" "time" "errors" "strings" "net/url" "net/http" "io/ioutil" "crypto/tls" "encoding/json" "encoding/base64" ) type CacheResponse struct { Resp *http.Response Body []byte CacheTime int64 } type Transport struct { tr http.RoundTripper BeforeReq func (req *http.Request) AfterReq func(resp *http.Response, req *http.Request) } func NewTransport(tr http.RoundTripper) *Transport { t := &Transport{} if tr == nil { tr = http.DefaultTransport } t.tr = tr return t } func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) { t.BeforeReq(req) resp, err = t.tr.RoundTrip(req) if err != nil { return } t.AfterReq(resp, req) return } type Fetcher struct { Https bool Host string Referer string CacheTime int64 Cookies []*http.Cookie Client *http.Client `json:"-"` Cache map[string] CacheResponse `json:"-"` } func NewFetcher(host string) (f *Fetcher) { f = newFetcher(nil) f.Host = host return } func NewFetcherHttps(host string) (f *Fetcher) { tr := &http.Transport{ TLSClientConfig: &tls.Config{RootCAs: nil, InsecureSkipVerify: true}, DisableCompression: true, } f = newFetcher(tr) f.Host = host f.Https = true return } func newFetcher(tr http.RoundTripper) (f *Fetcher) { f = &Fetcher{} newTr := NewTransport(tr) newTr.AfterReq = func(resp *http.Response, req *http.Request) { f.mergeCookie(resp) f.Referer = req.URL.String() } newTr.BeforeReq = func(req *http.Request) { f.makeOtherHeader(req) f.insertCookie(req) f.insertReferer(req) } f.Client = &http.Client{ Transport: newTr, } f.Cache = make(map[string] CacheResponse) return } func (f *Fetcher) GetBase64(path string) (data string, err error) { resp, body, err := f.Get(path) if err != nil { return } if resp.StatusCode / 100 != 2 { err = errors.New(err.Error()) return } data = base64.StdEncoding.EncodeToString(body) return } func (f *Fetcher) SaveFile(path, dstPath string) (err error) { _, body, err := f.Get(path) if err != nil { return } ioutil.WriteFile(dstPath, body, os.ModePerm) return } func (f *Fetcher) RemoveGetCache(path string) { key := "get-" + "http" if f.Https { key += "s" } key += "://" + f.Host + path _, ok := f.Cache[key] if ! ok { return } delete(f.Cache, key) } func (f *Fetcher) RemovePostCache(path string, params url.Values) { key := "post-" + path + params.Encode() delete(f.Cache, key) } func (f *Fetcher) Get(path string) (resp *http.Response, body []byte, err error) { path = f.makeUrl(path) req, err := http.NewRequest("GET", path, nil) if err != nil { return } key := "get-" + path resp, body, ok := f.loadCache(key) if ok { return } resp, body, err = f.request(req) if err != nil { return } if f.CacheTime > 0 { f.saveCache(key, resp, body) } return } func (f *Fetcher) GetWithNoCache(path string) (resp *http.Response, body []byte, err error) { path = f.makeUrl(path) req, err := http.NewRequest("GET", path, nil) if err != nil { return } key := "get-" + path resp, body, err = f.request(req) if err != nil { return } if f.CacheTime > 0 { f.saveCache(key, resp, body) } return } func (f *Fetcher) Post( path, contentType string, content io.Reader) (resp *http.Response, body []byte, err error) { path = f.makeUrl(path) req, err := http.NewRequest("POST", path, content) if err != nil { return } req.Header.Set("Content-Type", contentType) resp, body, err = f.request(req) if err != nil { return } f.Referer = path return } func (f *Fetcher) PostForm(path string, val url.Values) (resp *http.Response, body []byte, err error) { contentType := "application/x-www-form-urlencoded" if val == nil { val = url.Values{} } // key := "post-" + path + val.Encode() // resp, body, ok := f.loadCache(key) // if ok { return } resp, body, err = f.Post(path, contentType, strings.NewReader(val.Encode())) // if f.CacheTime > 0 { // f.saveCache(key, resp, body) // } return } func (f *Fetcher) PostFormRetry( path string, val url.Values, tryTime int) (resp *http.Response, body []byte, err error) { for i:=0; i<tryTime; i++ { resp, body, err = f.PostForm(path, val) if err == nil { break } } return } func (f *Fetcher) CallPostForm(v interface{}, path string, val url.Values) (err error) { _, body, err := f.PostForm(path, val) if err != nil { return } err = json.Unmarshal(body, v) if err != nil { err = errors.New("unmarshal fail: " + string(body) + ", " + err.Error()) return } return } func (f *Fetcher) getCacheKey(req *http.Request) string { q := req.URL.Query() key := req.URL.Path + q.Encode() return key } func (f *Fetcher) loadCache(key string) (resp *http.Response, body []byte, ok bool) { r, ok := f.Cache[key] if ! ok { return } ok = false if time.Now().Unix() - r.CacheTime > f.CacheTime { delete(f.Cache, key) return } resp, body = r.Resp, r.Body ok = true return } func (f *Fetcher) saveCache(key string, resp *http.Response, body []byte) { r := CacheResponse{ resp, body, time.Now().Unix(), } f.Cache[key] = r } func (f *Fetcher) request(req *http.Request) (resp *http.Response, body []byte, err error) { resp, err = f.Client.Do(req) if err != nil { return } defer resp.Body.Close() body, err = ioutil.ReadAll(resp.Body) return } func (f *Fetcher) insertReferer(req *http.Request) (err error) { if f.Referer != "" { req.Header.Set("Referer", f.Referer) } return } func (f *Fetcher) insertCookie(req *http.Request) (err error) { for _, cookie := range f.Cookies { req.AddCookie(cookie) } return } func (f *Fetcher) mergeCookie(resp *http.Response) (err error) { cookies := resp.Cookies() newCookies := make([]*http.Cookie, len(cookies)) length := 0 for _, c := range cookies { for idx, cs := range f.Cookies { if c.Name == cs.Name { f.Cookies[idx] = c goto next } } newCookies[length] = c length ++ next: continue } f.Cookies = append(f.Cookies, newCookies[:length]...) return } func (f *Fetcher) makeUrl(path string) string { u := path idx := strings.Index(path, "://") if idx <= 0 && f.Host != "" { u = f.Host + u } if idx <= 0 { prefix := "http" if f.Https { prefix = "https" } u = prefix + "://" + u } return u } func (f *Fetcher) makeOtherHeader(req *http.Request) (err error) { accept := "application/json, text/javascript, */*; q=0.01" origin := f.makeUrl("") requestWith := "XMLHttpRequest" agent := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) " agent += "AppleWebKit/537.36 (KHTML, like Gecko) " agent += "Chrome/27.0.1453.116 Safari/537.36" // encoding := "deflate,sdch" encoding := "none" language := "en-US,en;q=0.8" req.Header.Set("Accept", accept) req.Header.Set("Origin", origin) req.Header.Set("X-Requested-With", requestWith) req.Header.Set("User-Agent", agent) req.Header.Set("Accept-Encoding", encoding) req.Header.Set("Accept-Language", language) return } func (f *Fetcher) Store() (ret string, err error) { data, err := json.Marshal(f) if err != nil { return } ret = base64.StdEncoding.EncodeToString(data) return } func Restore(str string) (f *Fetcher, err error) { data, err := base64.StdEncoding.DecodeString(str) if err != nil { return } f = newFetcher(nil) err = json.Unmarshal(data, f) return }
{ "content_hash": "b9bb0bdc3889103d657e9241105bcd85", "timestamp": "", "source": "github", "line_count": 311, "max_line_length": 103, "avg_line_length": 23.459807073954984, "alnum_prop": 0.6463815789473685, "repo_name": "denghongcai/Go-BloodAttack", "id": "e1161545dda9432b63c3ac5851d1d9b26518f2a2", "size": "7296", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fetcher/fetcher.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "8368" } ], "symlink_target": "" }
 #include <aws/application-autoscaling/model/ScalableDimension.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace ApplicationAutoScaling { namespace Model { namespace ScalableDimensionMapper { static const int ecs_service_DesiredCount_HASH = HashingUtils::HashString("ecs:service:DesiredCount"); static const int ec2_spot_fleet_request_TargetCapacity_HASH = HashingUtils::HashString("ec2:spot-fleet-request:TargetCapacity"); static const int elasticmapreduce_instancegroup_InstanceCount_HASH = HashingUtils::HashString("elasticmapreduce:instancegroup:InstanceCount"); static const int appstream_fleet_DesiredCapacity_HASH = HashingUtils::HashString("appstream:fleet:DesiredCapacity"); static const int dynamodb_table_ReadCapacityUnits_HASH = HashingUtils::HashString("dynamodb:table:ReadCapacityUnits"); static const int dynamodb_table_WriteCapacityUnits_HASH = HashingUtils::HashString("dynamodb:table:WriteCapacityUnits"); static const int dynamodb_index_ReadCapacityUnits_HASH = HashingUtils::HashString("dynamodb:index:ReadCapacityUnits"); static const int dynamodb_index_WriteCapacityUnits_HASH = HashingUtils::HashString("dynamodb:index:WriteCapacityUnits"); static const int rds_cluster_ReadReplicaCount_HASH = HashingUtils::HashString("rds:cluster:ReadReplicaCount"); static const int sagemaker_variant_DesiredInstanceCount_HASH = HashingUtils::HashString("sagemaker:variant:DesiredInstanceCount"); static const int custom_resource_ResourceType_Property_HASH = HashingUtils::HashString("custom-resource:ResourceType:Property"); static const int comprehend_document_classifier_endpoint_DesiredInferenceUnits_HASH = HashingUtils::HashString("comprehend:document-classifier-endpoint:DesiredInferenceUnits"); static const int comprehend_entity_recognizer_endpoint_DesiredInferenceUnits_HASH = HashingUtils::HashString("comprehend:entity-recognizer-endpoint:DesiredInferenceUnits"); static const int lambda_function_ProvisionedConcurrency_HASH = HashingUtils::HashString("lambda:function:ProvisionedConcurrency"); static const int cassandra_table_ReadCapacityUnits_HASH = HashingUtils::HashString("cassandra:table:ReadCapacityUnits"); static const int cassandra_table_WriteCapacityUnits_HASH = HashingUtils::HashString("cassandra:table:WriteCapacityUnits"); static const int kafka_broker_storage_VolumeSize_HASH = HashingUtils::HashString("kafka:broker-storage:VolumeSize"); static const int elasticache_replication_group_NodeGroups_HASH = HashingUtils::HashString("elasticache:replication-group:NodeGroups"); static const int elasticache_replication_group_Replicas_HASH = HashingUtils::HashString("elasticache:replication-group:Replicas"); ScalableDimension GetScalableDimensionForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == ecs_service_DesiredCount_HASH) { return ScalableDimension::ecs_service_DesiredCount; } else if (hashCode == ec2_spot_fleet_request_TargetCapacity_HASH) { return ScalableDimension::ec2_spot_fleet_request_TargetCapacity; } else if (hashCode == elasticmapreduce_instancegroup_InstanceCount_HASH) { return ScalableDimension::elasticmapreduce_instancegroup_InstanceCount; } else if (hashCode == appstream_fleet_DesiredCapacity_HASH) { return ScalableDimension::appstream_fleet_DesiredCapacity; } else if (hashCode == dynamodb_table_ReadCapacityUnits_HASH) { return ScalableDimension::dynamodb_table_ReadCapacityUnits; } else if (hashCode == dynamodb_table_WriteCapacityUnits_HASH) { return ScalableDimension::dynamodb_table_WriteCapacityUnits; } else if (hashCode == dynamodb_index_ReadCapacityUnits_HASH) { return ScalableDimension::dynamodb_index_ReadCapacityUnits; } else if (hashCode == dynamodb_index_WriteCapacityUnits_HASH) { return ScalableDimension::dynamodb_index_WriteCapacityUnits; } else if (hashCode == rds_cluster_ReadReplicaCount_HASH) { return ScalableDimension::rds_cluster_ReadReplicaCount; } else if (hashCode == sagemaker_variant_DesiredInstanceCount_HASH) { return ScalableDimension::sagemaker_variant_DesiredInstanceCount; } else if (hashCode == custom_resource_ResourceType_Property_HASH) { return ScalableDimension::custom_resource_ResourceType_Property; } else if (hashCode == comprehend_document_classifier_endpoint_DesiredInferenceUnits_HASH) { return ScalableDimension::comprehend_document_classifier_endpoint_DesiredInferenceUnits; } else if (hashCode == comprehend_entity_recognizer_endpoint_DesiredInferenceUnits_HASH) { return ScalableDimension::comprehend_entity_recognizer_endpoint_DesiredInferenceUnits; } else if (hashCode == lambda_function_ProvisionedConcurrency_HASH) { return ScalableDimension::lambda_function_ProvisionedConcurrency; } else if (hashCode == cassandra_table_ReadCapacityUnits_HASH) { return ScalableDimension::cassandra_table_ReadCapacityUnits; } else if (hashCode == cassandra_table_WriteCapacityUnits_HASH) { return ScalableDimension::cassandra_table_WriteCapacityUnits; } else if (hashCode == kafka_broker_storage_VolumeSize_HASH) { return ScalableDimension::kafka_broker_storage_VolumeSize; } else if (hashCode == elasticache_replication_group_NodeGroups_HASH) { return ScalableDimension::elasticache_replication_group_NodeGroups; } else if (hashCode == elasticache_replication_group_Replicas_HASH) { return ScalableDimension::elasticache_replication_group_Replicas; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ScalableDimension>(hashCode); } return ScalableDimension::NOT_SET; } Aws::String GetNameForScalableDimension(ScalableDimension enumValue) { switch(enumValue) { case ScalableDimension::ecs_service_DesiredCount: return "ecs:service:DesiredCount"; case ScalableDimension::ec2_spot_fleet_request_TargetCapacity: return "ec2:spot-fleet-request:TargetCapacity"; case ScalableDimension::elasticmapreduce_instancegroup_InstanceCount: return "elasticmapreduce:instancegroup:InstanceCount"; case ScalableDimension::appstream_fleet_DesiredCapacity: return "appstream:fleet:DesiredCapacity"; case ScalableDimension::dynamodb_table_ReadCapacityUnits: return "dynamodb:table:ReadCapacityUnits"; case ScalableDimension::dynamodb_table_WriteCapacityUnits: return "dynamodb:table:WriteCapacityUnits"; case ScalableDimension::dynamodb_index_ReadCapacityUnits: return "dynamodb:index:ReadCapacityUnits"; case ScalableDimension::dynamodb_index_WriteCapacityUnits: return "dynamodb:index:WriteCapacityUnits"; case ScalableDimension::rds_cluster_ReadReplicaCount: return "rds:cluster:ReadReplicaCount"; case ScalableDimension::sagemaker_variant_DesiredInstanceCount: return "sagemaker:variant:DesiredInstanceCount"; case ScalableDimension::custom_resource_ResourceType_Property: return "custom-resource:ResourceType:Property"; case ScalableDimension::comprehend_document_classifier_endpoint_DesiredInferenceUnits: return "comprehend:document-classifier-endpoint:DesiredInferenceUnits"; case ScalableDimension::comprehend_entity_recognizer_endpoint_DesiredInferenceUnits: return "comprehend:entity-recognizer-endpoint:DesiredInferenceUnits"; case ScalableDimension::lambda_function_ProvisionedConcurrency: return "lambda:function:ProvisionedConcurrency"; case ScalableDimension::cassandra_table_ReadCapacityUnits: return "cassandra:table:ReadCapacityUnits"; case ScalableDimension::cassandra_table_WriteCapacityUnits: return "cassandra:table:WriteCapacityUnits"; case ScalableDimension::kafka_broker_storage_VolumeSize: return "kafka:broker-storage:VolumeSize"; case ScalableDimension::elasticache_replication_group_NodeGroups: return "elasticache:replication-group:NodeGroups"; case ScalableDimension::elasticache_replication_group_Replicas: return "elasticache:replication-group:Replicas"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace ScalableDimensionMapper } // namespace Model } // namespace ApplicationAutoScaling } // namespace Aws
{ "content_hash": "86b1f3084983ed97c75fd111bef01905", "timestamp": "", "source": "github", "line_count": 186, "max_line_length": 184, "avg_line_length": 53.06989247311828, "alnum_prop": 0.6966872657278897, "repo_name": "awslabs/aws-sdk-cpp", "id": "780504b8d9f766b35d7edf8db664740fb7c8fb2f", "size": "9990", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-application-autoscaling/source/model/ScalableDimension.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7596" }, { "name": "C++", "bytes": "61740540" }, { "name": "CMake", "bytes": "337520" }, { "name": "Java", "bytes": "223122" }, { "name": "Python", "bytes": "47357" } ], "symlink_target": "" }
<?php /** * @author Tomáš Blatný */ namespace greeny\Twitch\Entities; use greeny\Twitch\Api; class Entity { /** @var \stdClass */ protected $data = NULL; /** @var \greeny\Twitch\Api */ protected $api; public function __construct(Api $api, $data) { $this->api = $api; $this->data = $data; } /** * @return \stdClass */ public function getRaw() { return $this->data; } /** * @param $key * @return mixed * @throws \LogicException */ public function __get($key) { if(method_exists($this, $name = 'get'.ucfirst($key))) { return $this->$name(); } else { throw new \LogicException("Access to undefined property '$key'."); } } }
{ "content_hash": "120ccaddea9f07bc74ca8c6a6067abab", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 69, "avg_line_length": 15, "alnum_prop": 0.5940740740740741, "repo_name": "greeny/Twitch-Php", "id": "0106615279b11a7097ae1b29b7c42acc3c6ad897", "size": "678", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Twitch/Entities/Entity.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "28823" } ], "symlink_target": "" }
package com.example.chat.util; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import okio.ByteString; /** * Created by Administrator on 2017/8/6. */ public class EchoWebSocketListener extends WebSocketListener { @Override public void onOpen(WebSocket webSocket, Response response) { webSocket.send("hello world"); } @Override public void onMessage(WebSocket webSocket, String text) { } @Override public void onMessage(WebSocket webSocket, ByteString bytes) { } @Override public void onClosing(WebSocket webSocket, int code, String reason) { webSocket.close(1000, null); } @Override public void onClosed(WebSocket webSocket, int code, String reason) { } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { } }
{ "content_hash": "6cbed84e70636e1c099004a2bca5c7d1", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 80, "avg_line_length": 19.304347826086957, "alnum_prop": 0.6981981981981982, "repo_name": "zhuhanggl/chat", "id": "0c5184540f6cf6ba57b43623205fba815741b0ae", "size": "888", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/example/chat/util/EchoWebSocketListener.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "128706" } ], "symlink_target": "" }
$def with (toUser,fromUser,createTime,content) <xml> <ToUserName><![CDATA[$toUser]]></ToUserName> <FromUserName><![CDATA[$fromUser]]></FromUserName> <CreateTime>$createTime</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[$content]]></Content> </xml>
{ "content_hash": "4870a3f0392f37e6cf4e4ba4bd26c15e", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 50, "avg_line_length": 33.625, "alnum_prop": 0.7100371747211895, "repo_name": "weiguobin/weixin-app", "id": "c2563321ac0cb55aa6332f56be3a22cadaaecd6f", "size": "269", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "templates/reply_text.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "43508" } ], "symlink_target": "" }
#include "tensorflow/cc/framework/grad_op_registry.h" namespace tensorflow { namespace ops { // static GradOpRegistry* GradOpRegistry::Global() { static GradOpRegistry* grad_op_registry = new GradOpRegistry; return grad_op_registry; } bool GradOpRegistry::Register(const string& op, GradFunc func) { CHECK(registry_.insert({op, func}).second) << "Existing gradient for " << op; return true; } Status GradOpRegistry::Lookup(const string& op, GradFunc* func) { auto iter = registry_.find(op); if (iter == registry_.end()) { return errors::NotFound("No gradient defined for op: ", op); } *func = iter->second; return Status::OK(); } } // end namespace ops } // namespace tensorflow
{ "content_hash": "0fadda07d59c627c42106c3fa4189528", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 79, "avg_line_length": 24.482758620689655, "alnum_prop": 0.6957746478873239, "repo_name": "natanielruiz/android-yolo", "id": "b83e7de61c635d384bdc5fb45a6fabca75d175d5", "size": "1378", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "jni-build/jni/include/tensorflow/cc/framework/grad_op_registry.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "179103" }, { "name": "C++", "bytes": "11498765" }, { "name": "CMake", "bytes": "36462" }, { "name": "CSS", "bytes": "774" }, { "name": "HTML", "bytes": "520176" }, { "name": "Java", "bytes": "95359" }, { "name": "JavaScript", "bytes": "12951" }, { "name": "Jupyter Notebook", "bytes": "1773504" }, { "name": "Makefile", "bytes": "23603" }, { "name": "Objective-C", "bytes": "5332" }, { "name": "Objective-C++", "bytes": "45677" }, { "name": "Python", "bytes": "9531722" }, { "name": "Shell", "bytes": "238167" }, { "name": "TypeScript", "bytes": "632244" } ], "symlink_target": "" }
Given a diagram, determine which plants each child in the kindergarten class is responsible for. The kindergarten class is learning about growing plants. The teacher thought it would be a good idea to give them actual seeds, plant them in actual dirt, and grow actual plants. They've chosen to grow grass, clover, radishes, and violets. To this end, the children have put little cups along the window sills, and planted one type of plant in each cup, choosing randomly from the available types of seeds. ```text [window][window][window] ........................ # each dot represents a cup ........................ ``` There are 12 children in the class: - Alice, Bob, Charlie, David, - Eve, Fred, Ginny, Harriet, - Ileana, Joseph, Kincaid, and Larry. Each child gets 4 cups, two on each row. Their teacher assigns cups to the children alphabetically by their names. The following diagram represents Alice's plants: ```text [window][window][window] VR...................... RG...................... ``` In the first row, nearest the windows, she has a violet and a radish. In the second row she has a radish and some grass. Your program will be given the plants from left-to-right starting with the row nearest the windows. From this, it should be able to determine which plants belong to each student. For example, if it's told that the garden looks like so: ```text [window][window][window] VRCGVVRVCGGCCGVRGCVCGCGV VRCCCGCRRGVCGCRVVCVGCGCV ``` Then if asked for Alice's plants, it should provide: - Violets, radishes, violets, radishes While asking for Bob's plants would yield: - Clover, grass, clover, clover ## Getting Started For installation and learning resources, refer to the [exercism help page](http://exercism.io/languages/haskell). ## Running the tests To run the test suite, execute the following command: ```bash stack test ``` #### If you get an error message like this... ``` No .cabal file found in directory ``` You are probably running an old stack version and need to upgrade it. #### Otherwise, if you get an error message like this... ``` No compiler found, expected minor version match with... Try running "stack setup" to install the correct GHC... ``` Just do as it says and it will download and install the correct compiler version: ```bash stack setup ``` ## Running *GHCi* If you want to play with your solution in GHCi, just run the command: ```bash stack ghci ``` ## Feedback, Issues, Pull Requests The [exercism/haskell](https://github.com/exercism/haskell) repository on GitHub is the home for all of the Haskell exercises. If you have feedback about an exercise, or want to help implementing a new one, head over there and create an issue. We'll do our best to help you! ## Source Random musings during airplane trip. [http://jumpstartlab.com](http://jumpstartlab.com) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise.
{ "content_hash": "b2088b3059ff47495384215fa5b392ff", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 101, "avg_line_length": 25.279661016949152, "alnum_prop": 0.7298022125377137, "repo_name": "enolive/exercism", "id": "e0b49fd4458cbf97cbf30016d3323c73bf93d36b", "size": "3006", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "haskell/kindergarten-garden/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1346" }, { "name": "Haskell", "bytes": "220732" }, { "name": "Java", "bytes": "28701" }, { "name": "Kotlin", "bytes": "78063" }, { "name": "TypeScript", "bytes": "92672" } ], "symlink_target": "" }
import json import unittest import unittest.mock as mock from flake_suppressor import gpu_expectations from flake_suppressor import gpu_queries as queries from flake_suppressor import gpu_tag_utils as tag_utils from flake_suppressor import gpu_results as results_module from flake_suppressor_common import unittest_utils as uu from flake_suppressor_common import tag_utils as common_tag_utils class GpuQueriesUnittest(unittest.TestCase): def setUp(self) -> None: common_tag_utils.SetTagUtilsImplementation(tag_utils.GpuTagUtils) expectations_processor = gpu_expectations.GpuExpectationProcessor() result_processor = results_module.GpuResultProcessor(expectations_processor) self._querier_instance = queries.GpuBigQueryQuerier(1, 'project', result_processor) self._querier_instance._submitted_builds = set(['build-1234', 'build-2345']) self._subprocess_patcher = mock.patch( 'flake_suppressor_common.queries.subprocess.run') self._subprocess_mock = self._subprocess_patcher.start() self.addCleanup(self._subprocess_patcher.stop) def testIgnoredTags(self) -> None: """Tests that ignored tags are removed and their counts merged.""" def SideEffect(*_, **kwargs) -> uu.FakeProcess: query = kwargs['input'] if 'submitted_builds' in query: # Try results. query_result = [ { 'typ_tags': ['linux', 'nvidia'], 'test_name': 'garbage.suite.garbage.linux', 'result_count': '25', }, { 'typ_tags': ['linux', 'win-laptop'], 'test_name': 'garbage.suite.garbage.linux', 'result_count': '50', }, ] else: # CI results. query_result = [{ 'typ_tags': ['win', 'win-laptop'], 'test_name': 'garbage.suite.garbage.windows', 'result_count': '100', }, { 'typ_tags': ['win'], 'test_name': 'garbage.suite.garbage.windows', 'result_count': '50', }, { 'typ_tags': ['mac', 'exact'], 'test_name': 'garbage.suite.garbage.mac', 'result_count': '200', }, { 'typ_tags': ['linux'], 'test_name': 'garbage.suite.garbage.linux', 'result_count': '300', }] return uu.FakeProcess(stdout=json.dumps(query_result)) self._subprocess_mock.side_effect = SideEffect result_counts = self._querier_instance.GetResultCounts() expected_result_counts = { tuple(['win']): { 'windows': 150, }, tuple(['mac']): { 'mac': 200, }, tuple(['linux']): { 'linux': 350, }, tuple(['linux', 'nvidia']): { 'linux': 25, }, } self.assertEqual(result_counts, expected_result_counts) self.assertEqual(self._subprocess_mock.call_count, 2) if __name__ == '__main__': unittest.main(verbosity=2)
{ "content_hash": "296dac07b1012908388cedeaaf97bf66", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 80, "avg_line_length": 35.13793103448276, "alnum_prop": 0.5734380111220151, "repo_name": "chromium/chromium", "id": "bf1ffbae1fdc6691c1d2b4259863967d1b2f5e37", "size": "3258", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "content/test/gpu/flake_suppressor/gpu_queries_unittest.py", "mode": "33261", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
{% extends "iavi/layout.html" %} {% block title %}Edit Participant{% endblock %} {% block pagecontent %} <h2>Edit Participant</h2> <form method="POST"> <table> {{ form.as_table}} </table> <input type="hidden" name="reporter_id" value="{{reporter.id}}"> <input type="submit" value="Submit" /> </form> <br> <a href="/iavi/participants">back to participant list</a> {% endblock %}
{ "content_hash": "7e5228499d711611d10fd87127c847b6", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 68, "avg_line_length": 28.714285714285715, "alnum_prop": 0.6243781094527363, "repo_name": "genova/rapidsms-senegal", "id": "863a25aa7cfa8dd25b5361b09929e60c8b97b5ee", "size": "402", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "apps/iavi/templates/iavi/participant_edit.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
CLASS({ package: 'foam.apps.builder.wizard', name: 'NewOrExistingDAOWizard', extends: 'foam.apps.builder.wizard.NewOrExistingWizard', requires: [ 'foam.apps.builder.wizard.NewDAOWizard', 'foam.apps.builder.dao.DAOFactory', ], imports: [ 'daoConfigDAO as unfilteredExistingDAO', ], exports: [ 'selection' ], properties: [ { name: 'newViewFactory', label: 'Create a new Data Source', defaultValue: { factory_: 'foam.apps.builder.wizard.NewDAOWizard' }, }, { name: 'existingViewFactory', label: 'Use an existing Data Source', defaultValue: null, }, { name: 'nextViewFactory', lazyFactory: function() { return this.newViewFactory; }, }, { name: 'selection', }, { name: 'unfilteredExistingDAO', postSet: function(old, nu) { if ( this.data ) { this.filterExistingDAO(); } else { this.data$.addListener(EventService.oneTime(this.filterExistingDAO)); } } }, { name: 'existingDAO', view: { factory_: 'foam.ui.md.DAOListView', rowView: 'foam.apps.builder.dao.DAOFactoryView', } } ], listeners: [ { name: 'filterExistingDAO', code: function() { this.existingDAO = this.unfilteredExistingDAO; // .where( // EQ(this.DAOFactory.MODEL_TYPE, this.data.baseModelId) // ); } }, ], methods: [ function onNext() { if ( this.selection && this.nextViewFactory === this.existingViewFactory ) { this.data.getDataConfig().dao = this.selection; } if ( this.nextViewFactory === this.newViewFactory ) { this.data.resetDAO(); } this.SUPER(); }, ], });
{ "content_hash": "521f232c19eb53ea6f3c854b4527a397", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 82, "avg_line_length": 21.829268292682926, "alnum_prop": 0.5659217877094972, "repo_name": "jlhughes/foam", "id": "57c62aab4df9fa750c6f8c6cc68bd2516819ce89", "size": "2094", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "js/foam/apps/builder/wizard/NewOrExistingDAOWizard.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1826" }, { "name": "CSS", "bytes": "64734" }, { "name": "HTML", "bytes": "324383" }, { "name": "Java", "bytes": "167220" }, { "name": "JavaScript", "bytes": "5905830" }, { "name": "Objective-J", "bytes": "834" }, { "name": "Shell", "bytes": "24747" } ], "symlink_target": "" }
import accountActions from '../../constants/account'; export default function registerAccount(context, payload, done) { context.dispatch(accountActions.ACCOUNT_REGISTER); context.api.account.register(payload).then(function successFn(result) { context.dispatch(accountActions.ACCOUNT_REGISTER_SUCCESS, result); done && done(); }, function errorFn(err) { context.dispatch(accountActions.ACCOUNT_REGISTER_ERROR, err.result); done && done(); }); };
{ "content_hash": "3af34e03c4021c26cf9851d6b894023e", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 76, "avg_line_length": 41.166666666666664, "alnum_prop": 0.7004048582995951, "repo_name": "ESTEBANMURUZABAL/my-ecommerce-template", "id": "0dc32268f7c63ac52435e6cf9be4c49c71d980e9", "size": "494", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/actions/Account/registerAccount.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "133699" }, { "name": "JavaScript", "bytes": "993705" } ], "symlink_target": "" }
@interface FuzzImageData : FuzzData @property (nonatomic, strong) NSURL *imageURL; @end
{ "content_hash": "b9eab16b0e4391a54e4bfdd2f39977e1", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 46, "avg_line_length": 29.333333333333332, "alnum_prop": 0.7840909090909091, "repo_name": "dylanshine/FuzzStagingQuiz", "id": "d44874d23088f40cc6d780b0403b693bd39dfa5d", "size": "256", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FuzzStagingQuiz/FuzzStagingQuiz/FuzzImageData.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2003" }, { "name": "Objective-C", "bytes": "460439" }, { "name": "Ruby", "bytes": "192" }, { "name": "Shell", "bytes": "4447" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ClientPropertiesManager"> <properties class="javax.swing.AbstractButton"> <property name="hideActionText" class="java.lang.Boolean" /> </properties> <properties class="javax.swing.JComponent"> <property name="html.disable" class="java.lang.Boolean" /> </properties> <properties class="javax.swing.JEditorPane"> <property name="JEditorPane.w3cLengthUnits" class="java.lang.Boolean" /> <property name="JEditorPane.honorDisplayProperties" class="java.lang.Boolean" /> <property name="charset" class="java.lang.String" /> </properties> <properties class="javax.swing.JList"> <property name="List.isFileList" class="java.lang.Boolean" /> </properties> <properties class="javax.swing.JPasswordField"> <property name="JPasswordField.cutCopyAllowed" class="java.lang.Boolean" /> </properties> <properties class="javax.swing.JSlider"> <property name="Slider.paintThumbArrowShape" class="java.lang.Boolean" /> <property name="JSlider.isFilled" class="java.lang.Boolean" /> </properties> <properties class="javax.swing.JTable"> <property name="Table.isFileList" class="java.lang.Boolean" /> <property name="JTable.autoStartsEdit" class="java.lang.Boolean" /> <property name="terminateEditOnFocusLost" class="java.lang.Boolean" /> </properties> <properties class="javax.swing.JToolBar"> <property name="JToolBar.isRollover" class="java.lang.Boolean" /> </properties> <properties class="javax.swing.JTree"> <property name="JTree.lineStyle" class="java.lang.String" /> </properties> <properties class="javax.swing.text.JTextComponent"> <property name="caretAspectRatio" class="java.lang.Double" /> <property name="caretWidth" class="java.lang.Integer" /> </properties> </component> <component name="ProjectInspectionProfilesVisibleTreeState"> <entry key="Project Default"> <profile-state> <expanded-state> <State> <id /> </State> <State> <id>Android &gt; Lint &gt; Correctness</id> </State> <State> <id>Android &gt; Lint &gt; Internationalization</id> </State> <State> <id>Android &gt; Lint &gt; Performance</id> </State> <State> <id>Android &gt; Lint &gt; Security</id> </State> <State> <id>Android &gt; Lint &gt; Usability</id> </State> <State> <id>Android Lint for Kotlin</id> </State> <State> <id>Ant inspections</id> </State> <State> <id>FreeMarker inspections</id> </State> <State> <id>Java</id> </State> <State> <id>Java 5Java language level migration aidsJava</id> </State> <State> <id>Java language level migration aidsJava</id> </State> <State> <id>Kotlin</id> </State> <State> <id>Performance issuesJava</id> </State> <State> <id>Portability issuesJava</id> </State> <State> <id>Probable bugsJava</id> </State> </expanded-state> </profile-state> </entry> </component> <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="Java 8" project-jdk-type="JavaSDK"> <output url="file://$PROJECT_DIR$/classes" /> </component> <component name="masterDetails"> <states> <state key="GlobalLibrariesConfigurable.UI"> <settings> <last-edited>activesupport (v4.0.13, ruby-2.3.1-p112) [gem]</last-edited> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> <state key="JdkListConfigurable.UI"> <settings> <last-edited>Java 8</last-edited> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> <state key="ProjectJDKs.UI"> <settings> <last-edited>Java 8</last-edited> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> <state key="ProjectLibrariesConfigurable.UI"> <settings> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> </states> </component> </project>
{ "content_hash": "045c53c09b95635e9bbb2499ac27c074", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 143, "avg_line_length": 34.33112582781457, "alnum_prop": 0.5553626543209876, "repo_name": "enolive/exercism", "id": "ea8aac80831661497a31505f9673c8d2f413c1be", "size": "5184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kotlin/difference-of-squares/.idea/misc.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1346" }, { "name": "Haskell", "bytes": "220732" }, { "name": "Java", "bytes": "28701" }, { "name": "Kotlin", "bytes": "78063" }, { "name": "TypeScript", "bytes": "92672" } ], "symlink_target": "" }
import { FC, memo } from 'react' import { LavaLampLoading } from '@/widgets/Loading' import EnterHint from '@/widgets/EnterHint' import type { TValidState } from '../spec' import { Wrapper, Title, Inputer, InputerWrapper, HintWrapper, Hint, } from '../styles/content/rss_inputer' import { inputOnChange, fetchRSSInfo } from '../logic' type TProps = { rss: string loading: boolean validState: TValidState } const RSSInputer: FC<TProps> = ({ rss, loading, validState }) => { return ( <Wrapper> <Title>请输入博客 RSS 地址</Title> <InputerWrapper> <Inputer value={rss} placeholder="// 例如:https://example.com/blog/atom.xml" onChange={(e) => inputOnChange(e, 'rss')} onEnter={() => validState.rss && fetchRSSInfo()} /> {validState.rss && <EnterHint bottom={-30} right={30} />} </InputerWrapper> {loading ? ( <LavaLampLoading top={20} left={5} /> ) : ( <HintWrapper> <Hint>支持 RSS 2.0 以及 Atom 格式</Hint> <Hint>已提交的博客会同时保存历史 Feed, 方便关联查看。</Hint> <Hint>已提交的 rss 记录每天会定时更新,可能会有滞后。</Hint> </HintWrapper> )} </Wrapper> ) } export default memo(RSSInputer)
{ "content_hash": "7d2ddb1f69468d8e7c47dae5ccd9bd46", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 66, "avg_line_length": 24.48, "alnum_prop": 0.5915032679738562, "repo_name": "mydearxym/mastani", "id": "d8b295f8a4cd99d69a4e6e55eb77c799b5c1be48", "size": "1338", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/containers/editor/BlogEditor/Content/RSSInputer.tsx", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "5475" }, { "name": "JavaScript", "bytes": "449787" } ], "symlink_target": "" }
package liquibase.ext.ora.enabletrigger; import liquibase.Contexts; import liquibase.ext.ora.testing.BaseTestCase; import org.dbunit.Assertion; import org.dbunit.database.DatabaseConnection; import org.dbunit.database.IDatabaseConnection; import org.dbunit.database.QueryDataSet; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSet; import org.junit.Before; import org.junit.Test; public class EnableTriggerDBTest extends BaseTestCase { private IDataSet loadedDataSet; private final String TABLE_NAME = "USER_TRIGGERS"; @Before public void setUp() throws Exception { changeLogFile = "liquibase/ext/ora/enabletrigger/changelog.test.xml"; connectToDB(); cleanDB(); } protected IDatabaseConnection getConnection() throws Exception { return new DatabaseConnection(connection); } protected IDataSet getDataSet() throws Exception { loadedDataSet = new FlatXmlDataSet(this.getClass().getClassLoader().getResourceAsStream( "liquibase/ext/ora/enabletrigger/input.xml")); return loadedDataSet; } @Test public void testCompare() throws Exception { QueryDataSet actualDataSet = new QueryDataSet(getConnection()); liquiBase.update(new Contexts()); actualDataSet.addTable("USER_TRIGGERS", "SELECT STATUS from " + TABLE_NAME + " WHERE TRIGGER_NAME = 'RENAMEDZUIOLTRIGGER'"); loadedDataSet = getDataSet(); Assertion.assertEquals(loadedDataSet, actualDataSet); } }
{ "content_hash": "e80af45e2399c22ad5e037eed71e29df", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 96, "avg_line_length": 32.395833333333336, "alnum_prop": 0.7209003215434083, "repo_name": "mrswadge/liquibase-oracle", "id": "3ab17771611a153800f47859c7ee887dc5b23cd3", "size": "1555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/liquibase/ext/ora/enabletrigger/EnableTriggerDBTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "226490" } ], "symlink_target": "" }
<?php namespace Vench\ParseContacts\Parsers; use Vench\ParseContacts\Models\PCSite; use Vench\ParseContacts\Models\PCSiteEmail; use Vench\ParseContacts\Models\PCSitePhone; use Vench\ParseContacts\Models\PCSiteAddress; /** * Created by PhpStorm. * User: vench * Date: 13.08.17 * Time: 16:17 */ abstract class AbParser { /** * @return AbParser[] */ public static function getListParsers() { return [ new YandexParser(), new HCardParse(), new PregMathParse(), ]; } /** * @param PCSite $model * @return boolean */ abstract public function parse(PCSite $model); /** * @param PCSite $model * @param attay $adrs array of string */ protected function addAddrs(PCSite $model, $adrs) { $issets = []; foreach ($model->pcSiteAddresses as $item) { $issets[$item->address] = true; } foreach ($adrs as $adr) { if(!isset($issets[$adr])) { $newItem = new PCSiteAddress(); $newItem->address = $adr; $newItem->site_id = $model->id; $newItem->sessia = 1; $newItem->save(); $model->refresh(); } } } /** * @param PCSite $model * @param array $tels array of string */ protected function addTels(PCSite $model, $tels) { $issets = []; foreach ($model->pcSitePhones as $item) { $issets[$item->phone] = true; } foreach ($tels as $tel) { if (!isset($issets[$tel])) { $newItem = new PCSitePhone(); $newItem->phone = $tel; $newItem->site_id = $model->id; $newItem->sessia = 1; $newItem->save(); $model->refresh(); } } } /** * @param PCSite $model * @param array $emails array of string */ protected function addEmails(PCSite $model, $emails) { $issets = []; foreach ($model->pcSiteEmails as $item) { $issets[$item->email] = true; } foreach ($emails as $email) { if (!isset($issets[$email])) { $newItem = new PCSiteEmail(); $newItem->email = $email; $newItem->site_id = $model->id; $newItem->sessia = 1; $newItem->save(); $model->refresh(); } } } /** * @param string $url * @return bool|string */ protected function getContent($url) { $opts = [ "http" => [ "method" => "GET", "header" => "Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36\r\n" ] ]; $context = stream_context_create($opts); try { return file_get_contents($url, false, $context); } catch (\Exception $e) {} return ''; } /** * @param string $phone * @return string */ protected function normallyPhone($phone) { return preg_replace('/[^0-9\+]/', '', $phone); } }
{ "content_hash": "f3d8fb18682d598eb4a684d8506c7ade", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 143, "avg_line_length": 24.496296296296297, "alnum_prop": 0.4820078621106743, "repo_name": "vench/yii2-parse-contacts", "id": "22b8db6bceda40c2fe7242f88dab4445cd1e7e41", "size": "3307", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "parsers/AbParser.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "46909" } ], "symlink_target": "" }
package ru.job4j.listtask.nodecycle; public class Node<T> { T value; Node<T> next; public Node(T value) { this.value = value; } }
{ "content_hash": "ef9f764f654f2ac6078fffdfafda01ff", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 36, "avg_line_length": 13.166666666666666, "alnum_prop": 0.5822784810126582, "repo_name": "nikolai-m/nmatveev", "id": "5f77d11b141cc83073ce58856cfbdd5a8d09111e", "size": "158", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_201/src/main/java/ru/job4j/listtask/nodecycle/Node.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "329093" }, { "name": "XSLT", "bytes": "330" } ], "symlink_target": "" }
""" PySpark supports custom serializers for transferring data; this can improve performance. By default, PySpark uses L{PickleSerializer} to serialize objects using Python's C{cPickle} serializer, which can serialize nearly any Python object. Other serializers, like L{MarshalSerializer}, support fewer datatypes but can be faster. The serializer is chosen when creating L{SparkContext}: >>> from pyspark.context import SparkContext >>> from pyspark.serializers import MarshalSerializer >>> sc = SparkContext('local', 'test', serializer=MarshalSerializer()) >>> sc.parallelize(list(range(1000))).map(lambda x: 2 * x).take(10) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>> sc.stop() By default, PySpark serialize objects in batches; the batch size can be controlled through SparkContext's C{batchSize} parameter (the default size is 1024 objects): >>> sc = SparkContext('local', 'test', batchSize=2) >>> rdd = sc.parallelize(range(16), 4).map(lambda x: x) Behind the scenes, this creates a JavaRDD with four partitions, each of which contains two batches of two objects: >>> rdd.glom().collect() [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]] >>> rdd._jrdd.count() 8L >>> sc.stop() A batch size of -1 uses an unlimited batch size, and a size of 1 disables batching: >>> sc = SparkContext('local', 'test', batchSize=1) >>> rdd = sc.parallelize(range(16), 4).map(lambda x: x) >>> rdd.glom().collect() [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]] >>> rdd._jrdd.count() 16L """ import cPickle from itertools import chain, izip, product import marshal import struct from pyspark import cloudpickle __all__ = ["PickleSerializer", "MarshalSerializer"] class SpecialLengths(object): END_OF_DATA_SECTION = -1 PYTHON_EXCEPTION_THROWN = -2 TIMING_DATA = -3 class Serializer(object): def dump_stream(self, iterator, stream): """ Serialize an iterator of objects to the output stream. """ raise NotImplementedError def load_stream(self, stream): """ Return an iterator of deserialized objects from the input stream. """ raise NotImplementedError def _load_stream_without_unbatching(self, stream): return self.load_stream(stream) # Note: our notion of "equality" is that output generated by # equal serializers can be deserialized using the same serializer. # This default implementation handles the simple cases; # subclasses should override __eq__ as appropriate. def __eq__(self, other): return isinstance(other, self.__class__) def __ne__(self, other): return not self.__eq__(other) class FramedSerializer(Serializer): """ Serializer that writes objects as a stream of (length, data) pairs, where C{length} is a 32-bit integer and data is C{length} bytes. """ def dump_stream(self, iterator, stream): for obj in iterator: self._write_with_length(obj, stream) def load_stream(self, stream): while True: try: yield self._read_with_length(stream) except EOFError: return def _write_with_length(self, obj, stream): serialized = self.dumps(obj) write_int(len(serialized), stream) stream.write(serialized) def _read_with_length(self, stream): length = read_int(stream) obj = stream.read(length) if obj == "": raise EOFError return self.loads(obj) def dumps(self, obj): """ Serialize an object into a byte array. When batching is used, this will be called with an array of objects. """ raise NotImplementedError def loads(self, obj): """ Deserialize an object from a byte array. """ raise NotImplementedError class BatchedSerializer(Serializer): """ Serializes a stream of objects in batches by calling its wrapped Serializer with streams of objects. """ UNLIMITED_BATCH_SIZE = -1 def __init__(self, serializer, batchSize=UNLIMITED_BATCH_SIZE): self.serializer = serializer self.batchSize = batchSize def _batched(self, iterator): if self.batchSize == self.UNLIMITED_BATCH_SIZE: yield list(iterator) else: items = [] count = 0 for item in iterator: items.append(item) count += 1 if count == self.batchSize: yield items items = [] count = 0 if items: yield items def dump_stream(self, iterator, stream): self.serializer.dump_stream(self._batched(iterator), stream) def load_stream(self, stream): return chain.from_iterable(self._load_stream_without_unbatching(stream)) def _load_stream_without_unbatching(self, stream): return self.serializer.load_stream(stream) def __eq__(self, other): return isinstance(other, BatchedSerializer) and \ other.serializer == self.serializer def __str__(self): return "BatchedSerializer<%s>" % str(self.serializer) class CartesianDeserializer(FramedSerializer): """ Deserializes the JavaRDD cartesian() of two PythonRDDs. """ def __init__(self, key_ser, val_ser): self.key_ser = key_ser self.val_ser = val_ser def load_stream(self, stream): key_stream = self.key_ser._load_stream_without_unbatching(stream) val_stream = self.val_ser._load_stream_without_unbatching(stream) key_is_batched = isinstance(self.key_ser, BatchedSerializer) val_is_batched = isinstance(self.val_ser, BatchedSerializer) for (keys, vals) in izip(key_stream, val_stream): keys = keys if key_is_batched else [keys] vals = vals if val_is_batched else [vals] for pair in product(keys, vals): yield pair def __eq__(self, other): return isinstance(other, CartesianDeserializer) and \ self.key_ser == other.key_ser and self.val_ser == other.val_ser def __str__(self): return "CartesianDeserializer<%s, %s>" % \ (str(self.key_ser), str(self.val_ser)) class NoOpSerializer(FramedSerializer): def loads(self, obj): return obj def dumps(self, obj): return obj class PickleSerializer(FramedSerializer): """ Serializes objects using Python's cPickle serializer: http://docs.python.org/2/library/pickle.html This serializer supports nearly any Python object, but may not be as fast as more specialized serializers. """ def dumps(self, obj): return cPickle.dumps(obj, 2) loads = cPickle.loads class CloudPickleSerializer(PickleSerializer): def dumps(self, obj): return cloudpickle.dumps(obj, 2) class MarshalSerializer(FramedSerializer): """ Serializes objects using Python's Marshal serializer: http://docs.python.org/2/library/marshal.html This serializer is faster than PickleSerializer but supports fewer datatypes. """ dumps = marshal.dumps loads = marshal.loads class UTF8Deserializer(Serializer): """ Deserializes streams written by getBytes. """ def loads(self, stream): length = read_int(stream) return stream.read(length).decode('utf8') def load_stream(self, stream): while True: try: yield self.loads(stream) except struct.error: return except EOFError: return def read_long(stream): length = stream.read(8) if length == "": raise EOFError return struct.unpack("!q", length)[0] def write_long(value, stream): stream.write(struct.pack("!q", value)) def pack_long(value): return struct.pack("!q", value) def read_int(stream): length = stream.read(4) if length == "": raise EOFError return struct.unpack("!i", length)[0] def write_int(value, stream): stream.write(struct.pack("!i", value)) def write_with_length(obj, stream): write_int(len(obj), stream) stream.write(obj)
{ "content_hash": "8fe9cb97bad100b0af0bc7d4eca2d66a", "timestamp": "", "source": "github", "line_count": 294, "max_line_length": 81, "avg_line_length": 28, "alnum_prop": 0.6313168124392614, "repo_name": "sryza/spark", "id": "8c6ad79059c2385599d9aa61e3ad9c867f8240c7", "size": "9017", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "python/pyspark/serializers.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9210" }, { "name": "Java", "bytes": "215550" }, { "name": "JavaScript", "bytes": "19550" }, { "name": "Python", "bytes": "250891" }, { "name": "Ruby", "bytes": "2261" }, { "name": "Scala", "bytes": "3392121" }, { "name": "Shell", "bytes": "73977" } ], "symlink_target": "" }
from __future__ import absolute_import # Copyright (c) 2010-2019 openpyxl """ File manifest """ from mimetypes import MimeTypes import os.path from openpyxl.descriptors.serialisable import Serialisable from openpyxl.descriptors import String, Sequence from openpyxl.xml.functions import fromstring from openpyxl.xml.constants import ( ARC_CORE, ARC_CONTENT_TYPES, ARC_WORKBOOK, ARC_APP, ARC_THEME, ARC_STYLE, ARC_SHARED_STRINGS, EXTERNAL_LINK, THEME_TYPE, STYLES_TYPE, XLSX, XLSM, XLTM, XLTX, WORKSHEET_TYPE, COMMENTS_TYPE, SHARED_STRINGS, DRAWING_TYPE, CHART_TYPE, CHARTSHAPE_TYPE, CHARTSHEET_TYPE, CONTYPES_NS, ACTIVEX, CTRL, VBA, ) from openpyxl.xml.functions import tostring # initialise mime-types mimetypes = MimeTypes() mimetypes.add_type('application/xml', ".xml") mimetypes.add_type('application/vnd.openxmlformats-package.relationships+xml', ".rels") mimetypes.add_type("application/vnd.ms-office.vbaProject", ".bin") mimetypes.add_type("application/vnd.openxmlformats-officedocument.vmlDrawing", ".vml") mimetypes.add_type("image/x-emf", ".emf") class FileExtension(Serialisable): tagname = "Default" Extension = String() ContentType = String() def __init__(self, Extension, ContentType): self.Extension = Extension self.ContentType = ContentType class Override(Serialisable): tagname = "Override" PartName = String() ContentType = String() def __init__(self, PartName, ContentType): self.PartName = PartName self.ContentType = ContentType DEFAULT_TYPES = [ FileExtension("rels", "application/vnd.openxmlformats-package.relationships+xml"), FileExtension("xml", "application/xml"), ] DEFAULT_OVERRIDE = [ Override("/" + ARC_STYLE, STYLES_TYPE), # Styles Override("/" + ARC_THEME, THEME_TYPE), # Theme Override("/docProps/core.xml", "application/vnd.openxmlformats-package.core-properties+xml"), Override("/docProps/app.xml", "application/vnd.openxmlformats-officedocument.extended-properties+xml") ] class Manifest(Serialisable): tagname = "Types" Default = Sequence(expected_type=FileExtension, unique=True) Override = Sequence(expected_type=Override, unique=True) path = "[Content_Types].xml" __elements__ = ("Default", "Override") def __init__(self, Default=(), Override=(), ): if not Default: Default = DEFAULT_TYPES self.Default = Default if not Override: Override = DEFAULT_OVERRIDE self.Override = Override @property def filenames(self): return [part.PartName for part in self.Override] @property def extensions(self): """ Map content types to file extensions Skip parts without extensions """ exts = set([os.path.splitext(part.PartName)[-1] for part in self.Override]) return [(ext[1:], mimetypes.types_map[True][ext]) for ext in sorted(exts) if ext] def to_tree(self): """ Custom serialisation method to allow setting a default namespace """ defaults = [t.Extension for t in self.Default] for ext, mime in self.extensions: if ext not in defaults: mime = FileExtension(ext, mime) self.Default.append(mime) tree = super(Manifest, self).to_tree() tree.set("xmlns", CONTYPES_NS) return tree def __contains__(self, content_type): """ Check whether a particular content type is contained """ for t in self.Override: if t.ContentType == content_type: return True def find(self, content_type): """ Find specific content-type """ try: return next(self.findall(content_type)) except StopIteration: return def findall(self, content_type): """ Find all elements of a specific content-type """ for t in self.Override: if t.ContentType == content_type: yield t def append(self, obj): """ Add content object to the package manifest # needs a contract... """ ct = Override(PartName=obj.path, ContentType=obj.mime_type) self.Override.append(ct) def _write(self, archive, workbook): """ Write manifest to the archive """ self.append(workbook) self._write_vba(workbook) self._register_mimetypes(filenames=archive.namelist()) archive.writestr(self.path, tostring(self.to_tree())) def _register_mimetypes(self, filenames): """ Make sure that the mime type for all file extensions is registered """ for fn in filenames: ext = os.path.splitext(fn)[-1] if not ext: continue mime = mimetypes.types_map[True][ext] fe = FileExtension(ext[1:], mime) self.Default.append(fe) def _write_vba(self, workbook): """ Add content types from cached workbook when keeping VBA """ if workbook.vba_archive: node = fromstring(workbook.vba_archive.read(ARC_CONTENT_TYPES)) mf = Manifest.from_tree(node) filenames = self.filenames for override in mf.Override: if override.PartName not in (ACTIVEX, CTRL, VBA): continue if override.PartName not in filenames: self.Override.append(override)
{ "content_hash": "ad267500cb70bd6cc3e5e3856c89bc71", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 106, "avg_line_length": 26.95260663507109, "alnum_prop": 0.6092843326885881, "repo_name": "cloudera/hue", "id": "a20684d2e3d9fe432aeee2737bd30ccd4e60db4a", "size": "5687", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "desktop/core/ext-py/openpyxl-2.6.4/openpyxl/packaging/manifest.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ABAP", "bytes": "962" }, { "name": "ActionScript", "bytes": "1133" }, { "name": "Ada", "bytes": "99" }, { "name": "Assembly", "bytes": "2347" }, { "name": "AutoHotkey", "bytes": "720" }, { "name": "BASIC", "bytes": "2884" }, { "name": "Batchfile", "bytes": "143575" }, { "name": "C", "bytes": "5129166" }, { "name": "C#", "bytes": "83" }, { "name": "C++", "bytes": "718011" }, { "name": "COBOL", "bytes": "4" }, { "name": "CSS", "bytes": "680715" }, { "name": "Cirru", "bytes": "520" }, { "name": "Clojure", "bytes": "794" }, { "name": "Closure Templates", "bytes": "1072" }, { "name": "CoffeeScript", "bytes": "403" }, { "name": "ColdFusion", "bytes": "86" }, { "name": "Common Lisp", "bytes": "632" }, { "name": "Cython", "bytes": "1016963" }, { "name": "D", "bytes": "324" }, { "name": "Dart", "bytes": "489" }, { "name": "Dockerfile", "bytes": "13576" }, { "name": "EJS", "bytes": "752" }, { "name": "Eiffel", "bytes": "375" }, { "name": "Elixir", "bytes": "692" }, { "name": "Elm", "bytes": "487" }, { "name": "Emacs Lisp", "bytes": "411907" }, { "name": "Erlang", "bytes": "487" }, { "name": "Forth", "bytes": "979" }, { "name": "FreeMarker", "bytes": "1017" }, { "name": "G-code", "bytes": "521" }, { "name": "GAP", "bytes": "29873" }, { "name": "GLSL", "bytes": "512" }, { "name": "Genshi", "bytes": "946" }, { "name": "Gherkin", "bytes": "699" }, { "name": "Go", "bytes": "641" }, { "name": "Groovy", "bytes": "1080" }, { "name": "HTML", "bytes": "28328425" }, { "name": "Haml", "bytes": "920" }, { "name": "Handlebars", "bytes": "173" }, { "name": "Haskell", "bytes": "512" }, { "name": "Haxe", "bytes": "447" }, { "name": "HiveQL", "bytes": "43" }, { "name": "Io", "bytes": "140" }, { "name": "Java", "bytes": "457398" }, { "name": "JavaScript", "bytes": "39181239" }, { "name": "Jinja", "bytes": "356" }, { "name": "Julia", "bytes": "210" }, { "name": "LSL", "bytes": "2080" }, { "name": "Lean", "bytes": "213" }, { "name": "Less", "bytes": "396102" }, { "name": "Lex", "bytes": "218764" }, { "name": "Liquid", "bytes": "1883" }, { "name": "LiveScript", "bytes": "5747" }, { "name": "Lua", "bytes": "78382" }, { "name": "M4", "bytes": "1751" }, { "name": "MATLAB", "bytes": "203" }, { "name": "Makefile", "bytes": "1025937" }, { "name": "Mako", "bytes": "3644004" }, { "name": "Mask", "bytes": "597" }, { "name": "Myghty", "bytes": "936" }, { "name": "Nix", "bytes": "2212" }, { "name": "OCaml", "bytes": "539" }, { "name": "Objective-C", "bytes": "2672" }, { "name": "OpenSCAD", "bytes": "333" }, { "name": "PHP", "bytes": "662" }, { "name": "PLSQL", "bytes": "29403" }, { "name": "PLpgSQL", "bytes": "6006" }, { "name": "Pascal", "bytes": "84273" }, { "name": "Perl", "bytes": "4327" }, { "name": "PigLatin", "bytes": "371" }, { "name": "PowerShell", "bytes": "6235" }, { "name": "Procfile", "bytes": "47" }, { "name": "Pug", "bytes": "584" }, { "name": "Python", "bytes": "92881549" }, { "name": "R", "bytes": "2445" }, { "name": "Roff", "bytes": "484108" }, { "name": "Ruby", "bytes": "1098" }, { "name": "Rust", "bytes": "495" }, { "name": "SCSS", "bytes": "78508" }, { "name": "Sass", "bytes": "770" }, { "name": "Scala", "bytes": "1541" }, { "name": "Scheme", "bytes": "559" }, { "name": "Shell", "bytes": "249165" }, { "name": "Smarty", "bytes": "130" }, { "name": "SourcePawn", "bytes": "948" }, { "name": "Stylus", "bytes": "682" }, { "name": "Tcl", "bytes": "899" }, { "name": "TeX", "bytes": "165743" }, { "name": "Thrift", "bytes": "341963" }, { "name": "Twig", "bytes": "761" }, { "name": "TypeScript", "bytes": "1241396" }, { "name": "VBScript", "bytes": "938" }, { "name": "VHDL", "bytes": "830" }, { "name": "Vala", "bytes": "485" }, { "name": "Verilog", "bytes": "274" }, { "name": "Vim Snippet", "bytes": "226931" }, { "name": "Vue", "bytes": "350385" }, { "name": "XQuery", "bytes": "114" }, { "name": "XSLT", "bytes": "522199" }, { "name": "Yacc", "bytes": "1070437" }, { "name": "jq", "bytes": "4" } ], "symlink_target": "" }
module Blog module Admin class NavigationsController < ::Blog::ApplicationController layout "blog/admin" before_filter :require_admin before_filter :find_navigation, :only => [:edit, :update, :destroy] def index @navigations = Blog::Navigation.order("position ASC") end def new @navigation = Blog::Navigation.new(:position => Blog::Navigation.all.size + 1) @navigations = Blog::Navigation.order("position ASC") end def create @navigation = Blog::Navigation.new(params[:navigation]) if @navigation.save redirect_to blog.admin_navigations_path else @navigations = Blog::Navigation.order("position ASC") render :action => :new end end def edit @navigations = Blog::Navigation.where("id != ?", @navigation.id).order("position ASC") end def update if @navigation.update_attributes(params[:navigation]) redirect_to blog.admin_navigations_path else @navigations = Blog::Navigation.where("id != ?", @navigation.id).order("position ASC") render :action => :edit end end def destroy @navigation.destroy redirect_to blog.admin_navigations_path end protected def find_navigation @navigation = Blog::Navigation.find(params[:id]) end end end end
{ "content_hash": "7698e6c17145898e522892910912642c", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 96, "avg_line_length": 27.037735849056602, "alnum_prop": 0.6043265875785067, "repo_name": "resumecompanion/blog", "id": "1a1256bd218bf5882b6dcd6b7ea6d400fcdcec1c", "size": "1433", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/blog/admin/navigations_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31799" }, { "name": "HTML", "bytes": "225104" }, { "name": "JavaScript", "bytes": "27953" }, { "name": "PHP", "bytes": "2274" }, { "name": "Ruby", "bytes": "98302" } ], "symlink_target": "" }
<h2>Runoff</h2> <form> <input placeholder="DATE" ng-model="newDATE"> <input placeholder="INPT" ng-model="newINPT"> <input placeholder="PREF" ng-model="newPREF"> <input placeholder="PH" ng-model="newPH"> <input placeholder="EC" ng-model="newEC"> <button type="submit" ng-click="addrunoff(newDATE, newINPT, newPREF, newPH, newEC);newDATE = null; newINPT = null; newPREF = null; newPH = null; newEC = null;">send</button> </form> <ul id="runoffs" ng-show="runoffs.length"> <li ng-repeat="runoff in runoffs | reverse">{{runoff.DATE}}</li> </ul>
{ "content_hash": "8d282bec29f5b13adcdb96bbf206bd1c", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 175, "avg_line_length": 39.92857142857143, "alnum_prop": 0.6797853309481217, "repo_name": "lee910705/viridian", "id": "2b7ed1608c3319d2d19d5219f294e270b9ba55aa", "size": "559", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/runoff/runoff.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "928" }, { "name": "HTML", "bytes": "12868" }, { "name": "JavaScript", "bytes": "74002" } ], "symlink_target": "" }
package org.intellij.xquery.runner.rt.vendor.exist; import org.intellij.xquery.runner.rt.RunnerApp; import org.intellij.xquery.runner.rt.RunnerAppFactory; import org.intellij.xquery.runner.rt.XQueryRunConfig; import java.io.PrintStream; public class ExistRunnerAppFactory implements RunnerAppFactory { @Override public RunnerApp getInstance(XQueryRunConfig config, PrintStream output) throws Exception { return new ExistRunnerApp(config, output); } }
{ "content_hash": "bf505ecad7f9aa85f6262c246bbcf2ba", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 95, "avg_line_length": 29.6875, "alnum_prop": 0.7978947368421052, "repo_name": "ligasgr/intellij-xquery", "id": "b1cd094f567cac2ddc43f6e6f763d10ee66af1a0", "size": "1148", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "intellij-xquery-rt/src/main/java/org/intellij/xquery/runner/rt/vendor/exist/ExistRunnerAppFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "18427" }, { "name": "Java", "bytes": "3994896" }, { "name": "Lex", "bytes": "51063" }, { "name": "XQuery", "bytes": "126191" } ], "symlink_target": "" }
package eddystone // SvcUUID is Eddystone service UUID const SvcUUID = 0xFEAA var ( // SvcUUIDBytes is Eddystone service UUID in Little Endian format SvcUUIDBytes = []byte{0xAA, 0xFE} ) // Header for Eddystone frames type Header byte func (hdr Header) String() string { switch hdr { case UID: return "UID" case URL: return "URL" case TLM: return "TLM" case EID: return "EID" } return "Unknown" } // Eddystone frame types const ( // UID means UID frame UID Header = 0x00 // URL means URL frame URL = 0x10 // TLM means TLM frame TLM = 0x20 // EID means EID frame EID = 0x30 // Unknown means it may not Eddystone frame Unknown = 0xff )
{ "content_hash": "c1712ac36e4940ad47b42e50a873776a", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 66, "avg_line_length": 16.625, "alnum_prop": 0.6917293233082706, "repo_name": "suapapa/go_eddystone", "id": "e6acd044112dad00e1d28aebf90946a71070fa92", "size": "841", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "header.go", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Go", "bytes": "14578" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.nozomi.almanac" android:versionCode="12" android:versionName="1.51" > <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="19" /> <permission android:name="com.nozomi.almanac.permission.JPUSH_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="com.nozomi.almanac.permission.JPUSH_MESSAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.VIBRATE" /> <application android:name="com.nozomi.almanac.activity.AlmanacApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.nozomi.almanac.activity.SplashActivity" android:label="@string/app_name" android:screenOrientation="portrait" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.nozomi.almanac.activity.AlmanacActivity" android:label="@string/app_name" android:screenOrientation="portrait" > </activity> <activity android:name="com.nozomi.almanac.activity.AboutActivity" android:label="@string/app_name" android:screenOrientation="portrait" > </activity> <activity android:name="com.nozomi.almanac.activity.SettingActivity" android:label="@string/app_name" android:screenOrientation="portrait" > </activity> <receiver android:name="com.nozomi.almanac.activity.AlarmReceiver" /> <receiver android:name="com.nozomi.almanac.activity.WidgetAlermReceiver" /> <receiver android:name="com.nozomi.almanac.activity.BootBroadcastReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </receiver> <receiver android:name="com.nozomi.almanac.activity.WidgetProvider" > <meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_provider" > </meta-data> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> </receiver> <activity android:name="com.umeng.socialize.view.ShareActivity" android:configChanges="orientation|keyboard" android:launchMode="singleTask" android:noHistory="true" android:theme="@style/Theme.UMDialog" android:windowSoftInputMode="stateVisible|adjustResize" > </activity> <activity android:name="com.nozomi.wxapi.WXEntryActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="true" android:screenOrientation="portrait" android:theme="@android:style/Theme.Translucent.NoTitleBar" /> <service android:name="com.umeng.common.net.DownloadingService" android:process=":DownloadingService" /> <activity android:name="com.umeng.update.UpdateDialogActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" /> <meta-data android:name="UMENG_APPKEY" android:value="52cf92af56240bdbc10a3e6f" > </meta-data> <meta-data android:name="UMENG_CHANNEL" android:value="google_market" /> <service android:name="cn.jpush.android.service.PushService" android:enabled="true" android:exported="false" > <intent-filter> <action android:name="cn.jpush.android.intent.REGISTER" /> <action android:name="cn.jpush.android.intent.REPORT" /> <action android:name="cn.jpush.android.intent.PushService" /> <action android:name="cn.jpush.android.intent.PUSH_TIME" /> </intent-filter> </service> <!-- Required --> <receiver android:name="cn.jpush.android.service.PushReceiver" android:enabled="true" > <intent-filter android:priority="1000" > <!-- since 1.3.5 --> <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY" /> <!-- since 1.3.5 --> <category android:name="com.nozomi.almanac" /> <!-- since 1.3.5 --> </intent-filter> <!-- since 1.3.5 --> <intent-filter> <action android:name="android.intent.action.USER_PRESENT" /> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PACKAGE_ADDED" /> <action android:name="android.intent.action.PACKAGE_REMOVED" /> <data android:scheme="package" /> </intent-filter> </receiver> <activity android:name="cn.jpush.android.ui.PushActivity" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Translucent.NoTitleBar" > <intent-filter> <action android:name="cn.jpush.android.ui.PushActivity" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="com.nozomi.almanac" /> </intent-filter> </activity> <service android:name="cn.jpush.android.service.DownloadService" android:enabled="true" android:exported="false" > </service> <receiver android:name="cn.jpush.android.service.AlarmReceiver" /> <meta-data android:name="JPUSH_CHANNEL" android:value="google_market" /> <meta-data android:name="JPUSH_APPKEY" android:value="f281dcfb009ded90ba3f9a0b" /> </application> </manifest>
{ "content_hash": "f89800ff372ccbec3b78e5abde468870", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 114, "avg_line_length": 42.11176470588235, "alnum_prop": 0.6136331889928761, "repo_name": "xuyangbill/AcfunAlmanac", "id": "abfac8ff88d5cec2290c120993963c547c3f343a", "size": "7159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "49203" } ], "symlink_target": "" }
select College_jobs, Median, Unemployment_rate from recent_grads limit 20; ## 3. Where ## select major from recent_grads where Major_category = 'Arts' limit 5; ## 4. Operators ## select Major,Total,Median,Unemployment_rate from recent_grads where (Major_category != 'Engineering') and (Unemployment_rate > 0.065 or Median <= 50000); ## 5. Ordering ## select Major from recent_grads where Major_category != 'Engineering' order by Major desc limit 20;
{ "content_hash": "d906d2ad158e5f8236340c68ce649dd9", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 98, "avg_line_length": 32.57142857142857, "alnum_prop": 0.7368421052631579, "repo_name": "vipmunot/Data-Analysis-using-Python", "id": "67aa146c5fb84162dadd84c9a7bcc59de0630f4b", "size": "483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SQL and Databases Begineer/Challenge_ Practice expressing complex SQL queries-130.sql", "mode": "33188", "license": "mit", "language": [ { "name": "Jupyter Notebook", "bytes": "19716" }, { "name": "Python", "bytes": "283672" }, { "name": "R", "bytes": "7194" }, { "name": "Shell", "bytes": "9169" } ], "symlink_target": "" }
namespace Framework.Web.Mvc { using System.Security; using System.Web.Mvc; ///------------------------------------------------------------------------------------------------- /// <summary> /// Attribute for content security policy filter. /// </summary> /// /// <remarks> /// Anwar Javed, 09/25/2013 4:07 PM. /// </remarks> ///------------------------------------------------------------------------------------------------- public class ContentSecurityPolicyFilterAttribute : ActionFilterAttribute { ///------------------------------------------------------------------------------------------------- /// <summary> /// Called by the ASP.NET MVC framework before the action method executes. /// </summary> /// /// <remarks> /// Anwar Javed, 09/25/2013 4:07 PM. /// </remarks> /// /// <param name="filterContext"> /// The filter context. /// </param> ///------------------------------------------------------------------------------------------------- public override void OnActionExecuting(ActionExecutingContext filterContext) { var response = filterContext.HttpContext.Response; response.AddHeader("Content-Security-Policy", "default-src 'self'; img-src *; script-src 'self'; style-src 'self' 'unsafe-inline';"); response.AddHeader("X-WebKit-CSP", "default-src 'self'; img-src *; script-src 'self'; style-src 'self' 'unsafe-inline';"); response.AddHeader("X-Content-Security-Policy", "default-src 'self'; img-src *; script-src 'self'; style-src 'self' 'unsafe-inline';"); base.OnActionExecuting(filterContext); } } }
{ "content_hash": "a4d44320c5d8963153ad4b88fb10af20", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 147, "avg_line_length": 43.90243902439025, "alnum_prop": 0.44, "repo_name": "anwarjaved/Innosparx", "id": "a9a92d48f373074bf1e0d1ba71089e41a852dc52", "size": "1802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Framework.Web.Mvc/Web/Mvc/ContentSecurityPolicyFilterAttribute.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "2824025" } ], "symlink_target": "" }
package v1beta1 import ( "context" "github.com/google/knative-gcp/pkg/apis/duck" "knative.dev/pkg/apis" ) func (s *CloudAuditLogsSource) SetDefaults(ctx context.Context) { ctx = apis.WithinParent(ctx, s.ObjectMeta) s.Spec.SetPubSubDefaults(ctx) duck.SetAutoscalingAnnotationsDefaults(ctx, &s.ObjectMeta) }
{ "content_hash": "f86bd679177c440f5500afa9fccb373b", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 65, "avg_line_length": 19.8125, "alnum_prop": 0.7634069400630915, "repo_name": "google/knative-gcp", "id": "c227c2960905b511676822f21f45f8beca0516b3", "size": "874", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pkg/apis/events/v1beta1/cloudauditlogssource_defaults.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "3344928" }, { "name": "Shell", "bytes": "70016" } ], "symlink_target": "" }
/** * This class is generated by jOOQ */ package de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.interfaces; /** * This class is generated by jOOQ. */ @javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" }, comments = "This class is generated by jOOQ") @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public interface ISuggestion extends java.io.Serializable { /** * Getter for <code>suggestion.initiative_id</code>. */ public java.lang.Integer getInitiativeId(); /** * Getter for <code>suggestion.id</code>. */ public java.lang.Long getId(); /** * Getter for <code>suggestion.draft_id</code>. */ public java.lang.Long getDraftId(); /** * Getter for <code>suggestion.created</code>. */ public java.sql.Timestamp getCreated(); /** * Getter for <code>suggestion.author_id</code>. */ public java.lang.Integer getAuthorId(); /** * Getter for <code>suggestion.name</code>. */ public java.lang.String getName(); /** * Getter for <code>suggestion.formatting_engine</code>. */ public java.lang.String getFormattingEngine(); /** * Getter for <code>suggestion.content</code>. */ public java.lang.String getContent(); /** * Getter for <code>suggestion.text_search_data</code>. */ public java.lang.Object getTextSearchData(); /** * Getter for <code>suggestion.minus2_unfulfilled_count</code>. */ public java.lang.Integer getMinus2UnfulfilledCount(); /** * Getter for <code>suggestion.minus2_fulfilled_count</code>. */ public java.lang.Integer getMinus2FulfilledCount(); /** * Getter for <code>suggestion.minus1_unfulfilled_count</code>. */ public java.lang.Integer getMinus1UnfulfilledCount(); /** * Getter for <code>suggestion.minus1_fulfilled_count</code>. */ public java.lang.Integer getMinus1FulfilledCount(); /** * Getter for <code>suggestion.plus1_unfulfilled_count</code>. */ public java.lang.Integer getPlus1UnfulfilledCount(); /** * Getter for <code>suggestion.plus1_fulfilled_count</code>. */ public java.lang.Integer getPlus1FulfilledCount(); /** * Getter for <code>suggestion.plus2_unfulfilled_count</code>. */ public java.lang.Integer getPlus2UnfulfilledCount(); /** * Getter for <code>suggestion.plus2_fulfilled_count</code>. */ public java.lang.Integer getPlus2FulfilledCount(); /** * Getter for <code>suggestion.proportional_order</code>. */ public java.lang.Integer getProportionalOrder(); }
{ "content_hash": "a1155f7ff85bae82d9d7badcf6904432", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 77, "avg_line_length": 24.281553398058254, "alnum_prop": 0.6877249100359856, "repo_name": "plattformbrandenburg/ldadmin", "id": "ea7c31e3af21c0038dc8eea136372a5b86226f96", "size": "2501", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/de/piratenpartei/berlin/ldadmin/dbaccess/generated/tables/interfaces/ISuggestion.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2192262" } ], "symlink_target": "" }
package com.google.cloud.dataflow.sdk.io; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.JAXBCoder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.common.base.Preconditions; import org.codehaus.stax2.XMLInputFactory2; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.SequenceInputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; import java.util.NoSuchElementException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; // CHECKSTYLE.OFF: JavadocStyle /** * A source that can be used to read XML files. This source reads one or more * XML files and creates a {@code PCollection} of a given type. An Dataflow read transform can be * created by passing an {@code XmlSource} object to {@code Read.from()}. Please note the * example given below. * * <p>The XML file must be of the following form, where {@code root} and {@code record} are XML * element names that are defined by the user: * * <pre> * {@code * <root> * <record> ... </record> * <record> ... </record> * <record> ... </record> * ... * <record> ... </record> * </root> * } * </pre> * * <p>Basically, the XML document should contain a single root element with an inner list consisting * entirely of record elements. The records may contain arbitrary XML content; however, that content * <b>must not</b> contain the start {@code <record>} or end {@code </record>} tags. This * restriction enables reading from large XML files in parallel from different offsets in the file. * * <p>Root and/or record elements may additionally contain an arbitrary number of XML attributes. * Additionally users must provide a class of a JAXB annotated Java type that can be used convert * records into Java objects and vice versa using JAXB marshalling/unmarshalling mechanisms. Reading * the source will generate a {@code PCollection} of the given JAXB annotated Java type. * Optionally users may provide a minimum size of a bundle that should be created for the source. * * <p>The following example shows how to read from {@link XmlSource} in a Dataflow pipeline: * * <pre> * {@code * XmlSource<String> source = XmlSource.<String>from(file.toPath().toString()) * .withRootElement("root") * .withRecordElement("record") * .withRecordClass(Record.class); * PCollection<String> output = p.apply(Read.from(source)); * } * </pre> * * <p>Currently, only XML files that use single-byte characters are supported. Using a file that * contains multi-byte characters may result in data loss or duplication. * * <p>To use {@code XmlSource}, explicitly declare dependencies on following two jars from Woodstox * StAX XML parser. * (1) stax2-api-3.1.1.jar * (2) woodstox-core-asl-4.1.2.jar * These dependencies have been declared as optional in Maven sdk/pom.xml file of Google Cloud * Dataflow. * * <p><h3>Permissions</h3> * Permission requirements depend on the * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner PipelineRunner} that is * used to execute the Dataflow job. Please refer to the documentation of corresponding * {@code PipelineRunner}s for more details. * * @param <T> Type of the objects that represent the records of the XML file. The * {@code PCollection} generated by this source will be of this type. */ // CHECKSTYLE.ON: JavadocStyle public class XmlSource<T> extends FileBasedSource<T> { private static final String XML_VERSION = "1.1"; private static final int DEFAULT_MIN_BUNDLE_SIZE = 8 * 1024; private final String rootElement; private final String recordElement; private final Class<T> recordClass; /** * Creates an XmlSource for a single XML file or a set of XML files defined by a Java "glob" file * pattern. Each XML file should be of the form defined in {@link XmlSource}. */ public static <T> XmlSource<T> from(String fileOrPatternSpec) { return new XmlSource<>(fileOrPatternSpec, DEFAULT_MIN_BUNDLE_SIZE, null, null, null); } /** * Sets name of the root element of the XML document. This will be used to create a valid starting * root element when initiating a bundle of records created from an XML document. This is a * required parameter. */ public XmlSource<T> withRootElement(String rootElement) { return new XmlSource<>( getFileOrPatternSpec(), getMinBundleSize(), rootElement, recordElement, recordClass); } /** * Sets name of the record element of the XML document. This will be used to determine offset of * the first record of a bundle created from the XML document. This is a required parameter. */ public XmlSource<T> withRecordElement(String recordElement) { return new XmlSource<>( getFileOrPatternSpec(), getMinBundleSize(), rootElement, recordElement, recordClass); } /** * Sets a JAXB annotated class that can be populated using a record of the provided XML file. This * will be used when unmarshalling record objects from the XML file. This is a required * parameter. */ public XmlSource<T> withRecordClass(Class<T> recordClass) { return new XmlSource<>( getFileOrPatternSpec(), getMinBundleSize(), rootElement, recordElement, recordClass); } /** * Sets a parameter {@code minBundleSize} for the minimum bundle size of the source. Please refer * to {@link OffsetBasedSource} for the definition of minBundleSize. This is an optional * parameter. */ public XmlSource<T> withMinBundleSize(long minBundleSize) { return new XmlSource<>( getFileOrPatternSpec(), minBundleSize, rootElement, recordElement, recordClass); } private XmlSource(String fileOrPattern, long minBundleSize, String rootElement, String recordElement, Class<T> recordClass) { super(fileOrPattern, minBundleSize); this.rootElement = rootElement; this.recordElement = recordElement; this.recordClass = recordClass; } private XmlSource(String fileOrPattern, long minBundleSize, long startOffset, long endOffset, String rootElement, String recordElement, Class<T> recordClass) { super(fileOrPattern, minBundleSize, startOffset, endOffset); this.rootElement = rootElement; this.recordElement = recordElement; this.recordClass = recordClass; } @Override public FileBasedSource<T> createForSubrangeOfFile(String fileName, long start, long end) { return new XmlSource<T>( fileName, getMinBundleSize(), start, end, rootElement, recordElement, recordClass); } @Override public FileBasedReader<T> createSingleFileReader(PipelineOptions options) { return new XMLReader<T>(this); } @Override public boolean producesSortedKeys(PipelineOptions options) throws Exception { return false; } @Override public void validate() { super.validate(); Preconditions.checkNotNull( rootElement, "rootElement is null. Use builder method withRootElement() to set this."); Preconditions.checkNotNull( recordElement, "recordElement is null. Use builder method withRecordElement() to set this."); Preconditions.checkNotNull( recordClass, "recordClass is null. Use builder method withRecordClass() to set this."); } @Override public Coder<T> getDefaultOutputCoder() { return JAXBCoder.of(recordClass); } public String getRootElement() { return rootElement; } public String getRecordElement() { return recordElement; } public Class<T> getRecordClass() { return recordClass; } /** * A {@link Source.Reader} for reading JAXB annotated Java objects from an XML file. The XML * file should be of the form defined at {@link XmlSource}. * * <p>Timestamped values are currently unsupported - all values implicitly have the timestamp * of {@code BoundedWindow.TIMESTAMP_MIN_VALUE}. * * @param <T> Type of objects that will be read by the reader. */ private static class XMLReader<T> extends FileBasedReader<T> { // The amount of bytes read from the channel to memory when determining the starting offset of // the first record in a bundle. After matching to starting offset of the first record the // remaining bytes read to this buffer and the bytes still not read from the channel are used to // create the XML parser. private static final int BUF_SIZE = 1024; // This should be the maximum number of bytes a character will encode to, for any encoding // supported by XmlSource. Currently this is set to 4 since UTF-8 characters may be // four bytes. private static final int MAX_CHAR_BYTES = 4; // In order to support reading starting in the middle of an XML file, we construct an imaginary // well-formed document (a header and root tag followed by the contents of the input starting at // the record boundary) and feed it to the parser. Because of this, the offset reported by the // XML parser is not the same as offset in the original file. They differ by a constant amount: // offsetInOriginalFile = parser.getLocation().getCharacterOffset() + parserBaseOffset; // Note that this is true only for files with single-byte characters. // It appears that, as of writing, there does not exist a Java XML parser capable of correctly // reporting byte offsets of elements in the presence of multi-byte characters. private long parserBaseOffset = 0; private boolean readingStarted = false; // If true, the current bundle does not contain any records. private boolean emptyBundle = false; private Unmarshaller jaxbUnmarshaller = null; private XMLStreamReader parser = null; private T currentRecord = null; // Byte offset of the current record in the XML file provided when creating the source. private long currentByteOffset = 0; public XMLReader(XmlSource<T> source) { super(source); // Set up a JAXB Unmarshaller that can be used to unmarshall record objects. try { JAXBContext jaxbContext = JAXBContext.newInstance(getCurrentSource().recordClass); jaxbUnmarshaller = jaxbContext.createUnmarshaller(); // Throw errors if validation fails. JAXB by default ignores validation errors. jaxbUnmarshaller.setEventHandler(new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); } catch (JAXBException e) { throw new RuntimeException(e); } } @Override public synchronized XmlSource<T> getCurrentSource() { return (XmlSource<T>) super.getCurrentSource(); } @Override protected void startReading(ReadableByteChannel channel) throws IOException { // This method determines the correct starting offset of the first record by reading bytes // from the ReadableByteChannel. This implementation does not need the channel to be a // SeekableByteChannel. // The method tries to determine the first record element in the byte channel. The first // record must start with the characters "<recordElement" where "recordElement" is the // record element of the XML document described above. For the match to be complete this // has to be followed by one of following. // * any whitespace character // * '>' character // * '/' character (to support empty records). // // After this match this method creates the XML parser for parsing the XML document, // feeding it a fake document consisting of an XML header and the <rootElement> tag followed // by the contents of channel starting from <recordElement. The <rootElement> tag may be never // closed. // This stores any bytes that should be used prior to the remaining bytes of the channel when // creating an XML parser object. ByteArrayOutputStream preambleByteBuffer = new ByteArrayOutputStream(); // A dummy declaration and root for the document with proper XML version and encoding. Without // this XML parsing may fail or may produce incorrect results. byte[] dummyStartDocumentBytes = ("<?xml version=\"" + XML_VERSION + "\" encoding=\"UTF-8\" ?>" + "<" + getCurrentSource().rootElement + ">").getBytes(StandardCharsets.UTF_8); preambleByteBuffer.write(dummyStartDocumentBytes); // Gets the byte offset (in the input file) of the first record in ReadableByteChannel. This // method returns the offset and stores any bytes that should be used when creating the XML // parser in preambleByteBuffer. long offsetInFileOfRecordElement = getFirstOccurenceOfRecordElement(channel, preambleByteBuffer); if (offsetInFileOfRecordElement < 0) { // Bundle has no records. So marking this bundle as an empty bundle. emptyBundle = true; return; } else { byte[] preambleBytes = preambleByteBuffer.toByteArray(); currentByteOffset = offsetInFileOfRecordElement; setUpXMLParser(channel, preambleBytes); parserBaseOffset = offsetInFileOfRecordElement - dummyStartDocumentBytes.length; } readingStarted = true; } // Gets the first occurrence of the next record within the given ReadableByteChannel. Puts // any bytes read past the starting offset of the next record back to the preambleByteBuffer. // If a record is found, returns the starting offset of the record, otherwise // returns -1. private long getFirstOccurenceOfRecordElement( ReadableByteChannel channel, ByteArrayOutputStream preambleByteBuffer) throws IOException { int byteIndexInRecordElementToMatch = 0; // Index of the byte in the string "<recordElement" to be matched // against the current byte from the stream. boolean recordStartBytesMatched = false; // "<recordElement" matched. Still have to match the // next character to confirm if this is a positive match. boolean fullyMatched = false; // If true, record element was fully matched. // This gives the offset of the byte currently being read. We do a '-1' here since we // increment this value at the beginning of the while loop below. long offsetInFileOfCurrentByte = getCurrentSource().getStartOffset() - 1; long startingOffsetInFileOfCurrentMatch = -1; // If this is non-negative, currently there is a match in progress and this value gives the // starting offset of the match currently being conducted. boolean matchStarted = false; // If true, a match is currently in progress. // These two values are used to determine the character immediately following a match for // "<recordElement". Please see the comment for 'MAX_CHAR_BYTES' above. byte[] charBytes = new byte[MAX_CHAR_BYTES]; int charBytesFound = 0; ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE); byte[] recordStartBytes = ("<" + getCurrentSource().recordElement).getBytes(StandardCharsets.UTF_8); outer: while (channel.read(buf) > 0) { buf.flip(); while (buf.hasRemaining()) { offsetInFileOfCurrentByte++; byte b = buf.get(); boolean reset = false; if (recordStartBytesMatched) { // We already matched "<recordElement" reading the next character to determine if this // is a positive match for a new record. charBytes[charBytesFound] = b; charBytesFound++; Character c = null; if (charBytesFound == charBytes.length) { CharBuffer charBuf = CharBuffer.allocate(1); InputStream charBufStream = new ByteArrayInputStream(charBytes); java.io.Reader reader = new InputStreamReader(charBufStream, StandardCharsets.UTF_8); int read = reader.read(); if (read <= 0) { return -1; } charBuf.flip(); c = (char) read; } else { continue; } // Record start may be of following forms // * "<recordElement<whitespace>..." // * "<recordElement>..." // * "<recordElement/..." if (Character.isWhitespace(c) || c == '>' || c == '/') { fullyMatched = true; // Add the recordStartBytes and charBytes to preambleByteBuffer since these were // already read from the channel. preambleByteBuffer.write(recordStartBytes); preambleByteBuffer.write(charBytes); // Also add the rest of the current buffer to preambleByteBuffer. while (buf.hasRemaining()) { preambleByteBuffer.write(buf.get()); } break outer; } else { // Matching was unsuccessful. Reset the buffer to include bytes read for the char. ByteBuffer newbuf = ByteBuffer.allocate(BUF_SIZE); newbuf.put(charBytes); offsetInFileOfCurrentByte -= charBytes.length; while (buf.hasRemaining()) { newbuf.put(buf.get()); } newbuf.flip(); buf = newbuf; // Ignore everything and try again starting from the current buffer. reset = true; } } else if (b == recordStartBytes[byteIndexInRecordElementToMatch]) { // Next byte matched. if (!matchStarted) { // Match was for the first byte, record the starting offset. matchStarted = true; startingOffsetInFileOfCurrentMatch = offsetInFileOfCurrentByte; } byteIndexInRecordElementToMatch++; } else { // Not a match. Ignore everything and try again starting at current point. reset = true; } if (reset) { // Clear variables and try to match starting from the next byte. byteIndexInRecordElementToMatch = 0; startingOffsetInFileOfCurrentMatch = -1; matchStarted = false; recordStartBytesMatched = false; charBytes = new byte[MAX_CHAR_BYTES]; charBytesFound = 0; } if (byteIndexInRecordElementToMatch == recordStartBytes.length) { // "<recordElement" matched. Need to still check next byte since this might be an // element that has "recordElement" as a prefix. recordStartBytesMatched = true; } } buf.clear(); } if (!fullyMatched) { return -1; } else { return startingOffsetInFileOfCurrentMatch; } } private void setUpXMLParser(ReadableByteChannel channel, byte[] lookAhead) throws IOException { try { // We use Woodstox because the StAX implementation provided by OpenJDK reports // character locations incorrectly. Note that Woodstox still currently reports *byte* // locations incorrectly when parsing documents that contain multi-byte characters. XMLInputFactory2 xmlInputFactory = (XMLInputFactory2) XMLInputFactory.newInstance(); this.parser = xmlInputFactory.createXMLStreamReader( new SequenceInputStream( new ByteArrayInputStream(lookAhead), Channels.newInputStream(channel)), "UTF-8"); // Current offset should be the offset before reading the record element. while (true) { int event = parser.next(); if (event == XMLStreamConstants.START_ELEMENT) { String localName = parser.getLocalName(); if (localName.equals(getCurrentSource().recordElement)) { break; } } } } catch (FactoryConfigurationError | XMLStreamException e) { throw new IOException(e); } } @Override protected boolean readNextRecord() throws IOException { if (emptyBundle) { currentByteOffset = Long.MAX_VALUE; return false; } try { // Update current offset and check if the next value is the record element. currentByteOffset = parserBaseOffset + parser.getLocation().getCharacterOffset(); while (parser.getEventType() != XMLStreamConstants.START_ELEMENT) { parser.next(); currentByteOffset = parserBaseOffset + parser.getLocation().getCharacterOffset(); if (parser.getEventType() == XMLStreamConstants.END_DOCUMENT) { currentByteOffset = Long.MAX_VALUE; return false; } } JAXBElement<T> jb = jaxbUnmarshaller.unmarshal(parser, getCurrentSource().recordClass); currentRecord = jb.getValue(); return true; } catch (JAXBException | XMLStreamException e) { throw new IOException(e); } } @Override public T getCurrent() throws NoSuchElementException { if (!readingStarted) { throw new NoSuchElementException(); } return currentRecord; } @Override protected boolean isAtSplitPoint() { // Every record is at a split point. return true; } @Override protected long getCurrentOffset() { return currentByteOffset; } } }
{ "content_hash": "8d5fd98371ed224dcc16f9e2ecf31b0b", "timestamp": "", "source": "github", "line_count": 525, "max_line_length": 100, "avg_line_length": 42.011428571428574, "alnum_prop": 0.6808578164671745, "repo_name": "Test-Betta-Inc/musical-umbrella", "id": "668361b7d953d7e44abe2976d15b50e45e62a2f2", "size": "22644", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "6354257" }, { "name": "Protocol Buffer", "bytes": "10419" }, { "name": "Shell", "bytes": "3238" } ], "symlink_target": "" }
package net.sourceforge.plantuml.graph; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.geom.Dimension2D; import net.sourceforge.plantuml.Dimension2DDouble; import net.sourceforge.plantuml.cucadiagram.IEntity; import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.ugraphic.ColorMapper; class EntityImageActivityBranch extends AbstractEntityImage { private final int size = 10; public EntityImageActivityBranch(IEntity entity) { super(entity); } @Override public Dimension2D getDimension(StringBounder stringBounder) { return new Dimension2DDouble(size * 2, size * 2); } @Override public void draw(ColorMapper colorMapper, Graphics2D g2d) { final Polygon p = new Polygon(); p.addPoint(size, 0); p.addPoint(size * 2, size); p.addPoint(size, size * 2); p.addPoint(0, size); g2d.setColor(colorMapper.getMappedColor(getYellow())); g2d.fill(p); g2d.setColor(colorMapper.getMappedColor(getRed())); g2d.draw(p); } }
{ "content_hash": "dda132872b446b2cf6d30a82e6a2a070", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 63, "avg_line_length": 25.692307692307693, "alnum_prop": 0.7674650698602794, "repo_name": "Banno/sbt-plantuml-plugin", "id": "1a2f2dba600f90179e5b2dd548d5bd4659e6339b", "size": "1921", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/sourceforge/plantuml/graph/EntityImageActivityBranch.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "12451864" }, { "name": "Scala", "bytes": "7987" }, { "name": "Shell", "bytes": "1069" } ], "symlink_target": "" }