code
stringlengths
4
1.01M
language
stringclasses
2 values
Trying to figure out: * Why two hierarchies? * How do they differ? * Do they share any entities? Approach: Make a XE db and have a look.
Java
/* * Copyright 2018 Mauricio Colli <mauriciocolli@outlook.com> * AnimationUtils.java is part of NewPipe * * License: GPL-3.0+ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.schabi.newpipe.util; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ArgbEvaluator; import android.animation.ValueAnimator; import android.content.res.ColorStateList; import android.util.Log; import android.view.View; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.FloatRange; import androidx.core.view.ViewCompat; import androidx.interpolator.view.animation.FastOutSlowInInterpolator; import org.schabi.newpipe.MainActivity; public final class AnimationUtils { private static final String TAG = "AnimationUtils"; private static final boolean DEBUG = MainActivity.DEBUG; private AnimationUtils() { } public static void animateView(final View view, final boolean enterOrExit, final long duration) { animateView(view, Type.ALPHA, enterOrExit, duration, 0, null); } public static void animateView(final View view, final boolean enterOrExit, final long duration, final long delay) { animateView(view, Type.ALPHA, enterOrExit, duration, delay, null); } public static void animateView(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { animateView(view, Type.ALPHA, enterOrExit, duration, delay, execOnEnd); } public static void animateView(final View view, final Type animationType, final boolean enterOrExit, final long duration) { animateView(view, animationType, enterOrExit, duration, 0, null); } public static void animateView(final View view, final Type animationType, final boolean enterOrExit, final long duration, final long delay) { animateView(view, animationType, enterOrExit, duration, delay, null); } /** * Animate the view. * * @param view view that will be animated * @param animationType {@link Type} of the animation * @param enterOrExit true to enter, false to exit * @param duration how long the animation will take, in milliseconds * @param delay how long the animation will wait to start, in milliseconds * @param execOnEnd runnable that will be executed when the animation ends */ public static void animateView(final View view, final Type animationType, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (DEBUG) { String id; try { id = view.getResources().getResourceEntryName(view.getId()); } catch (final Exception e) { id = view.getId() + ""; } final String msg = String.format("%8s → [%s:%s] [%s %s:%s] execOnEnd=%s", enterOrExit, view.getClass().getSimpleName(), id, animationType, duration, delay, execOnEnd); Log.d(TAG, "animateView()" + msg); } if (view.getVisibility() == View.VISIBLE && enterOrExit) { if (DEBUG) { Log.d(TAG, "animateView() view was already visible > view = [" + view + "]"); } view.animate().setListener(null).cancel(); view.setVisibility(View.VISIBLE); view.setAlpha(1f); if (execOnEnd != null) { execOnEnd.run(); } return; } else if ((view.getVisibility() == View.GONE || view.getVisibility() == View.INVISIBLE) && !enterOrExit) { if (DEBUG) { Log.d(TAG, "animateView() view was already gone > view = [" + view + "]"); } view.animate().setListener(null).cancel(); view.setVisibility(View.GONE); view.setAlpha(0f); if (execOnEnd != null) { execOnEnd.run(); } return; } view.animate().setListener(null).cancel(); view.setVisibility(View.VISIBLE); switch (animationType) { case ALPHA: animateAlpha(view, enterOrExit, duration, delay, execOnEnd); break; case SCALE_AND_ALPHA: animateScaleAndAlpha(view, enterOrExit, duration, delay, execOnEnd); break; case LIGHT_SCALE_AND_ALPHA: animateLightScaleAndAlpha(view, enterOrExit, duration, delay, execOnEnd); break; case SLIDE_AND_ALPHA: animateSlideAndAlpha(view, enterOrExit, duration, delay, execOnEnd); break; case LIGHT_SLIDE_AND_ALPHA: animateLightSlideAndAlpha(view, enterOrExit, duration, delay, execOnEnd); break; } } /** * Animate the background color of a view. * * @param view the view to animate * @param duration the duration of the animation * @param colorStart the background color to start with * @param colorEnd the background color to end with */ public static void animateBackgroundColor(final View view, final long duration, @ColorInt final int colorStart, @ColorInt final int colorEnd) { if (DEBUG) { Log.d(TAG, "animateBackgroundColor() called with: " + "view = [" + view + "], duration = [" + duration + "], " + "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]"); } final int[][] empty = {new int[0]}; final ValueAnimator viewPropertyAnimator = ValueAnimator .ofObject(new ArgbEvaluator(), colorStart, colorEnd); viewPropertyAnimator.setInterpolator(new FastOutSlowInInterpolator()); viewPropertyAnimator.setDuration(duration); viewPropertyAnimator.addUpdateListener(animation -> ViewCompat.setBackgroundTintList(view, new ColorStateList(empty, new int[]{(int) animation.getAnimatedValue()}))); viewPropertyAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { ViewCompat.setBackgroundTintList(view, new ColorStateList(empty, new int[]{colorEnd})); } @Override public void onAnimationCancel(final Animator animation) { onAnimationEnd(animation); } }); viewPropertyAnimator.start(); } /** * Animate the text color of any view that extends {@link TextView} (Buttons, EditText...). * * @param view the text view to animate * @param duration the duration of the animation * @param colorStart the text color to start with * @param colorEnd the text color to end with */ public static void animateTextColor(final TextView view, final long duration, @ColorInt final int colorStart, @ColorInt final int colorEnd) { if (DEBUG) { Log.d(TAG, "animateTextColor() called with: " + "view = [" + view + "], duration = [" + duration + "], " + "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]"); } final ValueAnimator viewPropertyAnimator = ValueAnimator .ofObject(new ArgbEvaluator(), colorStart, colorEnd); viewPropertyAnimator.setInterpolator(new FastOutSlowInInterpolator()); viewPropertyAnimator.setDuration(duration); viewPropertyAnimator.addUpdateListener(animation -> view.setTextColor((int) animation.getAnimatedValue())); viewPropertyAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setTextColor(colorEnd); } @Override public void onAnimationCancel(final Animator animation) { view.setTextColor(colorEnd); } }); viewPropertyAnimator.start(); } public static ValueAnimator animateHeight(final View view, final long duration, final int targetHeight) { final int height = view.getHeight(); if (DEBUG) { Log.d(TAG, "animateHeight: duration = [" + duration + "], " + "from " + height + " to → " + targetHeight + " in: " + view); } final ValueAnimator animator = ValueAnimator.ofFloat(height, targetHeight); animator.setInterpolator(new FastOutSlowInInterpolator()); animator.setDuration(duration); animator.addUpdateListener(animation -> { final float value = (float) animation.getAnimatedValue(); view.getLayoutParams().height = (int) value; view.requestLayout(); }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.getLayoutParams().height = targetHeight; view.requestLayout(); } @Override public void onAnimationCancel(final Animator animation) { view.getLayoutParams().height = targetHeight; view.requestLayout(); } }); animator.start(); return animator; } public static void animateRotation(final View view, final long duration, final int targetRotation) { if (DEBUG) { Log.d(TAG, "animateRotation: duration = [" + duration + "], " + "from " + view.getRotation() + " to → " + targetRotation + " in: " + view); } view.animate().setListener(null).cancel(); view.animate() .rotation(targetRotation).setDuration(duration) .setInterpolator(new FastOutSlowInInterpolator()) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationCancel(final Animator animation) { view.setRotation(targetRotation); } @Override public void onAnimationEnd(final Animator animation) { view.setRotation(targetRotation); } }).start(); } private static void animateAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.animate().setInterpolator(new FastOutSlowInInterpolator()).alpha(1f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.animate().setInterpolator(new FastOutSlowInInterpolator()).alpha(0f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } /*////////////////////////////////////////////////////////////////////////// // Internals //////////////////////////////////////////////////////////////////////////*/ private static void animateScaleAndAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setScaleX(.8f); view.setScaleY(.8f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()) .alpha(1f).scaleX(1f).scaleY(1f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.setScaleX(1f); view.setScaleY(1f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()) .alpha(0f).scaleX(.8f).scaleY(.8f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } private static void animateLightScaleAndAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setAlpha(.5f); view.setScaleX(.95f); view.setScaleY(.95f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()) .alpha(1f).scaleX(1f).scaleY(1f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.setAlpha(1f); view.setScaleX(1f); view.setScaleY(1f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()) .alpha(0f).scaleX(.95f).scaleY(.95f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } private static void animateSlideAndAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setTranslationY(-view.getHeight()); view.setAlpha(0f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()).alpha(1f).translationY(0) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.animate() .setInterpolator(new FastOutSlowInInterpolator()) .alpha(0f).translationY(-view.getHeight()) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } private static void animateLightSlideAndAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setTranslationY(-view.getHeight() / 2.0f); view.setAlpha(0f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()).alpha(1f).translationY(0) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.animate().setInterpolator(new FastOutSlowInInterpolator()) .alpha(0f).translationY(-view.getHeight() / 2.0f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } public static void slideUp(final View view, final long duration, final long delay, @FloatRange(from = 0.0f, to = 1.0f) final float translationPercent) { final int translationY = (int) (view.getResources().getDisplayMetrics().heightPixels * (translationPercent)); view.animate().setListener(null).cancel(); view.setAlpha(0f); view.setTranslationY(translationY); view.setVisibility(View.VISIBLE); view.animate() .alpha(1f) .translationY(0) .setStartDelay(delay) .setDuration(duration) .setInterpolator(new FastOutSlowInInterpolator()) .start(); } public enum Type { ALPHA, SCALE_AND_ALPHA, LIGHT_SCALE_AND_ALPHA, SLIDE_AND_ALPHA, LIGHT_SLIDE_AND_ALPHA } }
Java
My Dotfiles - Lasciate ogne speranza, voi ch'intrate ======== ## TODO - [ ] Improve `setup.sh` for easy installation.
Java
import {Component, OnInit} from '@angular/core'; import {EvaluationService} from '../service/evaluation.service'; @Component({ selector: 'app-evaluation', templateUrl: './evaluation.component.html', styleUrls: ['./evaluation.component.css'] }) export class EvaluationComponent implements OnInit { public result: number[]; private quadrantWith = 200; constructor(public evaluationService: EvaluationService) { } ngOnInit() { this.result = this.evaluationService.evaluate(); } calc(points: number): number { const value = 1 / 30 * (points - 10) * this.quadrantWith return (value < 0) ? 0 : value; } }
Java
#control-menu { position: fixed; background-color: #E9F2F5; border: solid 1px #d3d3d3; display: flex; justify-content: space-between; align-items: center; z-index: 100000 } #control-menu * { font-size: 13px; font-weight: bold; } #control-menu .user { display: block; margin: 0 8px 0 0; padding: 8px; background-color: #235c96; color: #fff; } #control-menu .right { display: flex; justify-content: flex-end; } #control-menu .right a { width: 20px; height: 18px; display: block; padding: 8px; } #control-menu .right a:hover { background-color: #D5E7ED; } #control-menu .about { background: transparent url(about.png) no-repeat center center; } #control-menu .help { background: transparent url(help.png) no-repeat center center; } #control-menu .logout { background: transparent url(logout.png) no-repeat center center; } #control-menu ul { display: flex; justify-content: flex-start; flex-grow: 1; margin: 0; padding: 0; } #control-menu ul li { display: block; list-style: none; margin: 0; position: relative; } #control-menu ul li a { display: block; padding: 8px; cursor: pointer; color: #00576d; text-decoration: none; } #control-menu ul li a:hover { background-color: #D5E7ED; } #control-menu ul li ul { position: absolute; left: 0; bottom: 32px; display: none; background-color: #E9F2F5; padding: 5px; width: 200px; border-top: solid 1px #d3d3d3; border-left: solid 1px #d3d3d3; border-right: solid 1px #d3d3d3; -moz-border-radius-topleft: 5px; -moz-border-radius-topright: 5px; -webkit-border-top-left-radius: 5px; -webkit-border-top-right-radius: 5px; border-top-left-radius: 5px; border-top-right-radius: 5px; } #control-menu ul li ul li { display: block; margin: 0; padding: 0; } #control-menu ul li ul li a { display: block; border-bottom: dotted 1px #d3d3d3; color: #00576d; text-decoration: none; } #control-menu ul li ul li a:hover { background-color: #df7500; color: #fff; } #control-menu .view { display: none; } #control-menu .view a { display: inline-block; cursor: pointer; width: 20px; height: 20px; padding: 5px 8px 5px 8px; background: transparent url(options.png) no-repeat center center; } #control-menu-mobile { display: none; position: fixed; background-color: #E9F2F5; z-index: 100000; overflow: scroll; padding: 10px; box-sizing: border-box; opacity: 0.9; } #control-menu-mobile a { color: #00576d; } #control-menu-mobile .close { text-align: right; } #control-menu-mobile .close a { font-weight: bold; display: inline-block; padding: 10px 10px 0 10px; font-size: 24px; cursor: pointer; } #control-menu-mobile ul { margin: 0; padding: 0; } #control-menu-mobile ul li { list-style: none; } #control-menu-mobile > ul > li { margin-bottom: 15px; } #control-menu-mobile > ul > li > a { font-size: 24px; margin-bottom: 10px; } #control-menu-mobile ul li a { display: block; } #control-menu-mobile ul ul li a { padding-left: 20px; display: block; padding: 7px; border-bottom: dotted 1px #d3d3d3; } #control-menu-mobile ul ul li a:hover { background-color: #df7500; color: #fff; } @media all and (max-width: 800px) { #control-menu ul { display: none; } #control-menu .view { display: block; flex-grow: 1; text-align: left; } }
Java
/* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: FillGeneratorTool.java * * Copyright (c) 2006 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.generator.layout.fill; import com.sun.electric.database.geometry.EPoint; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.hierarchy.Library; import com.sun.electric.database.prototype.PortProto; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.topology.PortInst; import com.sun.electric.technology.ArcProto; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.tool.Job; import com.sun.electric.tool.JobException; import com.sun.electric.tool.Tool; import com.sun.electric.tool.generator.layout.Gallery; import com.sun.electric.tool.generator.layout.LayoutLib; import com.sun.electric.tool.generator.layout.TechType; import java.lang.reflect.Constructor; import java.util.*; abstract class MetalFloorplanBase extends Floorplan { /** width Vdd wires */ public double vddWidth; /** width Gnd wires */ public double gndWidth; MetalFloorplanBase(double cellWidth, double cellHeight, boolean horiz) { super(cellWidth, cellHeight, horiz); vddWidth = gndWidth = 0; } } // ------------------------------ MetalFloorplanFlex ------------------------------ // Similar to Metalfloor but number of power/gnd lines is determined by cell size class MetalFloorplanFlex extends MetalFloorplanBase { public final double minWidth, space, vddReserve, gndReserve; MetalFloorplanFlex(double cellWidth, double cellHeight, double vddReserve, double gndReserve, double space, double vddW, double gndW, boolean horiz) { super(cellWidth, cellHeight, horiz); this.vddWidth = vddW; //27; this.gndWidth = gndW; //20; this.space = space; this.vddReserve = vddReserve; this.gndReserve = gndReserve; minWidth = vddReserve + gndReserve + 2*space + 2*gndWidth + 2*vddWidth; } } // ------------------------------ MetalFloorplan ------------------------------ // Floor plan: // // half of Gnd reserved // gggggggggggggggggggg // wide space // vvvvvvvvvvvvvvvvvvvv // Vdd reserved // vvvvvvvvvvvvvvvvvvvv // wide space // gggggggggggggggggggg // half of Gnd reserved class MetalFloorplan extends MetalFloorplanBase { /** no gap between Vdd wires */ public final boolean mergedVdd; /** if horizontal then y coordinate of top Vdd wire * if vertical then x coordinate of right Vdd wire */ public final double vddCenter; /** if horizontal then y coordinate of top Gnd wire * if vertical then x coordinate of right Gnd wire */ public final double gndCenter; public final double coverage; private double roundDownOneLambda(double x) { return Math.floor(x); } // Round metal widths down to multiples of 1 lambda resolution. // Then metal center can be on 1/2 lambda grid without problems. MetalFloorplan(double cellWidth, double cellHeight, double vddReserve, double gndReserve, double space, boolean horiz) { super(cellWidth, cellHeight, horiz); mergedVdd = vddReserve==0; double cellSpace = horiz ? cellHeight : cellWidth; double metalSpace = cellSpace - 2*space - vddReserve - gndReserve; // gnd is always in two pieces gndWidth = roundDownOneLambda(metalSpace / 4); gndCenter = cellSpace/2 - gndReserve/2 - gndWidth/2; // vdd may be one or two pieces if (mergedVdd) { vddWidth = gndWidth*2; vddCenter = 0; } else { vddWidth = gndWidth; vddCenter = vddReserve/2 + vddWidth/2; } // compute coverage statistics double cellArea = cellWidth * cellHeight; double strapLength = horiz ? cellWidth : cellHeight; double vddArea = (mergedVdd ? 1 : 2) * vddWidth * strapLength; double gndArea = 2 * gndWidth * strapLength; coverage = (vddArea + gndArea)/cellArea; } // Save this code in case I need to replicate LoCo FillCell exactly // MetalFloorplan(double cellWidth, double cellHeight, // double vddReserve, double gndReserve, // double space, boolean horiz) { // super(cellWidth, cellHeight, horiz); // mergedVdd = vddReserve==0; // double cellSpace = horiz ? cellHeight : cellWidth; // if (mergedVdd) { // double w = cellSpace/2 - space - vddReserve; // vddWidth = roundDownOneLambda(w); // vddCenter = 0; // } else { // double w = (cellSpace/2 - space - vddReserve) / 2; // vddWidth = roundDownOneLambda(w); // vddCenter = vddReserve/2 + vddWidth/2; // } // double vddEdge = vddCenter + vddWidth/2; // double w = cellSpace/2 - vddEdge - space - gndReserve/2; // gndWidth = roundDownOneLambda(w); // gndCenter = vddEdge + space + gndWidth/2; // // // compute coverage statistics // double cellArea = cellWidth * cellHeight; // double strapLength = horiz ? cellWidth : cellHeight; // double vddArea = (mergedVdd ? 1 : 2) * vddWidth * strapLength; // double gndArea = 2 * gndWidth * strapLength; // coverage = (vddArea + gndArea)/cellArea; // } } // ------------------------------- ExportBars --------------------------------- class ExportBar { PortInst[] ports = null; Double center = null; ExportBar(PortInst p1, PortInst p2, double c) { ports = new PortInst[2]; ports[0] = p1; ports[1] = p2; center = (c); // autoboxing } } class MetalLayer extends VddGndStraps { protected MetalFloorplanBase plan; protected int layerNum; protected PrimitiveNode pin; protected ArcProto metal; protected ArrayList<ExportBar> vddBars = new ArrayList<ExportBar>(); protected ArrayList<ExportBar> gndBars = new ArrayList<ExportBar>(); public boolean addExtraArc() { return true; } private void buildGnd(Cell cell) { double pinX, pinY; MetalFloorplan plan = (MetalFloorplan)this.plan; if (plan.horizontal) { pinX = plan.cellWidth/2; // - plan.gndWidth/2; pinY = plan.gndCenter; } else { pinX = plan.gndCenter; pinY = plan.cellHeight/2; // - plan.gndWidth/2; } PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); if (plan.horizontal) { G.noExtendArc(metal, plan.gndWidth, tl, tr); G.noExtendArc(metal, plan.gndWidth, bl, br); gndBars.add(new ExportBar(bl, br, -plan.gndCenter)); gndBars.add(new ExportBar(tl, tr, plan.gndCenter)); } else { G.noExtendArc(metal, plan.gndWidth, bl, tl); G.noExtendArc(metal, plan.gndWidth, br, tr); gndBars.add(new ExportBar(bl, tl, -plan.gndCenter)); gndBars.add(new ExportBar(br, tr, plan.gndCenter)); } } private void buildVdd(Cell cell) { double pinX, pinY; MetalFloorplan plan = (MetalFloorplan)this.plan; if (plan.horizontal) { pinX = plan.cellWidth/2; // - plan.vddWidth/2; pinY = plan.vddCenter; } else { pinX = plan.vddCenter; pinY = plan.cellHeight/2; // - plan.vddWidth/2; } if (plan.mergedVdd) { PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); G.noExtendArc(metal, plan.vddWidth, bl, tr); vddBars.add(new ExportBar(bl, tr, plan.vddCenter)); } else { PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); if (plan.horizontal) { G.noExtendArc(metal, plan.vddWidth, tl, tr); G.noExtendArc(metal, plan.vddWidth, bl, br); vddBars.add(new ExportBar(bl, br, -plan.vddCenter)); vddBars.add(new ExportBar(tl, tr, plan.vddCenter)); } else { G.noExtendArc(metal, plan.vddWidth, bl, tl); G.noExtendArc(metal, plan.vddWidth, br, tr); vddBars.add(new ExportBar(bl, tl, -plan.vddCenter)); vddBars.add(new ExportBar(br, tr, plan.vddCenter)); } } } /** It has to be protected to be overwritten by sub classes */ protected void buildGndAndVdd(Cell cell) { buildGnd(cell); buildVdd(cell); } public MetalLayer(TechType t, int layerNum, Floorplan plan, Cell cell) { super(t); this.plan = (MetalFloorplanBase)plan; this.layerNum = layerNum; metal = METALS[layerNum]; pin = PINS[layerNum]; buildGndAndVdd(cell); } public boolean isHorizontal() {return plan.horizontal;} public int numVdd() {return vddBars.size();} public double getVddCenter(int n) { return (vddBars.get(n).center); // autoboxing } public PortInst getVdd(int n, int pos) {return vddBars.get(n).ports[pos];} public double getVddWidth(int n) {return plan.vddWidth;} public int numGnd() {return gndBars.size();} public double getGndCenter(int n) { return (gndBars.get(n).center); // autoboxing } public PortInst getGnd(int n, int pos) {return gndBars.get(n).ports[pos];} public double getGndWidth(int n) {return (plan).gndWidth;} public PrimitiveNode getPinType() {return pin;} public ArcProto getMetalType() {return metal;} public double getCellWidth() {return plan.cellWidth;} public double getCellHeight() {return plan.cellHeight;} public int getLayerNumber() {return layerNum;} } // ------------------------------- MetalLayerFlex ----------------------------- class MetalLayerFlex extends MetalLayer { public MetalLayerFlex(TechType t, int layerNum, Floorplan plan, Cell cell) { super(t, layerNum, plan, cell); } public boolean addExtraArc() { return false; } // For automatic fill generator no extra arcs are wanted. protected void buildGndAndVdd(Cell cell) { double pinX, pinY; double limit = 0; MetalFloorplanFlex plan = (MetalFloorplanFlex)this.plan; if (plan.horizontal) { limit = plan.cellHeight/2; } else { limit = plan.cellWidth/2; } double position = 0; int i = 0; while (position < limit) { boolean even = (i%2==0); double maxDelta = 0, pos = 0; if (even) { maxDelta = plan.vddReserve/2 + plan.vddWidth; pos = plan.vddReserve/2 + plan.vddWidth/2 + position; } else { maxDelta = plan.gndReserve/2 + plan.gndWidth; pos = plan.gndReserve/2 + plan.gndWidth/2 + position; } if (position + maxDelta > limit) return; // border was reached if (plan.horizontal) { pinY = pos; pinX = plan.cellWidth/2; } else { pinX = pos; pinY = plan.cellHeight/2; } // Vdd if even, gnd if odd if (!even) addBars(cell, pinX, pinY, plan.gndWidth, gndBars); else addBars(cell, pinX, pinY, plan.vddWidth, vddBars); if (even) { maxDelta = plan.vddReserve/2 + plan.vddWidth + plan.space + plan.gndWidth; pos = plan.vddReserve/2 + plan.vddWidth + plan.space + plan.gndWidth/2 + position; } else { maxDelta = plan.gndReserve/2 + plan.gndWidth + plan.space + plan.vddWidth; pos = plan.gndReserve/2 + plan.gndWidth + plan.space + plan.vddWidth/2 + position; } if (position + maxDelta > limit) return; // border was reached if (plan.horizontal) pinY = pos; else pinX = pos; // Gnd if even, vdd if odd if (!even) { addBars(cell, pinX, pinY, plan.vddWidth, vddBars); position = ((plan.horizontal)?pinY:pinX) + plan.vddWidth/2 + plan.vddReserve/2; } else { addBars(cell, pinX, pinY, plan.gndWidth, gndBars); position = ((plan.horizontal)?pinY:pinX) + plan.gndWidth/2 + plan.gndReserve/2; } i++; } } private void addBars(Cell cell, double pinX, double pinY, double width, ArrayList<ExportBar> bars) { PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); double center = 0; if (plan.horizontal) { G.noExtendArc(metal, width, tl, tr); G.noExtendArc(metal, width, bl, br); center = pinY; bars.add(new ExportBar(bl, br, -center)); bars.add(new ExportBar(tl, tr, center)); } else { G.noExtendArc(metal, width, bl, tl); G.noExtendArc(metal, width, br, tr); center = pinX; bars.add(new ExportBar(bl, tl, -center)); bars.add(new ExportBar(br, tr, center)); } } } //---------------------------------- CapLayer --------------------------------- class CapLayer extends VddGndStraps { private CapCell capCell; private NodeInst capCellInst; private CapFloorplan plan; public boolean addExtraArc() { return true; } public CapLayer(TechType t, CapFloorplan plan, CapCell capCell, Cell cell) { super(t); this.plan = plan; this.capCell = capCell; double angle = plan.horizontal ? 0 : 90; if (capCell != null) capCellInst = LayoutLib.newNodeInst(capCell.getCell(), 0, 0, G.DEF_SIZE, G.DEF_SIZE, angle, cell); } public boolean isHorizontal() {return plan.horizontal;} public int numVdd() {return (capCell != null) ? capCell.numVdd() : 0;} public PortInst getVdd(int n, int pos) { return capCellInst.findPortInst(FillCell.VDD_NAME+"_"+n); } public double getVddCenter(int n) { EPoint center = getVdd(n, 0).getCenter(); return plan.horizontal ? center.getY() : center.getX(); } public double getVddWidth(int n) {return capCell.getVddWidth();} public int numGnd() {return (capCell != null) ? capCell.numGnd() : 0;} public PortInst getGnd(int n, int pos) { return capCellInst.findPortInst(FillCell.GND_NAME+"_"+n); } public double getGndCenter(int n) { EPoint center = getGnd(n, 0).getCenter(); return plan.horizontal ? center.getY() : center.getX(); } public double getGndWidth(int n) {return capCell.getGndWidth();} public PrimitiveNode getPinType() {return tech.m1pin();} public ArcProto getMetalType() {return tech.m1();} public double getCellWidth() {return plan.cellWidth;} public double getCellHeight() {return plan.cellHeight;} public int getLayerNumber() {return 1;} } class FillRouter { private HashMap<String,List<PortInst>> portMap = new HashMap<String,List<PortInst>>(); private TechType tech; private String makeKey(PortInst pi) { EPoint center = pi.getCenter(); String x = ""+center.getX(); // LayoutLib.roundCenterX(pi); String y = ""+center.getY(); // LayoutLib.roundCenterY(pi); return x+"x"+y; } // private boolean bothConnect(ArcProto a, PortProto pp1, PortProto pp2) { // return pp1.connectsTo(a) && pp2.connectsTo(a); // } private ArcProto findCommonArc(PortInst p1, PortInst p2) { ArcProto[] metals = {tech.m6(), tech.m5(), tech.m4(), tech.m3(), tech.m2(), tech.m1()}; PortProto pp1 = p1.getPortProto(); PortProto pp2 = p2.getPortProto(); for (int i=0; i<metals.length; i++) { if (pp1.connectsTo(metals[i]) && pp2.connectsTo(metals[i])) { return metals[i]; } } return null; } private void connectPorts(List<PortInst> ports) { for (Iterator<PortInst> it=ports.iterator(); it.hasNext(); ) { PortInst first = it.next(); double width = LayoutLib.widestWireWidth(first); it.remove(); for (PortInst pi : ports) { ArcProto a = findCommonArc(first, pi); if (a!=null) LayoutLib.newArcInst(a, width, first, pi); } } } private FillRouter(TechType t, ArrayList<PortInst> ports) { tech = t; for (PortInst pi : ports) { String key = makeKey(pi); List<PortInst> l = portMap.get(key); if (l==null) { l = new LinkedList<PortInst>(); portMap.put(key, l); } l.add(pi); } // to guarantee deterministic results List<String> keys = new ArrayList<String>(); keys.addAll(portMap.keySet()); Collections.sort(keys); for (String str : keys) { connectPorts(portMap.get(str)); } } public static void connectCoincident(TechType t, ArrayList<PortInst> ports) { new FillRouter(t, ports); } } /** * Object for building fill libraries */ public class FillGeneratorTool extends Tool { public FillGenConfig config; protected Library lib; private boolean libInitialized; public List<Cell> masters; protected CapCell capCell; protected Floorplan[] plans; /** the fill generator tool. */ private static FillGeneratorTool tool = getTool(); // Depending on generator plugin available public static FillGeneratorTool getTool() { if (tool != null) return tool; FillGeneratorTool tool; try { Class<?> extraClass = Class.forName("com.sun.electric.plugins.generator.FillCellTool"); Constructor instance = extraClass.getDeclaredConstructor(); // varags Object obj = instance.newInstance(); // varargs; tool = (FillGeneratorTool)obj; } catch (Exception e) { if (Job.getDebug()) System.out.println("GNU Release can't find Fill Cell Generator plugin"); tool = new FillGeneratorTool(); } return tool; } public FillGeneratorTool() { super("Fill Generator"); } public void setConfig(FillGenConfig config) { this.config = config; this.libInitialized = false; } public enum Units {NONE, LAMBDA, TRACKS} protected boolean getOrientation() {return plans[plans.length-1].horizontal;} /** Reserve space in the middle of the Vdd and ground straps for signals. * @param layer the layer number. This may be 2, 3, 4, 5, or 6. The layer * number 1 is reserved to mean "capacitor between Vdd and ground". * @param reserved space to reserve in the middle of the central * strap in case of Vdd. The value 0 makes the Vdd strap one large strap instead of two smaller * adjacent straps. * Space to reserve between the ground strap of this * cell and the ground strap of the adjacent fill cell. The value 0 means * that these two ground straps should abut to form a single large strap * instead of two smaller adjacent straps. * */ private double reservedToLambda(int layer, double reserved, Units units) { if (units==LAMBDA) return reserved; double nbTracks = reserved; if (nbTracks==0) return 0; return config.getTechType().reservedToLambda(layer, nbTracks); } private Floorplan[] makeFloorplans(boolean metalFlex, boolean hierFlex) { Job.error(config.width==Double.NaN, "width hasn't been specified. use setWidth()"); Job.error(config.height==Double.NaN, "height hasn't been specified. use setHeight()"); double w = config.width; double h = config.height; int numLayers = config.getTechType().getNumMetals() + 1; // one extra for the cap double[] vddRes = new double[numLayers]; //{0,0,0,0,0,0,0}; double[] gndRes = new double[numLayers]; //{0,0,0,0,0,0,0}; double[] vddW = new double[numLayers]; //{0,0,0,0,0,0,0}; double[] gndW = new double[numLayers]; //{0,0,0,0,0,0,0}; // set given values for (FillGenConfig.ReserveConfig c : config.reserves) { vddRes[c.layer] = reservedToLambda(c.layer, c.vddReserved, c.vddUnits); gndRes[c.layer] = reservedToLambda(c.layer, c.gndReserved, c.gndUnits); if (c.vddWUnits != Units.NONE) vddW[c.layer] = reservedToLambda(c.layer, c.vddWidth, c.vddWUnits); if (c.gndWUnits != Units.NONE) gndW[c.layer] = reservedToLambda(c.layer, c.gndWidth, c.gndWUnits); } boolean evenHor = config.evenLayersHorizontal; boolean alignedMetals = true; double[] spacing = new double[numLayers]; for (int i = 0; i < numLayers; i++) spacing[i] = config.drcSpacingRule; // {config.drcSpacingRule,config.drcSpacingRule, // config.drcSpacingRule,config.drcSpacingRule, // config.drcSpacingRule,config.drcSpacingRule,config.drcSpacingRule}; if (alignedMetals) { double maxVddRes = 0, maxGndRes = 0, maxSpacing = 0, maxVddW = 0, maxGndW = 0; for (int i = 0; i < vddRes.length; i++) { boolean vddOK = false, gndOK = false; if (vddRes[i] > 0) { vddOK = true; if (maxVddRes < vddRes[i]) maxVddRes = vddRes[i]; } if (gndRes[i] > 0) { gndOK = true; if (maxGndRes < gndRes[i]) maxGndRes = gndRes[i]; } if (gndOK || vddOK) // checking max spacing rule { if (maxSpacing < config.drcSpacingRule) maxSpacing = config.drcSpacingRule; //drcRules[i]; } if (maxVddW < vddW[i]) maxVddW = vddW[i]; if (maxGndW < gndW[i]) maxGndW = gndW[i]; } // correct the values for (int i = 0; i < vddRes.length; i++) { vddRes[i] = maxVddRes; gndRes[i] = maxGndRes; spacing[i] = maxSpacing; vddW[i] = maxVddW; gndW[i] = maxGndW; } } Floorplan[] thePlans = new Floorplan[numLayers]; // 0 is always null thePlans[1] = new CapFloorplan(w, h, !evenHor); if (metalFlex) { if (!hierFlex) { for (int i = 2; i < numLayers; i++) { boolean horiz = (i%2==0); thePlans[i] = new MetalFloorplanFlex(w, h, vddRes[i], gndRes[i], spacing[i], vddW[i], gndW[i], horiz); } return thePlans; } w = config.width = config.minTileSizeX; h = config.height = config.minTileSizeY; } for (int i = 2; i < numLayers; i++) { boolean horiz = (i%2==0); thePlans[i] = new MetalFloorplan(w, h, vddRes[i], gndRes[i], spacing[i], horiz); } return thePlans; } private void printCoverage(Floorplan[] plans) { for (int i=2; i<plans.length; i++) { System.out.println("metal-"+i+" coverage: "+ ((MetalFloorplan)plans[i]).coverage); } } private static CapCell getCMOS90CapCell(Library lib, CapFloorplan plan) { CapCell c = null; try { Class<?> cmos90Class = Class.forName("com.sun.electric.plugins.tsmc.fill90nm.CapCellCMOS90"); Constructor capCellC = cmos90Class.getDeclaredConstructor(Library.class, CapFloorplan.class); // varargs Object cell = capCellC.newInstance(lib, plan); c = (CapCell)cell; } catch (Exception e) { assert(false); // runtime error } return c; } protected void initFillParameters(boolean metalFlex, boolean hierFlex) { if (libInitialized) return; Job.error(config.fillLibName==null, "no library specified. Use setFillLibrary()"); Job.error((config.width==Double.NaN || config.width<=0), "no width specified. Use setFillCellWidth()"); Job.error((config.height==Double.NaN || config.height<=0), "no height specified. Use setFillCellHeight()"); plans = makeFloorplans(metalFlex, hierFlex); if (!metalFlex) printCoverage(plans); lib = LayoutLib.openLibForWrite(config.fillLibName); if (!metalFlex) // don't do transistors { if (config.is180Tech()) { capCell = new CapCellMosis(lib, (CapFloorplan) plans[1], config.getTechType()); } else { capCell = getCMOS90CapCell(lib, (CapFloorplan) plans[1]); } } libInitialized = true; } private void makeTiledCells(Cell cell, Floorplan[] plans, Library lib, int[] tiledSizes) { if (tiledSizes==null) return; for (int num : tiledSizes) { TiledCell.makeTiledCell(num, num, cell, plans, lib); } } public static Cell makeFillCell(Library lib, Floorplan[] plans, int botLayer, int topLayer, CapCell capCell, TechType tech, ExportConfig expCfg, boolean metalFlex, boolean hierFlex) { FillCell fc = new FillCell(tech); return fc.makeFillCell1(lib, plans, botLayer, topLayer, capCell, expCfg, metalFlex, hierFlex); } /** * Method to create standard set of tiled cells. */ private Cell standardMakeAndTileCell(Library lib, Floorplan[] plans, int lowLay, int hiLay, CapCell capCell, TechType tech, ExportConfig expCfg, int[] tiledSizes, boolean metalFlex) { Cell master = makeFillCell(lib, plans, lowLay, hiLay, capCell, tech, expCfg, metalFlex, false); masters = new ArrayList<Cell>(); masters.add(master); makeTiledCells(master, plans, lib, tiledSizes); return master; } public static final Units LAMBDA = Units.LAMBDA; public static final Units TRACKS = Units.TRACKS; //public static final PowerType POWER = PowerType.POWER; //public static final PowerType VDD = PowerType.VDD; public static final ExportConfig PERIMETER = ExportConfig.PERIMETER; public static final ExportConfig PERIMETER_AND_INTERNAL = ExportConfig.PERIMETER_AND_INTERNAL; /** Reserve space in the middle of the Vdd and ground straps for signals. * @param layer the layer number. This may be 2, 3, 4, 5, or 6. The layer * number 1 is reserved to mean "capacitor between Vdd and ground". * @param vddReserved space to reserve in the middle of the central Vdd * strap. * The value 0 makes the Vdd strap one large strap instead of two smaller * adjacent straps. * @param vddUnits LAMBDA or TRACKS * @param gndReserved space to reserve between the ground strap of this * cell and the ground strap of the adjacent fill cell. The value 0 means * that these two ground straps should abut to form a single large strap * instead of two smaller adjacent straps. * @param gndUnits LAMBDA or TRACKS * param tiledSizes an array of sizes. The default value is null. The * value null means don't generate anything. */ // public void reserveSpaceOnLayer(int layer, // double vddReserved, Units vddUnits, // double gndReserved, Units gndUnits) { // LayoutLib.error(layer<2 || layer>6, // "Bad layer. Layers must be between 2 and 6 inclusive: "+ // layer); // this.vddReserved[layer] = reservedToLambda(layer, vddReserved, vddUnits); // this.gndReserved[layer] = reservedToLambda(layer, gndReserved, gndUnits); // } /** Create a fill cell using the current library, fill cell width, fill cell * height, layer orientation, and reserved spaces for each layer. Then * generate larger fill cells by tiling that fill cell according to the * current tiled cell sizes. * @param loLayer the lower layer. This may be 1 through 6. Layer 1 means * build a capacitor using MOS transistors between Vdd and ground. * @param hiLayer the upper layer. This may be 2 through 6. Note that hiLayer * must be >= loLayer. * @param exportConfig may be PERIMETER in which case exports are * placed along the perimeter of the cell for the top two layers. Otherwise * exportConfig must be PERIMETER_AND_INTERNAL in which case exports are * placed inside the perimeter of the cell for the bottom layer. * @param tiledSizes Array specifying composite Cells we should build by * concatonating fill cells. For example int[] {2, 4, 7} means we should * */ public Cell standardMakeFillCell(int loLayer, int hiLayer, TechType tech, ExportConfig exportConfig, int[] tiledSizes, boolean metalFlex) { initFillParameters(metalFlex, false); Job.error(loLayer<1, "loLayer must be >=1"); int maxNumMetals = config.getTechType().getNumMetals(); Job.error(hiLayer>maxNumMetals, "hiLayer must be <=" + maxNumMetals); Job.error(loLayer>hiLayer, "loLayer must be <= hiLayer"); Cell cell = null; cell = standardMakeAndTileCell(lib, plans, loLayer, hiLayer, capCell, tech, exportConfig, tiledSizes, metalFlex); return cell; } public void makeGallery() { Gallery.makeGallery(lib); } public void writeLibrary(int backupScheme) throws JobException { LayoutLib.writeLibrary(lib, backupScheme); } public enum FillTypeEnum {INVALID,TEMPLATE,CELL} }
Java
<!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>MetaDataInfo xref</title> <link type="text/css" rel="stylesheet" href="../../../stylesheet.css" /> </head> <body> <div id="overview"><a href="../../../../apidocs/fspotcloud/shared/admin/MetaDataInfo.html">View Javadoc</a></div><pre> <a class="jxr_linenumber" name="1" href="#1">1</a> <strong class="jxr_keyword">package</strong> fspotcloud.shared.admin; <a class="jxr_linenumber" name="2" href="#2">2</a> <a class="jxr_linenumber" name="3" href="#3">3</a> <strong class="jxr_keyword">import</strong> java.util.Date; <a class="jxr_linenumber" name="4" href="#4">4</a> <a class="jxr_linenumber" name="5" href="#5">5</a> <strong class="jxr_keyword">import</strong> com.google.gwt.user.client.rpc.IsSerializable; <a class="jxr_linenumber" name="6" href="#6">6</a> <a class="jxr_linenumber" name="7" href="#7">7</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../fspotcloud/shared/admin/MetaDataInfo.html">MetaDataInfo</a> <strong class="jxr_keyword">implements</strong> IsSerializable { <a class="jxr_linenumber" name="8" href="#8">8</a> <a class="jxr_linenumber" name="9" href="#9">9</a> <strong class="jxr_keyword">private</strong> Date created; <a class="jxr_linenumber" name="10" href="#10">10</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> peerPhotoCount; <a class="jxr_linenumber" name="11" href="#11">11</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> tagCount; <a class="jxr_linenumber" name="12" href="#12">12</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> pendingCommandCount; <a class="jxr_linenumber" name="13" href="#13">13</a> <strong class="jxr_keyword">private</strong> Date peerLastSeen; <a class="jxr_linenumber" name="14" href="#14">14</a> <strong class="jxr_keyword">private</strong> String instanceName; <a class="jxr_linenumber" name="15" href="#15">15</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">long</strong> photoCount; <a class="jxr_linenumber" name="16" href="#16">16</a> <strong class="jxr_keyword">private</strong> Date photosLastCounted; <a class="jxr_linenumber" name="17" href="#17">17</a> <a class="jxr_linenumber" name="18" href="#18">18</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">long</strong> getPhotoCount() { <a class="jxr_linenumber" name="19" href="#19">19</a> <strong class="jxr_keyword">return</strong> photoCount; <a class="jxr_linenumber" name="20" href="#20">20</a> } <a class="jxr_linenumber" name="21" href="#21">21</a> <a class="jxr_linenumber" name="22" href="#22">22</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPhotoCount(<strong class="jxr_keyword">long</strong> photoCount) { <a class="jxr_linenumber" name="23" href="#23">23</a> <strong class="jxr_keyword">this</strong>.photoCount = photoCount; <a class="jxr_linenumber" name="24" href="#24">24</a> } <a class="jxr_linenumber" name="25" href="#25">25</a> <a class="jxr_linenumber" name="26" href="#26">26</a> <strong class="jxr_keyword">public</strong> Date getPhotosLastCounted() { <a class="jxr_linenumber" name="27" href="#27">27</a> <strong class="jxr_keyword">return</strong> photosLastCounted; <a class="jxr_linenumber" name="28" href="#28">28</a> } <a class="jxr_linenumber" name="29" href="#29">29</a> <a class="jxr_linenumber" name="30" href="#30">30</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPhotosLastCounted(Date photosLastCounted) { <a class="jxr_linenumber" name="31" href="#31">31</a> <strong class="jxr_keyword">this</strong>.photosLastCounted = photosLastCounted; <a class="jxr_linenumber" name="32" href="#32">32</a> } <a class="jxr_linenumber" name="33" href="#33">33</a> <a class="jxr_linenumber" name="34" href="#34">34</a> <strong class="jxr_keyword">public</strong> <a href="../../../fspotcloud/shared/admin/MetaDataInfo.html">MetaDataInfo</a>() { <a class="jxr_linenumber" name="35" href="#35">35</a> created = <strong class="jxr_keyword">new</strong> Date(); <a class="jxr_linenumber" name="36" href="#36">36</a> } <a class="jxr_linenumber" name="37" href="#37">37</a> <a class="jxr_linenumber" name="38" href="#38">38</a> <strong class="jxr_keyword">public</strong> Date getCreated() { <a class="jxr_linenumber" name="39" href="#39">39</a> <strong class="jxr_keyword">return</strong> created; <a class="jxr_linenumber" name="40" href="#40">40</a> } <a class="jxr_linenumber" name="41" href="#41">41</a> <a class="jxr_linenumber" name="42" href="#42">42</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> getPeerPhotoCount() { <a class="jxr_linenumber" name="43" href="#43">43</a> <strong class="jxr_keyword">return</strong> peerPhotoCount; <a class="jxr_linenumber" name="44" href="#44">44</a> } <a class="jxr_linenumber" name="45" href="#45">45</a> <a class="jxr_linenumber" name="46" href="#46">46</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPeerPhotoCount(<strong class="jxr_keyword">int</strong> peerPhotoCount) { <a class="jxr_linenumber" name="47" href="#47">47</a> <strong class="jxr_keyword">this</strong>.peerPhotoCount = peerPhotoCount; <a class="jxr_linenumber" name="48" href="#48">48</a> } <a class="jxr_linenumber" name="49" href="#49">49</a> <a class="jxr_linenumber" name="50" href="#50">50</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> getTagCount() { <a class="jxr_linenumber" name="51" href="#51">51</a> <strong class="jxr_keyword">return</strong> tagCount; <a class="jxr_linenumber" name="52" href="#52">52</a> } <a class="jxr_linenumber" name="53" href="#53">53</a> <a class="jxr_linenumber" name="54" href="#54">54</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setTagCount(<strong class="jxr_keyword">int</strong> tagCount) { <a class="jxr_linenumber" name="55" href="#55">55</a> <strong class="jxr_keyword">this</strong>.tagCount = tagCount; <a class="jxr_linenumber" name="56" href="#56">56</a> } <a class="jxr_linenumber" name="57" href="#57">57</a> <a class="jxr_linenumber" name="58" href="#58">58</a> <strong class="jxr_keyword">public</strong> Date getPeerLastSeen() { <a class="jxr_linenumber" name="59" href="#59">59</a> <strong class="jxr_keyword">return</strong> peerLastSeen; <a class="jxr_linenumber" name="60" href="#60">60</a> } <a class="jxr_linenumber" name="61" href="#61">61</a> <a class="jxr_linenumber" name="62" href="#62">62</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPeerLastSeen(Date peerLastSeen) { <a class="jxr_linenumber" name="63" href="#63">63</a> <strong class="jxr_keyword">this</strong>.peerLastSeen = peerLastSeen; <a class="jxr_linenumber" name="64" href="#64">64</a> } <a class="jxr_linenumber" name="65" href="#65">65</a> <a class="jxr_linenumber" name="66" href="#66">66</a> <strong class="jxr_keyword">public</strong> String getInstanceName() { <a class="jxr_linenumber" name="67" href="#67">67</a> <strong class="jxr_keyword">return</strong> instanceName; <a class="jxr_linenumber" name="68" href="#68">68</a> } <a class="jxr_linenumber" name="69" href="#69">69</a> <a class="jxr_linenumber" name="70" href="#70">70</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setInstanceName(String instanceName) { <a class="jxr_linenumber" name="71" href="#71">71</a> <strong class="jxr_keyword">this</strong>.instanceName = instanceName; <a class="jxr_linenumber" name="72" href="#72">72</a> } <a class="jxr_linenumber" name="73" href="#73">73</a> <a class="jxr_linenumber" name="74" href="#74">74</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPendingCommandCount(<strong class="jxr_keyword">int</strong> pendingCommandCount) { <a class="jxr_linenumber" name="75" href="#75">75</a> <strong class="jxr_keyword">this</strong>.pendingCommandCount = pendingCommandCount; <a class="jxr_linenumber" name="76" href="#76">76</a> } <a class="jxr_linenumber" name="77" href="#77">77</a> <a class="jxr_linenumber" name="78" href="#78">78</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> getPendingCommandCount() { <a class="jxr_linenumber" name="79" href="#79">79</a> <strong class="jxr_keyword">return</strong> pendingCommandCount; <a class="jxr_linenumber" name="80" href="#80">80</a> } <a class="jxr_linenumber" name="81" href="#81">81</a> <a class="jxr_linenumber" name="82" href="#82">82</a> } </pre> <hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body> </html>
Java
#include "session.h" // This file is part of MCI_Host. // MCI_Host is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // MCI_Host is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with MCI_Host under the LICENSE.md file. If not, see // <http://www.gnu.org/licenses/>. Session::Session(uint sesId, qintptr newPtr, QObject *parent) : QTcpSocket(0) { timer = new QTimer(); bits = 0; flags = 0; dSize = 0; sessionId = 0; slotId = 0; baseSlot = 0; rdHash = 0; wrHash = 0; cmdListMode = 0; cmdListCaseSensitive = false; cmdListenabled = false; keyOk = false; verOk = false; onBaseSlot = false; timer->setSingleShot(true); timer->setInterval(6000); // the timer object provides a 6sec timeout for the client to send the // header before the session is forced closed. connect(this, SIGNAL(readyRead()), this, SLOT(dataFromClient())); connect(this, SIGNAL(destroyed()), timer, SLOT(deleteLater())); connect(timer, SIGNAL(timeout()), this, SLOT(sessionTimeout())); connect(parent, SIGNAL(destroyed()), this, SLOT(deleteLater())); setSocketDescriptor(newPtr); if (inBanList(peerAddress().toString())) { // any session that still has a session id of zero after running the // contructor is considered a blocked ip so the session will get killed // externally at Server::incomingConnection(). sessionEnding = true; addIpAction(tr("IP address blocked"), peerAddress().toString()); } else { // Session represents the TCP connection with the client. it provides the // xOR encryption, version negotiation and an interface for CmdHub objects. // it starts in it's own thread from within the contructor and kills // itself when the client disconnects but does not kill the CmdHub it's // currently connected to. addIpAction(tr("Connected, assigned session id: ") + QString::number(sesId), peerAddress().toString()); sessionEnding = false; sessionId = sesId; QThread *thr = new QThread(); connect(thr, SIGNAL(finished()), thr, SLOT(deleteLater())); connect(thr, SIGNAL(started()), timer, SLOT(start())); connect(this, SIGNAL(destroyed()), thr, SLOT(quit())); connect(this, SIGNAL(disconnected()), this, SLOT(clientDisconnected())); timer->moveToThread(thr); moveToThread(thr); thr->start(); } } bool Session::loadProfile(const QString &proName, QByteArray &key) { // this function runs 3 database queries to read the following profile // data: // keyHash - this is used in the Hash object to setup encryption. // groupName - this indicates what group the profile belongs to. // the group can contain host privileges that profile // is allowed to do. // cmdListCaseSensitive - indicates if the profileCmdList is casesSensitive. // cmdListenabled - indicates if the profileCmdList is enabled. // cmdListMode - indicates what the profileCmdList does when the // sent in command line is matched. // baseSlot - this indicates the fallback slot in cases when the // the slot the session is currently connected is // killed. // profileCmdList - this is the group command line list that is used // allowed or disallow certain commands depending // on what is loaded into cmdListMode or // cmdListCaseSensitive. bool ret = false; Query db(this); db.setType(Query::PULL, TABLE_PROFILES); db.addColumn(COLUMN_PRONAME); db.addColumn(COLUMN_PROKEY); db.addColumn(COLUMN_GRNAME); db.addCondition(COLUMN_PRONAME, proName); db.exec(); if (db.rows()) { ret = true; profileName = db.getData(COLUMN_PRONAME).toString(); groupName = db.getData(COLUMN_GRNAME).toString(); key = db.getData(COLUMN_PROKEY).toByteArray(); db.setType(Query::PULL, TABLE_GROUPS); db.addColumn(COLUMN_CS); db.addColumn(COLUMN_LS_MODE); db.addColumn(COLUMN_LS_STATE); db.addColumn(COLUMN_BASE_SL); db.addCondition(COLUMN_GRNAME, groupName); db.exec(); cmdListCaseSensitive = db.getData(COLUMN_CS).toBool(); cmdListenabled = db.getData(COLUMN_LS_STATE).toBool(); cmdListMode = db.getData(COLUMN_LS_MODE).toUInt(); baseSlot = db.getData(COLUMN_BASE_SL).toUInt(); profileCmdList.clear(); db.setType(Query::PULL, TABLE_CMD_LIST); db.addColumn(COLUMN_CMD_LINE); db.addCondition(COLUMN_GRNAME, groupName); db.exec(); for (int i = 0; i < db.rows(); ++i) { profileCmdList.append(db.getData(COLUMN_CMD_LINE, i).toString()); } } return ret; } bool Session::inBanList(const QString &ip) { // simple database select query with the provided ip address in the where // clause. if a row is found, that indicates that the ip address is in // the ban list. Query db(this); db.setType(Query::PULL, TABLE_IPBANS); db.addColumn(COLUMN_IPADDR); db.addCondition(COLUMN_IPADDR, ip); db.exec(); return db.rows(); } void Session::addIpAction(const QString &action, const QString &ip) { // insert database query for the ip address action log (ip_hist). Query db(this); db.setType(Query::PUSH, TABLE_IPHIST); db.addColumn(COLUMN_IPADDR, ip); db.addColumn(COLUMN_LOGENTRY, action); db.exec(); } uint Session::id() { return sessionId; } void Session::slotClosed() { // this function is connected to CmdHub::destroyed() as a way to catch if the currently // connected command interperter has been killed. command interperters (CmdHub) running in the // background are considered slots in this application so when a command interperter dies, its // the same as a slot getting closed so the session will attempt to re-create or re-attach to // the base slot defined in the profile when this happens. this behavior should not be allowed // if the session is closing so sessionEnding is checked. if (!sessionEnding) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<300> Slot id: ") + QString::number(slotId) + tr(" was killed. falling back to slot id: ") + QString::number(baseSlot) + tr(".")); emit createSlot(sessionId, 0, baseSlot); } } void Session::groupBaseSlotChanged(const QString &grpName, uint id) { if (grpName.toLower() == groupName.toLower()) { if (onBaseSlot) { // force the session to create or attach to the new base slot if currently connected // to the old base slot. emit createSlot(sessionId, baseSlot, id); } baseSlot = id; } } void Session::groupCmdListChanged(const QString &grpName, const QStringList &ls) { if (grpName.toLower() == groupName.toLower()) { profileCmdList = ls; } } void Session::groupCSListChanged(const QString &grpName, bool cs) { if (grpName.toLower() == groupName.toLower()) { cmdListCaseSensitive = cs; } } void Session::groupEnabledListChanged(const QString &grpName, bool state) { if (grpName.toLower() == groupName.toLower()) { cmdListenabled = state; } } void Session::groupCmdLsModeChanged(const QString &grpName, uint mode) { if (grpName.toLower() == groupName.toLower()) { cmdListMode = mode; } } void Session::profileGroupChanged(const QString &proName) { if (profileName.toLower() == proName.toLower()) { QByteArray unused; loadProfile(profileName, unused); groupBaseSlotChanged(groupName, baseSlot); } } void Session::profileNameChanged(const QString &oldName, const QString &newName) { if (profileName.toLower() == oldName.toLower()) { profileName = newName; textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<301> Your current profile name was changed to: ") + newName); } } void Session::groupRenamed(const QString &oldName, const QString &newName) { if (groupName.toLower() == oldName.toLower()) { groupName = newName; } } void Session::profileDeleted(const QString &proName) { if (profileName.toLower() == proName.toLower()) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<302> Your current profile got deleted, ending this session.")); sessionEnding = true; emit deleteSession(sessionId); } } void Session::sessionSlotChanged(uint sesId, uint slId) { // this should be connected to the Server object's sessionSlotChanged() signal to help this // object keep track of the slotId it is currently connected to. if (sesId == sessionId) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<201> Connected to slot id: ") + QString::number(slId) + tr(".")); slotId = slId; onBaseSlot = (slotId == baseSlot); } } void Session::clientDisconnected() { addIpAction(tr("Disconnected"), peerAddress().toString()); if (!sessionEnding) { sessionEnding = true; emit deleteSession(sessionId); } } void Session::sessionTimeout() { sessionEnding = true; emit deleteSession(sessionId); } void Session::requestedToClose(uint sesId) { if (sesId == 0) { sessionEnding = true; emit deleteSession(sessionId); } else if (sesId == sessionId) { emit okToDelete(sesId); close(); } } void Session::dataToClient(const QByteArray &data, uint exclude, uchar flgs) { if (keyOk && (exclude != sessionId)) { // data format: [num_of_bits][flags][data_size][data] // it's very important that the data is sent in this format and encrypted to avoid // undefined behavior. QByteArray lenBa = wrInt(data.size()); QByteArray flagsBa = QByteArray(1, flgs); QByteArray bitsBa = QByteArray(1, (uchar) lenBa.size() * 8); write(wrHash->xOR(Hash::ENCODE, bitsBa + flagsBa + lenBa + data)); } } void Session::textFromCmd(uint sesId, bool cr, const QString &line) { QTextCodec *codec = QTextCodec::codecForName("UTF-16LE"); if (cr) dataToClient(codec->fromUnicode(line), 0, TEXT_CH); else dataToClient(codec->fromUnicode(line), sesId, TEXT_CH); } void Session::textFromServer(uint sesId, const QString &line) { if ((sesId == sessionId) || (sesId == 0)) { textFromCmd(sessionId, true, line); } } void Session::binFromCmd(uint sesId, bool cr, bool priv, const QByteArray &bin) { if (priv) { if (sesId == sessionId) { dataToClient(bin, 0, BIN_CH); } } else { if (cr) dataToClient(bin, 0, BIN_CH); else dataToClient(bin, sesId, BIN_CH); } } void Session::dataFilter(const QByteArray &data, uchar flgs) { // this take the decrypted data from dataFromClient() and converts it to a // QString if the flgs TEXT_CH is present or reads the command name from // the raw data if BIN_CH is present. the the command name or full command // line is then checked with profileAllowedCmd() at this point. QString line; if (flgs & TEXT_CH) { line = QTextCodec::codecForName("UTF-16LE")->toUnicode(data); if (profileAllowedCmd(line)) { emit textToCmd(sessionId, &profileName, line); } } else if (flgs & BIN_CH) { if (activeHook) { emit binToCmd(sessionId, &profileName, data); } else { bool found = false; for (int i = 0; i < data.size(); i += 2) { QByteArray chrPair(data.mid(i, 2)); if (chrPair.size() == 2) { if ((chrPair[0] == (char) 0) && (chrPair[1] == (char) 0)) { line = QTextCodec::codecForName("UTF-16LE")->toUnicode(data.left(i)); if (profileAllowedCmd(line)) { emit binToCmd(sessionId, &profileName, data); } found = true; break; } } } if (!found) { textFromCmd(sessionId, true, tr("<105> Call to binary command has no terminator.")); } } } } void Session::setHookState(bool state) { // this is used in Server::attach() to make this class aware of the // hook state of the currently connected CmdHub. activeHook = state; } bool Session::profileAllowedCmd(const QString &line) { // this take in the sent in command line from the client and attempts // the match it with the patterns defined in the profileCmdList if the // list is enabled. empty lines are allowed no matter what. bool ret = true; // command filtering need to be completely bypassed if there is an // active hook on the currently attached CmdHub. if (!activeHook) { if (cmdListenabled && !line.isEmpty()) { bool matched = false; for (int i = 0; (i < profileCmdList.size()) && !matched; ++i) { QRegExp regEx(profileCmdList[i]); regEx.setPatternSyntax(QRegExp::Wildcard); if (cmdListCaseSensitive) regEx.setCaseSensitivity(Qt::CaseSensitive); else regEx.setCaseSensitivity(Qt::CaseInsensitive); matched = regEx.exactMatch(line); } // matched == true at this point indicate that a pattern was found // of cmdListMode is checked to determine if the command should be // allowed to run or not. if (matched && (cmdListMode == CMD_LINES_DISALLOWED_TO_RUN)) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<108> Command rejected by the host.")); ret = false; } else if (!matched && (cmdListMode == CMD_LINES_ALLOWED_TO_RUN)) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<108> Command rejected by the host.")); ret = false; } else if (matched && (cmdListMode != CMD_LINES_ALLOWED_TO_RUN)) { textFromCmd(sessionId, true, tr(" ")); textFromCmd(sessionId, true, tr("<108> host bug! - command list mode not recognized. mode: ") + QString::number(cmdListMode)); ret = false; } } } return ret; } void Session::dataFromClient() { if (keyOk && !sessionEnding) { if (dSize) //stage 5 { if (bytesAvailable() >= dSize) { dataFilter(rdHash->xOR(Hash::DECODE, read(dSize)), flags); dSize = 0; bits = 0; flags = 0; dataFromClient(); } } else if (bits) //stage 4 { if (bytesAvailable() >= bits / 8) { dSize = rdInt(rdHash->xOR(Hash::DECODE, read(bits / 8))); if (dSize) { dataFromClient(); } else if (flags & TEXT_CH) { // 0 on dSize at this point assumes empty text was sent to the // host so this code will actually locally create empty text // and send it through dataFilter(). dataFilter(QTextCodec::codecForName("UTF-16LE")->fromUnicode(tr("")), flags); flags = 0; bits = 0; } else { // just like above, this will locally create an empty QByteArray() // to send through dataFilter(). dataFilter(QByteArray(), flags); flags = 0; bits = 0; } } } else if (bytesAvailable() >= 2) //stage 3 { QByteArray data = rdHash->xOR(Hash::DECODE, read(2)); bits = (uchar) data[0]; flags = (uchar) data[1]; if ((bits > MAX_BITS) || (bits < 8)) { bits = 0; flags = 0; addIpAction(tr("Out-of-sync event (int bits over maximum or < 8)"), peerAddress().toString()); // the client will must likely end up de-synced with the server // at this point. the best way to recover will be to re-start // a new session. (disconnect-reconnect) } else { dataFromClient(); } } } else if (verOk) //stage 2 { // SHA3-512 == 64 bytes. if (bytesAvailable() >= 64) { if (rdHash->passHash() == rdHash->xOR(Hash::DECODE, read(64))) { // numeric value 1 indicates that the passHash matches with // the host and will unlock stage 3-5 until the session closes. // a successful match also resets the ban increment. keyOk = true; write(wrInt(1, 8)); waitForBytesWritten(); emit createSlot(sessionId, 0, baseSlot); emit clearIPBanCount(peerAddress().toString()); } else { // numeric value 2 indicates that the passHash sent in from the // client is invalid. clients are free to make more attempts at this // stage but keep in mind that the ban increment will only grow with // each failed attempt. addIpAction(tr("Client passHash missmatch"), peerAddress().toString()); write(wrInt(2, 8)); emit incrementIPBan(sessionId, peerAddress().toString()); } } } else { if ((bytesAvailable() >= CLIENT_HEADER_LEN) && !sessionEnding) //stage 1 { // client header format: [3bytes(tag)][2bytes(major)][2bytes(minor)][2bytes(patch)][58bytes(profile)] // tag = 0x4D, 0x43, 0x49 (MCI) // major = 16bit little endian int // minor = 16bit little endian int // patch = 16bit little endian int // profile = UTF-16LE string (padded with white spaces to fill 29 max chars) // note: profile names in this app are case insensitive. timer->stop(); if (read(3) == QByteArray(SERVER_HEADER_TAG)) { clientMajor = rdInt(read(2)); clientMinor = rdInt(read(2)); clientPatch = rdInt(read(2)); QByteArray servHeader; QByteArray reply; QByteArray key; QByteArray proName = read(60); addIpAction(tr("Client version: ") + QString::number(clientMajor) + "." + QString::number(clientMinor) + "." + QString::number(clientPatch), peerAddress().toString()); if ((clientMajor >= 1) && (clientMinor > 0)) { QString proStr = QTextCodec::codecForName("UTF-16LE")->toUnicode(proName).trimmed(); addIpAction(tr("Profile name: ") + proStr, peerAddress().toString()); if (loadProfile(proStr, key)) { reply = wrInt(1, 8); verOk = true; addIpAction(tr("Client version and profile ok"), peerAddress().toString()); } else { reply = wrInt(2, 8); addIpAction(tr("Profile not found"), peerAddress().toString()); } } else { reply = wrInt(3, 8); addIpAction(tr("Client version rejected"), peerAddress().toString()); } QStringList ver = QApplication::applicationVersion().split('.'); servHeader.append(reply); servHeader.append(wrInt(ver[0].toShort(), 16)); servHeader.append(wrInt(ver[1].toShort(), 16)); servHeader.append(wrInt(ver[2].toShort(), 16)); if (verOk) { rdHash = new Hash(key + TO_SERV_SALT, sessionId, this); wrHash = new Hash(key + FROM_SERV_SALT, sessionId, this); servHeader.append(rdHash->seqBytes()); servHeader.append(wrHash->seqBytes()); servHeader.append(rdHash->sessionIdBytes()); if (servHeader.size() != SERVER_HEADER_LEN) { addIpAction(tr("Host bug! - header len != ") + QString::number(SERVER_HEADER_LEN), peerAddress().toString()); } write(servHeader); } else { servHeader.append(QByteArray(NUM_OF_SEQ + 4, 0)); write(servHeader); waitForBytesWritten(); sessionEnding = true; emit deleteSession(sessionId); } } else { addIpAction(tr("Invalid tag"), peerAddress().toString()); sessionEnding = true; emit deleteSession(sessionId); } } } }
Java
class UsersController < ApplicationController def index users = User.all render json: users end end
Java
export * from './results.handler';
Java
using System; using System.IO; using System.Collections.Generic; using System.Text; using Kontract.IO; namespace Kontract.Compression { public class LZSSVLE { public static byte[] Decompress(Stream input, bool leaveOpen = false) { using (var br = new BinaryReader(input, Encoding.Default, leaveOpen)) { Tuple<int, int> GetNibbles(byte b) => new Tuple<int, int>(b >> 4, b & 0xF); int ReadVLC(int seed = 0) { while (true) { var b = br.ReadByte(); seed = (seed << 7) | (b / 2); if (b % 2 != 0) return seed; } } var filesize = ReadVLC(); var unk1 = ReadVLC(); // filetype maybe??? var unk2 = ReadVLC(); // compression type = 1 (LZSS?) var buffer = new List<byte>(); while (buffer.Count < filesize) { // literal var copiesSize = GetNibbles(br.ReadByte()); var copies = copiesSize.Item1; var size = copiesSize.Item2; if (size == 0) size = ReadVLC(); if (copies == 0) copies = ReadVLC(); buffer.AddRange(br.ReadBytes(size)); // copy stuff while (copies-- > 0) { var lengthOffset = GetNibbles(br.ReadByte()); var length = lengthOffset.Item1; var offset = lengthOffset.Item2; if (offset % 2 == 0) offset = ReadVLC(offset / 2) * 2; else offset >>= 1; if (length == 0) length = ReadVLC(length); while (length-- >= 0) buffer.Add(buffer[buffer.Count - offset / 2 - 1]); } } return buffer.ToArray(); } } } }
Java
<? if($this->uri->segment(3,'add') == 'add'): ?> <h2>Create user</h2> <? else: ?> <h2>Edit user "<?= $member->full_name; ?>"</h2> <? endif; ?> <?=form_open($this->uri->uri_string()); ?> <fieldset> <legend>Details</legend> <div class="field"> <label for="first_name">First Name</label> <?= form_input('first_name', $member->first_name, 'class="text"'); ?> </div> <div class="field"> <label for="first_name">Surname</label> <?= form_input('last_name', $member->last_name, 'class="text"'); ?> </div> <div class="field"> <label for="email">E-mail</label> <?= form_input('email', $member->email, 'class="text"'); ?> </div> <div class="field"> <label for="active">Activate</label> <?= form_checkbox('is_active', 1, $member->is_active == 1); ?> </div> </fieldset> <fieldset> <legend>Password</legend> <div class="field"> <label for="password">Password</label> <?= form_password('password', '', 'class="text"'); ?> </div> <div class="field"> <label for="confirm_password">Confirm Password</label> <?= form_password('confirm_password', '', 'class="text"'); ?> </div> </fieldset> <? $this->load->view('admin/layout_fragments/table_buttons', array('buttons' => array('save', 'cancel') )); ?> <?=form_close(); ?>
Java
#ifndef UNIFORMVARIABLEEDITOR_H #define UNIFORMVARIABLEEDITOR_H #include <QDialog> #include <QDebug> #include <QComboBox> #include <QLineEdit> #include <QVBoxLayout> #include <QHBoxLayout> #include <QScrollBar> #include <QWidget> #include "setvariablewidget.h" namespace Ui { class UniformVariableEditor; } class UniformVariableEditor : public QDialog { Q_OBJECT public: struct UniformAttachment { QString uniformName; QString programName; QString variableName; }; public: explicit UniformVariableEditor(QWidget *parent = 0); ~UniformVariableEditor(); void setUniformSettings(QList<UniformAttachment> list); QList<UniformAttachment> getUniformSettings(); QList<UniformAttachment> getRemovedSettings(); private: void customConnect(); private: Ui::UniformVariableEditor *ui; const int layerIncY; int layerY; QVBoxLayout* vbox; QList<SetVariableWidget*> lines; QList<UniformAttachment> removed; private slots: void addNewUniformWidgetLine(); void removeUniformWidgetLine(QWidget* widget); }; #endif // UNIFORMVARIABLEEDITOR_H
Java
#include <vigir_footstep_planning_plugins/plugin_aggregators/world_model.h> namespace vigir_footstep_planning { WorldModel::WorldModel() : ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>("WorldModel") { } void WorldModel::loadPlugins(bool print_warning) { ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>::loadPlugins(print_warning); // get terrain model vigir_pluginlib::PluginManager::getPlugin(terrain_model_); if (terrain_model_) { ROS_INFO("[WorldModel] Found terrain model:"); ROS_INFO(" %s (%s)", terrain_model_->getName().c_str(), terrain_model_->getTypeClass().c_str()); } } bool WorldModel::loadParams(const vigir_generic_params::ParameterSet& params) { bool result = ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>::loadParams(params); if (terrain_model_) result &= terrain_model_->loadParams(params); return result; } void WorldModel::resetPlugins() { ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>::resetPlugins(); if (terrain_model_) terrain_model_->reset(); } bool WorldModel::isAccessible(const State& s) const { for (CollisionCheckPlugin::Ptr plugin : getPlugins()) { if (plugin && plugin->isCollisionCheckAvailable() && !plugin->isAccessible(s)) return false; } return true; } bool WorldModel::isAccessible(const State& next, const State& current) const { for (CollisionCheckPlugin::Ptr plugin : getPlugins()) { if (plugin && plugin->isCollisionCheckAvailable() && !plugin->isAccessible(next, current)) return false; } return true; } void WorldModel::useTerrainModel(bool enabled) { use_terrain_model_ = enabled; } bool WorldModel::isTerrainModelAvailable() const { return terrain_model_ && terrain_model_->isTerrainModelAvailable(); } TerrainModelPlugin::ConstPtr WorldModel::getTerrainModel() const { return terrain_model_; } bool WorldModel::getHeight(double x, double y, double& height) const { if (!use_terrain_model_ || !isTerrainModelAvailable()) return true; return terrain_model_->getHeight(x, y, height); } bool WorldModel::update3DData(State& s) const { if (!use_terrain_model_ || !isTerrainModelAvailable()) return true; return terrain_model_->update3DData(s); } }
Java
# -*- encoding: utf-8 -*- # # OpenERP, Open Source Management Solution # This module copyright (C) 2014 Savoir-faire Linux # (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import logging from openerp.osv import osv, fields _logger = logging.getLogger(__name__) class res_users(osv.osv): _inherit = "res.users" _columns = { 'xis_user_external_id': fields.integer('XIS external user', required=True), }
Java
<?php include_once 'CommunityApi.php'; use Illuminate\Foundation\Testing\DatabaseTransactions; class DeleteCommunityApiTest extends CommunityApi { use DatabaseTransactions; public function setUp() { parent::setUp(); } /////////////////////////////////////////////////////////// CORRECT RESPONSES /** @test ******************/ public function delete_community_correct_response() { $this->signInAsRole('administrator'); $community = factory(App\Community::class)->create(); $this->delete('/api/community/'.$community->slug) ->assertResponseStatus(200); } /////////////////////////////////////////////////////////// INCORRECT RESPONSES }
Java
/*global require,module,console,angular */ require("angular/angular"); require("angular-route/angular-route"); angular.module("RegistrationApp", ["ngRoute"]); angular.module("RegistrationApp").controller("RegistrationCtrl", require("./components/registration/controller")); angular.module("RegistrationApp").directive("myRegistration", require("./components/registration/directive")); angular.module("MainApp", [ "RegistrationApp" ]); angular.module("MainApp").config(["$routeProvider", "$locationProvider", require("./app.routes")]);
Java
package com.lizardtech.djvubean.outline; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListCellRenderer; import javax.swing.UIManager; public class ImageListCellRenderer implements ListCellRenderer { /** * From <a href="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:" title="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:">http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:</a> * * Return a component that has been configured to display the specified value. * That component's paint method is then called to "render" the cell. * If it is necessary to compute the dimensions of a list because the list cells do not have a fixed size, * this method is called to generate a component on which getPreferredSize can be invoked. * * jlist - the jlist we're painting * value - the value returned by list.getModel().getElementAt(index). * cellIndex - the cell index * isSelected - true if the specified cell is currently selected * cellHasFocus - true if the cell has focus */ public Component getListCellRendererComponent(JList jlist, Object value, int cellIndex, boolean isSelected, boolean cellHasFocus) { if (value instanceof JPanel) { Component component = (Component) value; component.setForeground (Color.white); component.setBackground (isSelected ? UIManager.getColor("Table.focusCellForeground") : Color.white); return component; } else { // TODO - I get one String here when the JList is first rendered; proper way to deal with this? //System.out.println("Got something besides a JPanel: " + value.getClass().getCanonicalName()); return new JLabel("???"); } }}
Java
Discussion Inserts =================== A Vanilla Forums plugin that attaches an insert to a specific discussion. It is released under the GPLv3 and may be released under a different license with permission. A special thanks the phreak @ VanillaSkins.com for sponsorship. Install ======= 1. Drop the DiscussionInserts folder into your vanilla/plugins folder. 2. Enable the plugin in your dashboard 3. Enjoy!
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Created by texi2html, http://www.gnu.org/software/texinfo/ --> <head> <title>Singular 2-0-4 Manual: D.5.5.15 newtonpoly</title> <meta name="description" content="Singular 2-0-4 Manual: D.5.5.15 newtonpoly"> <meta name="keywords" content="Singular 2-0-4 Manual: D.5.5.15 newtonpoly"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="texi2html"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> <!-- @import "sing_tex4ht_tex.css"; a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} pre.display {font-family: serif} pre.format {font-family: serif} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: serif; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: serif; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:pre} span.nolinebreak {white-space:pre} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} --> </style> </head> <body lang="en" background="../singular_images/Mybg.png"> <a name="newtonpoly"></a> <table border="0" cellpadding="0" cellspacing="0"> <tr valign="top"> <td align="left"> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr valign="top" align="left"> <td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/singular-icon-transparent.png" width="50" border="0" alt="Top"></a> </td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="delta.html#delta" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.5.5.14 delta" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="is_005fNND.html#is_005fNND" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.5.5.16 is_NND" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="hnoether_005flib.html#hnoether_005flib" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.5.5 hnoether_lib" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr> </table> </td> <td align="left"> <a name="newtonpoly-1"></a> <h4 class="subsubsection">D.5.5.15 newtonpoly</h4> <a name="index-newtonpoly"></a> <p>Procedure from library <code>hnoether.lib</code> (see <a href="hnoether_005flib.html#hnoether_005flib">hnoether_lib</a>). </p> <dl compact="compact"> <dt><strong>Usage:</strong></dt> <dd><p>newtonpoly(f); f poly </p> </dd> <dt><strong>Assume:</strong></dt> <dd><p>basering has exactly two variables; <br> f is convenient, that is, f(x,0) != 0 != f(0,y). </p> </dd> <dt><strong>Return:</strong></dt> <dd><p>list of intvecs (= coordinates x,y of the Newton polygon of f). </p> </dd> <dt><strong>Note:</strong></dt> <dd><p>Procedure uses <code>execute</code>; this can be avoided by calling <code>newtonpoly(f,1)</code> if the ordering of the basering is <code>ls</code>. </p> <a name="index-Newton-polygon"></a> </dd> </dl> <p><strong>Example:</strong> </p><div class="smallexample"> <pre class="smallexample">LIB &quot;hnoether.lib&quot;; ring r=0,(x,y),ls; poly f=x5+2x3y-x2y2+3xy5+y6-y7; newtonpoly(f); &rarr; [1]: &rarr; 0,6 &rarr; [2]: &rarr; 2,2 &rarr; [3]: &rarr; 3,1 &rarr; [4]: &rarr; 5,0 </pre></div> </td> </tr> </table> <hr> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/singular-icon-transparent.png" width="50" border="0" alt="Top"></a> </td> <td valign="middle" align="left"><a href="delta.html#delta" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.5.5.14 delta" align="middle"></a></td> <td valign="middle" align="left"><a href="is_005fNND.html#is_005fNND" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.5.5.16 is_NND" align="middle"></a></td> <td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td> <td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td> <td valign="middle" align="left"><a href="hnoether_005flib.html#hnoether_005flib" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.5.5 hnoether_lib" align="middle"></a></td> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr></table> <font size="-1"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; User manual for <a href="http://www.singular.uni-kl.de/"><i>Singular</i></a> version 2-0-4, October 2002, generated by <a href="http://www.gnu.org/software/texinfo/"><i>texi2html</i></a>. </font> </body> </html>
Java
/***************************************************************************** * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 * * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ #pragma once // Structures shared between both RCT1 and RCT2. #include "../common.h" #include "../object/Object.h" #include <string> #include <string_view> constexpr const uint8_t RCT12_MAX_RIDES_IN_PARK = 255; constexpr const uint8_t RCT12_MAX_AWARDS = 4; constexpr const uint8_t RCT12_MAX_NEWS_ITEMS = 61; constexpr const uint8_t RCT12_MAX_STATIONS_PER_RIDE = 4; constexpr const uint8_t RCT12_MAX_PEEP_SPAWNS = 2; constexpr const uint8_t RCT12_MAX_PARK_ENTRANCES = 4; // The number of elements in the patrol_areas array per staff member. Every bit in the array represents a 4x4 square. // In RCT1, that's an 8-bit array. 8 * 128 = 1024 bits, which is also the number of 4x4 squares on a 128x128 map. // For RCT2, it's a 32-bit array. 32 * 128 = 4096 bits, which is also the number of 4x4 squares on a 256x256 map. constexpr const uint8_t RCT12_PATROL_AREA_SIZE = 128; constexpr const uint8_t RCT12_STAFF_TYPE_COUNT = 4; constexpr const uint8_t RCT12_NUM_COLOUR_SCHEMES = 4; constexpr const uint8_t RCT12_MAX_VEHICLE_COLOURS = 32; constexpr const uint8_t RCT12_SOUND_ID_NULL = 0xFF; constexpr const uint8_t RCT12_EXPENDITURE_TABLE_MONTH_COUNT = 16; constexpr const uint8_t RCT12_EXPENDITURE_TYPE_COUNT = 14; constexpr const uint8_t RCT12_FINANCE_GRAPH_SIZE = 128; constexpr const uint16_t RCT12_MAX_USER_STRINGS = 1024; constexpr const uint8_t RCT12_USER_STRING_MAX_LENGTH = 32; constexpr const uint8_t RCT12_PEEP_MAX_THOUGHTS = 5; constexpr const uint8_t RCT12_RIDE_ID_NULL = 255; constexpr const uint16_t RCT12_RIDE_MEASUREMENT_MAX_ITEMS = 4800; constexpr uint16_t const RCT12_MAX_INVERSIONS = 31; constexpr uint16_t const RCT12_MAX_GOLF_HOLES = 31; constexpr uint16_t const RCT12_MAX_HELICES = 31; constexpr uint8_t RCT12_BANNER_INDEX_NULL = std::numeric_limits<uint8_t>::max(); constexpr const uint8_t RCT12_TILE_ELEMENT_SURFACE_EDGE_STYLE_MASK = 0xE0; // in RCT12TileElement.properties.surface.slope constexpr const uint8_t RCT12_TILE_ELEMENT_SURFACE_WATER_HEIGHT_MASK = 0x1F; // in RCT12TileElement.properties.surface.terrain constexpr const uint8_t RCT12_TILE_ELEMENT_SURFACE_TERRAIN_MASK = 0xE0; // in RCT12TileElement.properties.surface.terrain constexpr const uint16_t RCT12_TILE_ELEMENT_LARGE_TYPE_MASK = 0x3FF; constexpr uint16_t const RCT12_XY8_UNDEFINED = 0xFFFF; using RCT12ObjectEntryIndex = uint8_t; constexpr const RCT12ObjectEntryIndex RCT12_OBJECT_ENTRY_INDEX_NULL = 255; // Everything before this point has been researched constexpr const uint32_t RCT12_RESEARCHED_ITEMS_SEPARATOR = 0xFFFFFFFF; // Everything before this point and after separator still requires research constexpr const uint32_t RCT12_RESEARCHED_ITEMS_END = 0xFFFFFFFE; // Extra end of list entry. Leftover from RCT1. constexpr const uint32_t RCT12_RESEARCHED_ITEMS_END_2 = 0xFFFFFFFD; constexpr const uint8_t RCT12_MAX_ELEMENT_HEIGHT = 255; constexpr const uint16_t RCT12_PEEP_SPAWN_UNDEFINED = 0xFFFF; enum class RCT12TrackDesignVersion : uint8_t { TD4, TD4_AA, TD6, unknown }; enum { RCT12_TILE_ELEMENT_FLAG_GHOST = (1 << 4), RCT12_TILE_ELEMENT_FLAG_BROKEN = (1 << 5), RCT12_TILE_ELEMENT_FLAG_BLOCK_BRAKE_CLOSED = (1 << 5), RCT12_TILE_ELEMENT_FLAG_INDESTRUCTIBLE_TRACK_PIECE = (1 << 6), RCT12_TILE_ELEMENT_FLAG_BLOCKED_BY_VEHICLE = (1 << 6), RCT12_TILE_ELEMENT_FLAG_LARGE_SCENERY_ACCOUNTED = (1 << 6), RCT12_TILE_ELEMENT_FLAG_LAST_TILE = (1 << 7) }; enum { RCT12_TRACK_ELEMENT_TYPE_FLAG_CHAIN_LIFT = 1 << 7, }; enum { RCT12_TRACK_ELEMENT_SEQUENCE_STATION_INDEX_MASK = 0b01110000, RCT12_TRACK_ELEMENT_SEQUENCE_SEQUENCE_MASK = 0b00001111, RCT12_TRACK_ELEMENT_SEQUENCE_TAKING_PHOTO_MASK = 0b11110000, }; enum { // Not anything to do with colour but uses // that field in the tile element // Used for multi-dimension coaster RCT12_TRACK_ELEMENT_COLOUR_FLAG_INVERTED = (1 << 2), // Used for giga coaster RCT12_TRACK_ELEMENT_COLOUR_FLAG_CABLE_LIFT = (1 << 3), RCT12_TRACK_ELEMENT_DOOR_A_MASK = 0b00011100, RCT12_TRACK_ELEMENT_DOOR_B_MASK = 0b11100000, }; // Masks and flags for values stored in TileElement.properties.path.type enum { RCT12_FOOTPATH_PROPERTIES_SLOPE_DIRECTION_MASK = (1 << 0) | (1 << 1), RCT12_FOOTPATH_PROPERTIES_FLAG_IS_SLOPED = (1 << 2), RCT12_FOOTPATH_PROPERTIES_FLAG_HAS_QUEUE_BANNER = (1 << 3), RCT12_FOOTPATH_PROPERTIES_TYPE_MASK = (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7), }; // Masks and flags for values stored in in RCT12TileElement.properties.path.additions enum { RCT12_FOOTPATH_PROPERTIES_ADDITIONS_TYPE_MASK = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3), // The most significant bit in this mask will always be zero, since rides can only have 4 stations RCT12_FOOTPATH_PROPERTIES_ADDITIONS_STATION_INDEX_MASK = (1 << 4) | (1 << 5) | (1 << 6), RCT12_FOOTPATH_PROPERTIES_ADDITIONS_FLAG_GHOST = (1 << 7), }; enum { RCT12_STATION_STYLE_PLAIN, RCT12_STATION_STYLE_WOODEN, RCT12_STATION_STYLE_CANVAS_TENT, RCT12_STATION_STYLE_CASTLE_GREY, RCT12_STATION_STYLE_CASTLE_BROWN, RCT12_STATION_STYLE_JUNGLE, RCT12_STATION_STYLE_LOG_CABIN, RCT12_STATION_STYLE_CLASSICAL, RCT12_STATION_STYLE_ABSTRACT, RCT12_STATION_STYLE_SNOW, RCT12_STATION_STYLE_PAGODA, RCT12_STATION_STYLE_SPACE, RCT12_STATION_STYLE_INVISIBLE, // Added by OpenRCT2 }; #pragma pack(push, 1) struct RCT12xy8 { union { struct { uint8_t x, y; }; uint16_t xy; }; bool isNull() const { return xy == RCT12_XY8_UNDEFINED; } void setNull() { xy = RCT12_XY8_UNDEFINED; } }; assert_struct_size(RCT12xy8, 2); /* Maze Element entry size: 0x04 */ struct rct_td46_maze_element { union { uint32_t all; struct { int8_t x; int8_t y; union { uint16_t maze_entry; struct { uint8_t direction; uint8_t type; }; }; }; }; }; assert_struct_size(rct_td46_maze_element, 0x04); /* Track Element entry size: 0x02 */ struct rct_td46_track_element { uint8_t type; // 0x00 uint8_t flags; // 0x01 }; assert_struct_size(rct_td46_track_element, 0x02); struct rct12_award { uint16_t time; uint16_t type; }; assert_struct_size(rct12_award, 4); /** * A single news item / message. * size: 0x10C */ struct rct12_news_item { uint8_t Type; uint8_t Flags; uint32_t Assoc; uint16_t Ticks; uint16_t MonthYear; uint8_t Day; uint8_t pad_0B; char Text[256]; }; assert_struct_size(rct12_news_item, 0x10C); struct rct12_xyzd8 { uint8_t x, y, z, direction; }; assert_struct_size(rct12_xyzd8, 4); struct rct12_peep_spawn { uint16_t x; uint16_t y; uint8_t z; uint8_t direction; }; assert_struct_size(rct12_peep_spawn, 6); enum class RCT12TileElementType : uint8_t { Surface = (0 << 2), Path = (1 << 2), Track = (2 << 2), SmallScenery = (3 << 2), Entrance = (4 << 2), Wall = (5 << 2), LargeScenery = (6 << 2), Banner = (7 << 2), Corrupt = (8 << 2), EightCarsCorrupt14 = (14 << 2), EightCarsCorrupt15 = (15 << 2), }; struct RCT12SurfaceElement; struct RCT12PathElement; struct RCT12TrackElement; struct RCT12SmallSceneryElement; struct RCT12LargeSceneryElement; struct RCT12WallElement; struct RCT12EntranceElement; struct RCT12BannerElement; struct RCT12CorruptElement; struct RCT12EightCarsCorruptElement14; struct RCT12EightCarsCorruptElement15; struct RCT12TileElementBase { uint8_t type; // 0 uint8_t flags; // 1. Upper nibble: flags. Lower nibble: occupied quadrants (one bit per quadrant). uint8_t base_height; // 2 uint8_t clearance_height; // 3 uint8_t GetType() const; uint8_t GetDirection() const; void SetDirection(uint8_t direction); uint8_t GetOccupiedQuadrants() const; void SetOccupiedQuadrants(uint8_t quadrants); bool IsLastForTile() const; void SetLastForTile(bool on); bool IsGhost() const; void SetGhost(bool isGhost); }; /** * Map element structure * size: 0x08 */ struct RCT12TileElement : public RCT12TileElementBase { uint8_t pad_04[4]; template<typename TType, RCT12TileElementType TClass> TType* as() const { return static_cast<RCT12TileElementType>(GetType()) == TClass ? reinterpret_cast<TType*>(const_cast<RCT12TileElement*>(this)) : nullptr; } RCT12SurfaceElement* AsSurface() const { return as<RCT12SurfaceElement, RCT12TileElementType::Surface>(); } RCT12PathElement* AsPath() const { return as<RCT12PathElement, RCT12TileElementType::Path>(); } RCT12TrackElement* AsTrack() const { return as<RCT12TrackElement, RCT12TileElementType::Track>(); } RCT12SmallSceneryElement* AsSmallScenery() const { return as<RCT12SmallSceneryElement, RCT12TileElementType::SmallScenery>(); } RCT12LargeSceneryElement* AsLargeScenery() const { return as<RCT12LargeSceneryElement, RCT12TileElementType::LargeScenery>(); } RCT12WallElement* AsWall() const { return as<RCT12WallElement, RCT12TileElementType::Wall>(); } RCT12EntranceElement* AsEntrance() const { return as<RCT12EntranceElement, RCT12TileElementType::Entrance>(); } RCT12BannerElement* AsBanner() const { return as<RCT12BannerElement, RCT12TileElementType::Banner>(); } void ClearAs(uint8_t newType); uint8_t GetBannerIndex(); }; assert_struct_size(RCT12TileElement, 8); struct RCT12SurfaceElement : RCT12TileElementBase { private: uint8_t slope; // 4 0xE0 Edge Style, 0x1F Slope uint8_t terrain; // 5 0xE0 Terrain Style, 0x1F Water height uint8_t grass_length; // 6 uint8_t ownership; // 7 public: uint8_t GetSlope() const; uint32_t GetSurfaceStyle() const; uint32_t GetEdgeStyle() const; uint8_t GetGrassLength() const; uint8_t GetOwnership() const; uint32_t GetWaterHeight() const; uint8_t GetParkFences() const; bool HasTrackThatNeedsWater() const; void SetSlope(uint8_t newSlope); void SetSurfaceStyle(uint32_t newStyle); void SetEdgeStyle(uint32_t newStyle); void SetGrassLength(uint8_t newLength); void SetOwnership(uint8_t newOwnership); void SetWaterHeight(uint32_t newWaterHeight); void SetParkFences(uint8_t newParkFences); void SetHasTrackThatNeedsWater(bool on); }; assert_struct_size(RCT12SurfaceElement, 8); struct RCT12PathElement : RCT12TileElementBase { private: uint8_t entryIndex; // 4, 0xF0 Path type, 0x08 Ride sign, 0x04 Set when path is sloped, 0x03 Rotation uint8_t additions; // 5, 0bGSSSAAAA: G = Ghost, S = station index, A = addition (0 means no addition) uint8_t edges; // 6 union { uint8_t additionStatus; // 7 uint8_t rideIndex; }; public: RCT12ObjectEntryIndex GetEntryIndex() const; uint8_t GetQueueBannerDirection() const; bool IsSloped() const; uint8_t GetSlopeDirection() const; uint8_t GetRideIndex() const; uint8_t GetStationIndex() const; bool IsWide() const; bool IsQueue() const; bool HasQueueBanner() const; uint8_t GetEdges() const; uint8_t GetCorners() const; uint8_t GetAddition() const; bool AdditionIsGhost() const; uint8_t GetAdditionStatus() const; uint8_t GetRCT1PathType() const; uint8_t GetRCT1SupportType() const; void SetPathEntryIndex(RCT12ObjectEntryIndex newIndex); void SetQueueBannerDirection(uint8_t direction); void SetSloped(bool isSloped); void SetSlopeDirection(uint8_t newSlope); void SetRideIndex(uint8_t newRideIndex); void SetStationIndex(uint8_t newStationIndex); void SetWide(bool isWide); void SetIsQueue(bool isQueue); void SetHasQueueBanner(bool hasQueueBanner); void SetEdges(uint8_t newEdges); void SetCorners(uint8_t newCorners); void SetAddition(uint8_t newAddition); void SetAdditionIsGhost(bool isGhost); void SetAdditionStatus(uint8_t newStatus); bool IsBroken() const; void SetIsBroken(bool isBroken); bool IsBlockedByVehicle() const; void SetIsBlockedByVehicle(bool isBlocked); }; assert_struct_size(RCT12PathElement, 8); struct RCT12TrackElement : RCT12TileElementBase { private: uint8_t trackType; // 4 union { struct { // The lower 4 bits are the track sequence. // The upper 4 bits are either station bits or on-ride photo bits. // // Station bits: // - Bit 8 marks green light // - Bit 5-7 are station index. // // On-ride photo bits: // - Bits 7 and 8 are never set // - Bits 5 and 6 are set when a vehicle triggers the on-ride photo and act like a countdown from 3. // - If any of the bits 5-8 are set, the game counts it as a photo being taken. uint8_t sequence; // 5. uint8_t colour; // 6 }; uint16_t mazeEntry; // 5 }; uint8_t rideIndex; // 7 public: uint8_t GetTrackType() const; uint8_t GetSequenceIndex() const; uint8_t GetRideIndex() const; uint8_t GetColourScheme() const; uint8_t GetStationIndex() const; bool HasChain() const; bool HasCableLift() const; bool IsInverted() const; uint8_t GetBrakeBoosterSpeed() const; bool HasGreenLight() const; uint8_t GetSeatRotation() const; uint16_t GetMazeEntry() const; uint8_t GetPhotoTimeout() const; // Used in RCT1, will be reintroduced at some point. // (See https://github.com/OpenRCT2/OpenRCT2/issues/7059) uint8_t GetDoorAState() const; uint8_t GetDoorBState() const; void SetTrackType(uint8_t newEntryIndex); void SetSequenceIndex(uint8_t newSequenceIndex); void SetRideIndex(uint8_t newRideIndex); void SetColourScheme(uint8_t newColourScheme); void SetStationIndex(uint8_t newStationIndex); void SetHasChain(bool on); void SetHasCableLift(bool on); void SetInverted(bool inverted); bool BlockBrakeClosed() const; void SetBlockBrakeClosed(bool isClosed); void SetBrakeBoosterSpeed(uint8_t speed); void SetHasGreenLight(uint8_t greenLight); void SetSeatRotation(uint8_t newSeatRotation); void SetMazeEntry(uint16_t newMazeEntry); void SetPhotoTimeout(uint8_t newValue); bool IsIndestructible() const; void SetIsIndestructible(bool isIndestructible); }; assert_struct_size(RCT12TrackElement, 8); struct RCT12SmallSceneryElement : RCT12TileElementBase { private: uint8_t entryIndex; // 4 uint8_t age; // 5 uint8_t colour_1; // 6 uint8_t colour_2; // 7 public: RCT12ObjectEntryIndex GetEntryIndex() const; uint8_t GetAge() const; uint8_t GetSceneryQuadrant() const; colour_t GetPrimaryColour() const; colour_t GetSecondaryColour() const; bool NeedsSupports() const; void SetEntryIndex(RCT12ObjectEntryIndex newIndex); void SetAge(uint8_t newAge); void SetSceneryQuadrant(uint8_t newQuadrant); void SetPrimaryColour(colour_t colour); void SetSecondaryColour(colour_t colour); void SetNeedsSupports(); }; assert_struct_size(RCT12SmallSceneryElement, 8); struct RCT12LargeSceneryElement : RCT12TileElementBase { private: uint16_t entryIndex; // 4 uint8_t colour[2]; // 6 public: uint32_t GetEntryIndex() const; uint16_t GetSequenceIndex() const; colour_t GetPrimaryColour() const; colour_t GetSecondaryColour() const; uint8_t GetBannerIndex() const; void SetEntryIndex(uint32_t newIndex); void SetSequenceIndex(uint16_t sequence); void SetPrimaryColour(colour_t colour); void SetSecondaryColour(colour_t colour); void SetBannerIndex(uint8_t newIndex); }; assert_struct_size(RCT12LargeSceneryElement, 8); struct RCT12WallElement : RCT12TileElementBase { private: uint8_t entryIndex; // 4 union { uint8_t colour_3; // 5 uint8_t banner_index; // 5 }; uint8_t colour_1; // 6 0b_2221_1111 2 = colour_2 (uses flags for rest of colour2), 1 = colour_1 uint8_t animation; // 7 0b_dfff_ft00 d = direction, f = frame num, t = across track flag (not used) public: RCT12ObjectEntryIndex GetEntryIndex() const; uint8_t GetSlope() const; colour_t GetPrimaryColour() const; colour_t GetSecondaryColour() const; colour_t GetTertiaryColour() const; uint8_t GetAnimationFrame() const; uint8_t GetBannerIndex() const; bool IsAcrossTrack() const; bool AnimationIsBackwards() const; uint32_t GetRawRCT1WallTypeData() const; int32_t GetRCT1WallType(int32_t edge) const; colour_t GetRCT1WallColour() const; void SetEntryIndex(RCT12ObjectEntryIndex newIndex); void SetSlope(uint8_t newslope); void SetPrimaryColour(colour_t newColour); void SetSecondaryColour(colour_t newColour); void SetTertiaryColour(colour_t newColour); void SetAnimationFrame(uint8_t frameNum); void SetBannerIndex(uint8_t newIndex); void SetAcrossTrack(bool acrossTrack); void SetAnimationIsBackwards(bool isBackwards); }; assert_struct_size(RCT12WallElement, 8); struct RCT12EntranceElement : RCT12TileElementBase { private: uint8_t entranceType; // 4 uint8_t index; // 5. 0bUSSS????, S = station index. uint8_t pathType; // 6 uint8_t rideIndex; // 7 public: uint8_t GetEntranceType() const; uint8_t GetRideIndex() const; uint8_t GetStationIndex() const; uint8_t GetSequenceIndex() const; uint8_t GetPathType() const; void SetEntranceType(uint8_t newType); void SetRideIndex(uint8_t newRideIndex); void SetStationIndex(uint8_t stationIndex); void SetSequenceIndex(uint8_t newSequenceIndex); void SetPathType(uint8_t newPathType); }; assert_struct_size(RCT12EntranceElement, 8); struct RCT12BannerElement : RCT12TileElementBase { private: uint8_t index; // 4 uint8_t position; // 5 uint8_t flags; // 6 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" uint8_t unused; // 7 #pragma clang diagnostic pop public: uint8_t GetIndex() const; uint8_t GetPosition() const; uint8_t GetAllowedEdges() const; void SetIndex(uint8_t newIndex); void SetPosition(uint8_t newPosition); void SetAllowedEdges(uint8_t newEdges); }; assert_struct_size(RCT12BannerElement, 8); struct RCT12CorruptElement : RCT12TileElementBase { uint8_t pad[4]; }; assert_struct_size(RCT12CorruptElement, 8); struct RCT12EightCarsCorruptElement14 : RCT12TileElementBase { uint8_t pad[4]; }; assert_struct_size(RCT12EightCarsCorruptElement14, 8); struct RCT12EightCarsCorruptElement15 : RCT12TileElementBase { uint8_t pad[4]; }; assert_struct_size(RCT12EightCarsCorruptElement15, 8); struct RCT12SpriteBase { uint8_t sprite_identifier; // 0x00 uint8_t type; // 0x01 uint16_t next_in_quadrant; // 0x02 uint16_t next; // 0x04 uint16_t previous; // 0x06 uint8_t linked_list_type_offset; // 0x08 uint8_t sprite_height_negative; // 0x09 uint16_t sprite_index; // 0x0A uint16_t flags; // 0x0C int16_t x; // 0x0E int16_t y; // 0x10 int16_t z; // 0x12 uint8_t sprite_width; // 0x14 uint8_t sprite_height_positive; // 0x15 int16_t sprite_left; // 0x16 int16_t sprite_top; // 0x18 int16_t sprite_right; // 0x1A int16_t sprite_bottom; // 0x1C uint8_t sprite_direction; // 0x1E }; assert_struct_size(RCT12SpriteBase, 0x1F); struct RCT12SpriteBalloon : RCT12SpriteBase { uint8_t pad_1F[0x24 - 0x1F]; uint16_t popped; // 0x24 uint8_t time_to_move; // 0x26 uint8_t frame; // 0x27 uint8_t pad_28[4]; uint8_t colour; // 0x2C }; assert_struct_size(RCT12SpriteBalloon, 0x2D); struct RCT12SpriteDuck : RCT12SpriteBase { uint8_t pad_1F[0x26 - 0x1F]; uint16_t frame; // 0x26 uint8_t pad_28[0x30 - 0x28]; int16_t target_x; // 0x30 int16_t target_y; // 0x32 uint8_t pad_34[0x14]; uint8_t state; // 0x48 }; assert_struct_size(RCT12SpriteDuck, 0x49); struct RCT12SpriteLitter : RCT12SpriteBase { uint8_t pad_1F[0x24 - 0x1F]; uint32_t creationTick; // 0x24 }; assert_struct_size(RCT12SpriteLitter, 0x28); struct RCT12SpriteParticle : RCT12SpriteBase { uint8_t pad_1F[0x26 - 0x1F]; uint16_t frame; // 0x26 }; assert_struct_size(RCT12SpriteParticle, 0x28); struct RCT12SpriteJumpingFountain : RCT12SpriteBase { uint8_t pad_1F[0x26 - 0x1F]; uint8_t num_ticks_alive; // 0x26 uint8_t frame; // 0x27 uint8_t pad_28[0x2F - 0x28]; uint8_t fountain_flags; // 0x2F int16_t target_x; // 0x30 int16_t target_y; // 0x32 uint8_t pad_34[0x46 - 0x34]; uint16_t iteration; // 0x46 }; assert_struct_size(RCT12SpriteJumpingFountain, 0x48); struct RCT12SpriteMoneyEffect : RCT12SpriteBase { uint8_t pad_1F[0x24 - 0x1F]; uint16_t move_delay; // 0x24 uint8_t num_movements; // 0x26 uint8_t vertical; money32 value; // 0x28 uint8_t pad_2C[0x44 - 0x2C]; int16_t offset_x; // 0x44 uint16_t wiggle; // 0x46 }; assert_struct_size(RCT12SpriteMoneyEffect, 0x48); struct RCT12SpriteCrashedVehicleParticle : RCT12SpriteBase { uint8_t pad_1F[0x24 - 0x1F]; uint16_t time_to_live; // 0x24 uint16_t frame; // 0x26 uint8_t pad_28[0x2C - 0x28]; uint8_t colour[2]; // 0x2C uint16_t crashed_sprite_base; // 0x2E int16_t velocity_x; // 0x30 int16_t velocity_y; // 0x32 int16_t velocity_z; // 0x34 uint8_t pad_36[0x38 - 0x36]; int32_t acceleration_x; // 0x38 int32_t acceleration_y; // 0x3C int32_t acceleration_z; // 0x40 }; assert_struct_size(RCT12SpriteCrashedVehicleParticle, 0x44); struct RCT12SpriteCrashSplash : RCT12SpriteBase { uint8_t pad_1F[0x26 - 0x1F]; uint16_t frame; // 0x26 }; assert_struct_size(RCT12SpriteCrashSplash, 0x28); struct RCT12SpriteSteamParticle : RCT12SpriteBase { uint8_t pad_1F[0x24 - 0x1F]; uint16_t time_to_move; // 0x24 uint16_t frame; // 0x26 }; assert_struct_size(RCT12SpriteSteamParticle, 0x28); struct RCT12PeepThought { uint8_t type; uint8_t item; uint8_t freshness; uint8_t fresh_timeout; }; assert_struct_size(RCT12PeepThought, 4); struct RCT12RideMeasurement { uint8_t ride_index; // 0x0000 uint8_t flags; // 0x0001 uint32_t last_use_tick; // 0x0002 uint16_t num_items; // 0x0006 uint16_t current_item; // 0x0008 uint8_t vehicle_index; // 0x000A uint8_t current_station; // 0x000B int8_t vertical[RCT12_RIDE_MEASUREMENT_MAX_ITEMS]; // 0x000C int8_t lateral[RCT12_RIDE_MEASUREMENT_MAX_ITEMS]; // 0x12CC uint8_t velocity[RCT12_RIDE_MEASUREMENT_MAX_ITEMS]; // 0x258C uint8_t altitude[RCT12_RIDE_MEASUREMENT_MAX_ITEMS]; // 0x384C }; assert_struct_size(RCT12RideMeasurement, 0x4B0C); struct RCT12Banner { RCT12ObjectEntryIndex type; uint8_t flags; // 0x01 rct_string_id string_idx; // 0x02 union { uint8_t colour; // 0x04 uint8_t ride_index; // 0x04 }; uint8_t text_colour; // 0x05 uint8_t x; // 0x06 uint8_t y; // 0x07 }; assert_struct_size(RCT12Banner, 8); struct RCT12MapAnimation { uint8_t baseZ; uint8_t type; uint16_t x; uint16_t y; }; assert_struct_size(RCT12MapAnimation, 6); struct RCT12ResearchItem { // Bit 16 (0: scenery entry, 1: ride entry) union { uint32_t rawValue; struct { RCT12ObjectEntryIndex entryIndex; uint8_t baseRideType; uint8_t type; // 0: scenery entry, 1: ride entry uint8_t flags; }; }; uint8_t category; bool IsInventedEndMarker() const; bool IsRandomEndMarker() const; bool IsUninventedEndMarker() const; }; assert_struct_size(RCT12ResearchItem, 5); #pragma pack(pop) ObjectEntryIndex RCTEntryIndexToOpenRCT2EntryIndex(const RCT12ObjectEntryIndex index); RCT12ObjectEntryIndex OpenRCT2EntryIndexToRCTEntryIndex(const ObjectEntryIndex index);
Java
/* * Copyright (c) by Michał Niedźwiecki 2016 * Contact: nkg753 on gmail or via GitHub profile: dzwiedziu-nkg * * This file is part of Bike Road Quality. * * Bike Road Quality is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Bike Road Quality is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Foobar; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package pl.nkg.brq.android.ui; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import pl.nkg.brq.android.R; import pl.nkg.brq.android.events.SensorsRecord; import pl.nkg.brq.android.events.SensorsServiceState; import pl.nkg.brq.android.services.SensorsService; public class MainActivity extends AppCompatActivity { private static final int MY_PERMISSION_RESPONSE = 29; @Bind(R.id.button_on) Button mButtonOn; @Bind(R.id.button_off) Button mButtonOff; @Bind(R.id.speedTextView) TextView mSpeedTextView; @Bind(R.id.altitudeTextView) TextView mAltitudeTextView; @Bind(R.id.shakeTextView) TextView mShakeTextView; @Bind(R.id.noiseTextView) TextView mNoiseTextView; @Bind(R.id.distanceTextView) TextView mDistanceTextView; @Bind(R.id.warningTextView) TextView mWarningTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Prompt for permissions if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { Log.w("BleActivity", "Location access not granted!"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH}, MY_PERMISSION_RESPONSE); } } ButterKnife.bind(this); } @Override protected void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override protected void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } @OnClick(R.id.button_on) public void onButtonOnClick() { startService(new Intent(MainActivity.this, SensorsService.class)); } @OnClick(R.id.button_off) public void onButtonOffClick() { stopService(new Intent(MainActivity.this, SensorsService.class)); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(SensorsServiceState state) { } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(SensorsRecord record) { mSpeedTextView.setText((int) (record.speed * 3.6) + " km/h"); mAltitudeTextView.setText((int) record.altitude + " m n.p.m."); mShakeTextView.setText((int) (record.shake * 100) / 100.0 + " m/s²"); mNoiseTextView.setText((int) record.soundNoise + " db"); mDistanceTextView.setText((double) record.distance / 100.0 + " m"); if (record.distance < 120 && record.distance != 0) { mWarningTextView.setVisibility(View.VISIBLE); mWarningTextView.setText((double) record.distance / 100.0 + " m"); mWarningTextView.setTextSize(Math.min(5000 / record.distance, 100)); } else { mWarningTextView.setVisibility(View.GONE); } } }
Java
package com.malak.yaim.model; import java.util.List; public class FlickrFeed { private String title; private String link; private String description; private String modified; private String generator; private List<Item> items = null; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getModified() { return modified; } public void setModified(String modified) { this.modified = modified; } public String getGenerator() { return generator; } public void setGenerator(String generator) { this.generator = generator; } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } }
Java
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - LAWSON, Adelaide Kate</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> <link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../families.html" title="Families">Families</a></li> <li><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="IndividualDetail"> <h3>LAWSON, Adelaide Kate<sup><small></small></sup></h3> <div id="summaryarea"> <table class="infolist"> <tr> <td class="ColumnAttribute">Birth Name</td> <td class="ColumnValue"> LAWSON, Adelaide Kate <a href="#sref1a">1a</a> </td> </tr> <tr> <td class="ColumnAttribute">Gramps&nbsp;ID</td> <td class="ColumnValue">I10791</td> </tr> <tr> <td class="ColumnAttribute">Gender</td> <td class="ColumnValue">female</td> </tr> <tr> <td class="ColumnAttribute">Age at Death</td> <td class="ColumnValue">60 years, 5 months, 12 days</td> </tr> </table> </div> <div class="subsection" id="events"> <h4>Events</h4> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> <a href="../../../evt/4/0/d15f603cbd747573e7f39951404.html" title="Birth"> Birth <span class="grampsid"> [E11919]</span> </a> </td> <td class="ColumnDate">1879-11-15</td> <td class="ColumnPlace"> <a href="../../../plc/c/4/d15f5fb92e843882bcabe3e6e4c.html" title=""> </a> </td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> <tr> <td class="ColumnEvent"> <a href="../../../evt/3/1/d15f603cbe04c44437644607713.html" title="Death"> Death <span class="grampsid"> [E11920]</span> </a> </td> <td class="ColumnDate">1940-04-27</td> <td class="ColumnPlace"> <a href="../../../plc/c/4/d15f5fb92e843882bcabe3e6e4c.html" title=""> </a> </td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </div> <div class="subsection" id="parents"> <h4>Parents</h4> <table class="infolist"> <thead> <tr> <th class="ColumnAttribute">Relation to main person</th> <th class="ColumnValue">Name</th> <th class="ColumnValue">Relation within this family (if not by birth)</th> </tr> </thead> <tbody> </tbody> <tr> <td class="ColumnAttribute">Father</td> <td class="ColumnValue"> <a href="../../../ppl/f/8/d15f603c9034e759c0ac890918f.html">LAWSON, William<span class="grampsid"> [I10779]</span></a> </td> </tr> <tr> <td class="ColumnAttribute">Mother</td> <td class="ColumnValue"> <a href="../../../ppl/0/8/d15f603c8b74e5fed8b1ad5f80.html">LUCAS, Adelaide<span class="grampsid"> [I10778]</span></a> </td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/8/3/d15f603c9312348dd5bc05c4d38.html">LAWSON, Alice Emily<span class="grampsid"> [I10780]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/1/7/d15f603c9a67c0aefb00341b271.html">LAWSON, George William<span class="grampsid"> [I10781]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/e/5/d15f603ca2c246079fb8eef625e.html">LAWSON, Bertha Beatrice<span class="grampsid"> [I10784]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/6/0/d15f603ca916c80619d7d9b7706.html">LAWSON, Harry Hatton<span class="grampsid"> [I10786]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/0/9/d15f603cad1cee2ac0f23a7490.html">LAWSON, Hubert Lucas<span class="grampsid"> [I10787]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/4/e/d15f603cb134d5bd1a0733a20e4.html">LAWSON, Ethel Henrietta<span class="grampsid"> [I10788]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/e/d/d15f603cb6117449b9ad6b48de.html">LAWSON, Harold Athol<span class="grampsid"> [I10789]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/0/2/d15f603cb9f1a218c780d708720.html">LAWSON, Emily Lucas<span class="grampsid"> [I10790]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/2/9/d15f603cbce7f07779628b52a92.html">LAWSON, Adelaide Kate<span class="grampsid"> [I10791]</span></a></td> <td class="ColumnValue"></td> </tr> </table> </div> <div class="subsection" id="attributes"> <h4>Attributes</h4> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">A9B9DC830D9475458C1BF923EE4EE5FAFA15</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </div> <div class="subsection" id="pedigree"> <h4>Pedigree</h4> <ol class="pedigreegen"> <li> <a href="../../../ppl/f/8/d15f603c9034e759c0ac890918f.html">LAWSON, William<span class="grampsid"> [I10779]</span></a> <ol> <li class="spouse"> <a href="../../../ppl/0/8/d15f603c8b74e5fed8b1ad5f80.html">LUCAS, Adelaide<span class="grampsid"> [I10778]</span></a> <ol> <li> <a href="../../../ppl/8/3/d15f603c9312348dd5bc05c4d38.html">LAWSON, Alice Emily<span class="grampsid"> [I10780]</span></a> </li> <li> <a href="../../../ppl/1/7/d15f603c9a67c0aefb00341b271.html">LAWSON, George William<span class="grampsid"> [I10781]</span></a> </li> <li> <a href="../../../ppl/e/5/d15f603ca2c246079fb8eef625e.html">LAWSON, Bertha Beatrice<span class="grampsid"> [I10784]</span></a> </li> <li> <a href="../../../ppl/6/0/d15f603ca916c80619d7d9b7706.html">LAWSON, Harry Hatton<span class="grampsid"> [I10786]</span></a> </li> <li> <a href="../../../ppl/0/9/d15f603cad1cee2ac0f23a7490.html">LAWSON, Hubert Lucas<span class="grampsid"> [I10787]</span></a> </li> <li> <a href="../../../ppl/4/e/d15f603cb134d5bd1a0733a20e4.html">LAWSON, Ethel Henrietta<span class="grampsid"> [I10788]</span></a> </li> <li> <a href="../../../ppl/e/d/d15f603cb6117449b9ad6b48de.html">LAWSON, Harold Athol<span class="grampsid"> [I10789]</span></a> </li> <li> <a href="../../../ppl/0/2/d15f603cb9f1a218c780d708720.html">LAWSON, Emily Lucas<span class="grampsid"> [I10790]</span></a> </li> <li class="thisperson"> LAWSON, Adelaide Kate </li> </ol> </li> </ol> </li> </ol> </div> <div class="subsection" id="tree"> <h4>Ancestors</h4> <div id="treeContainer" style="width:735px; height:602px;"> <div class="boxbg female AncCol0" style="top: 269px; left: 6px;"> <a class="noThumb" href="../../../ppl/2/9/d15f603cbce7f07779628b52a92.html"> LAWSON, Adelaide Kate </a> </div> <div class="shadow" style="top: 274px; left: 10px;"></div> <div class="bvline" style="top: 301px; left: 165px; width: 15px"></div> <div class="gvline" style="top: 306px; left: 165px; width: 20px"></div> <div class="boxbg male AncCol1" style="top: 119px; left: 196px;"> <a class="noThumb" href="../../../ppl/f/8/d15f603c9034e759c0ac890918f.html"> LAWSON, William </a> </div> <div class="shadow" style="top: 124px; left: 200px;"></div> <div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div> <div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div> <div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div> <div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div> <div class="boxbg female AncCol1" style="top: 419px; left: 196px;"> <a class="noThumb" href="../../../ppl/0/8/d15f603c8b74e5fed8b1ad5f80.html"> LUCAS, Adelaide </a> </div> <div class="shadow" style="top: 424px; left: 200px;"></div> <div class="bvline" style="top: 451px; left: 180px; width: 15px;"></div> <div class="gvline" style="top: 456px; left: 185px; width: 20px;"></div> <div class="bhline" style="top: 301px; left: 180px; height: 150px;"></div> <div class="gvline" style="top: 306px; left: 185px; height: 150px;"></div> <div class="bvline" style="top: 451px; left: 355px; width: 15px"></div> <div class="gvline" style="top: 456px; left: 355px; width: 20px"></div> <div class="boxbg male AncCol2" style="top: 344px; left: 386px;"> <a class="noThumb" href="../../../ppl/b/c/d15f60113e257f63df1048230cb.html"> LUCAS, George </a> </div> <div class="shadow" style="top: 349px; left: 390px;"></div> <div class="bvline" style="top: 376px; left: 370px; width: 15px;"></div> <div class="gvline" style="top: 381px; left: 375px; width: 20px;"></div> <div class="bhline" style="top: 376px; left: 370px; height: 75px;"></div> <div class="gvline" style="top: 381px; left: 375px; height: 75px;"></div> <div class="bvline" style="top: 376px; left: 545px; width: 15px"></div> <div class="gvline" style="top: 381px; left: 545px; width: 20px"></div> <div class="boxbg male AncCol3" style="top: 307px; left: 576px;"> <a class="noThumb" href="../../../ppl/a/3/d15f5fb962f11f46775d411d23a.html"> LUCAS, Nathaniel </a> </div> <div class="shadow" style="top: 312px; left: 580px;"></div> <div class="bvline" style="top: 339px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 344px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 339px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 344px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol3" style="top: 381px; left: 576px;"> <a class="noThumb" href="../../../ppl/6/8/d15f5fb965a7bfcfae4d7c1e486.html"> GASCOYNE, Olivia </a> </div> <div class="shadow" style="top: 386px; left: 580px;"></div> <div class="bvline" style="top: 413px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 418px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 376px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 381px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol2" style="top: 494px; left: 386px;"> <a class="noThumb" href="../../../ppl/6/7/d15f5fe2e527676c66ae7aec176.html"> HODGETTS, Elizabeth </a> </div> <div class="shadow" style="top: 499px; left: 390px;"></div> <div class="bvline" style="top: 526px; left: 370px; width: 15px;"></div> <div class="gvline" style="top: 531px; left: 375px; width: 20px;"></div> <div class="bhline" style="top: 451px; left: 370px; height: 75px;"></div> <div class="gvline" style="top: 456px; left: 375px; height: 75px;"></div> <div class="bvline" style="top: 526px; left: 545px; width: 15px"></div> <div class="gvline" style="top: 531px; left: 545px; width: 20px"></div> <div class="boxbg male AncCol3" style="top: 457px; left: 576px;"> <a class="noThumb" href="../../../ppl/a/4/d15f5fb95dd145846dcccdda14a.html"> HODGETTS, Thomas </a> </div> <div class="shadow" style="top: 462px; left: 580px;"></div> <div class="bvline" style="top: 489px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 494px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 489px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 494px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol3" style="top: 531px; left: 576px;"> <a class="noThumb" href="../../../ppl/e/5/d15f5fb960476abfb804452155e.html"> LUCE, Harriet </a> </div> <div class="shadow" style="top: 536px; left: 580px;"></div> <div class="bvline" style="top: 563px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 568px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 526px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 531px; left: 565px; height: 37px;"></div> </div> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/8/d/d15f5fe05fb4f67e220976f79d8.html" title="Frank Lee: GEDCOM File : GeorgeLUCAS.ged" name ="sref1"> Frank Lee: GEDCOM File : GeorgeLUCAS.ged <span class="grampsid"> [S0301]</span> </a> <ol> <li id="sref1a"> <ul> <li> Confidence: Low </li> </ul> </li> </ol> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:51<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
Java
""" Contains format specification class and methods to parse it from JSON. .. codeauthor:: Tomas Krizek <tomas.krizek1@tul.cz> """ import json import re def get_root_input_type_from_json(data): """Return the root input type from JSON formatted string.""" return parse_format(json.loads(data)) def parse_format(data): """Returns root input type from data.""" input_types = {} data = data['ist_nodes'] root_id = data[0]['id'] # set root type for item in data: input_type = _get_input_type(item) if input_type is not None: input_types[input_type['id']] = input_type # register by id _substitute_ids_with_references(input_types) return input_types[root_id] SCALAR = ['Integer', 'Double', 'Bool', 'String', 'Selection', 'FileName'] def is_scalar(input_type): """Returns True if input_type is scalar.""" return input_type['base_type'] in SCALAR RE_PARAM = re.compile('^<([a-zA-Z][a-zA-Z0-9_]*)>$') def is_param(value): """Determine whether given value is a parameter string.""" if not isinstance(value, str): return False return RE_PARAM.match(value) def _substitute_ids_with_references(input_types): """Replaces ids or type names with python object references.""" input_type = {} def _substitute_implementations(): """Replaces implementation ids with input_types.""" impls = {} for id_ in input_type['implementations']: type_ = input_types[id_] impls[type_['name']] = type_ input_type['implementations'] = impls def _substitute_default_descendant(): """Replaces default descendant id with input_type.""" id_ = input_type.get('default_descendant', None) if id_ is not None: input_type['default_descendant'] = input_types[id_] def _substitute_key_type(): """Replaces key type with input_type.""" # pylint: disable=unused-variable, invalid-name for __, value in input_type['keys'].items(): value['type'] = input_types[value['type']] # pylint: disable=unused-variable, invalid-name for __, input_type in input_types.items(): if input_type['base_type'] == 'Array': input_type['subtype'] = input_types[input_type['subtype']] elif input_type['base_type'] == 'Abstract': _substitute_implementations() _substitute_default_descendant() elif input_type['base_type'] == 'Record': _substitute_key_type() def _get_input_type(data): """Returns the input_type data structure that defines an input type and its constraints for validation.""" if 'id' not in data or 'input_type' not in data: return None input_type = dict( id=data['id'], base_type=data['input_type'] ) input_type['name'] = data.get('name', '') input_type['full_name'] = data.get('full_name', '') input_type['description'] = data.get('description', '') input_type['attributes'] = data.get('attributes', {}) if input_type['base_type'] in ['Double', 'Integer']: input_type.update(_parse_range(data)) elif input_type['base_type'] == 'Array': input_type.update(_parse_range(data)) if input_type['min'] < 0: input_type['min'] = 0 input_type['subtype'] = data['subtype'] elif input_type['base_type'] == 'FileName': input_type['file_mode'] = data['file_mode'] elif input_type['base_type'] == 'Selection': input_type['values'] = _list_to_dict(data['values'], 'name') elif input_type['base_type'] == 'Record': input_type['keys'] = _list_to_dict(data['keys']) input_type['implements'] = data.get('implements', []) input_type['reducible_to_key'] = data.get('reducible_to_key', None) elif input_type['base_type'] == 'Abstract': input_type['implementations'] = data['implementations'] input_type['default_descendant'] = data.get('default_descendant', None) return input_type def _parse_range(data): """Parses the format range properties - min, max.""" input_type = {} try: input_type['min'] = data['range'][0] except (KeyError, TypeError): # set default value input_type['min'] = float('-inf') try: input_type['max'] = data['range'][1] except (KeyError, TypeError): # set default value input_type['max'] = float('inf') return input_type def _list_to_dict(list_, key_label='key'): """ Transforms a list of dictionaries into a dictionary of dictionaries. Original dictionaries are assigned key specified in each of them by key_label. """ dict_ = {} for item in list_: dict_[item[key_label]] = item return dict_
Java
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEditor; using System.IO; public class Serializer : MonoBehaviour { //save defaults are only used to set the data used when initializing that map the next time. string saveFile; string loadFile; string fileName; public string saveData; public string defaults; CharacterControllerScript player; // Use this for initialization void Start () { player = Globals.playerScript; //save on disc saveData = Path.Combine(Application.persistentDataPath, "SaveData"); // defaults included in project defaults = "Assets/Resources/Defaults/"; CreateDirectories(); } // Update is called once per frame void Update () { } void CreateDirectories() { if(!Directory.Exists(saveData)) { Directory.CreateDirectory(saveData); } /*if(!Directory.Exists(defaults)) { Directory.CreateDirectory(defaults); }*/ } public void SavePlayerData() { PlayerSaveData playerData = new PlayerSaveData() { level = player.level, statPoints = player.statPoints, skillPoints = player.skillPoints, spentStatPoints = player.spentStatPoints, spentSkillPoints = player.spentSkillPoints, currentHealth = player.currentHealth, maxHealth = player.maxHealth, currentXP = player.currentXP, xpToLevel = player.xpToLevel, atk = player.atk, atkItemBonus = player.atkItemBonus, statAtk = player.statAtk, def = player.def, defItemBonus = player.defItemBonus, statDef = player.statDef, skill1Lvl = player.skills[0].level, skill2Lvl = player.skills[1].level, skill3Lvl = player.skills[2].level, skill4Lvl = player.skills[3].level, lookingX = (int)player.looking.x, lookingY = (int)player.looking.y, direction = player.direction, bronzeKeys = player.bronzeKeys, silverKeys = player.silverKeys, goldKeys = player.goldKeys, currentMap = Globals.currentMap, redOrbState = player.redOrbState, blueOrbState = player.blueOrbState, storyProgress = player.storyProgress, sideQuests = new List<PlayerSaveData.PlayerQuests>() }; foreach(Quest q in player.quests) { PlayerSaveData.PlayerQuests quest = new PlayerSaveData.PlayerQuests(); quest.questName = q.questName; quest.description = q.description; quest.complete = q.complete; quest.progress = q.progress; playerData.sideQuests.Add(quest); } string json = JsonUtility.ToJson(playerData); string fileName = Path.Combine(saveData, "player.json"); if(File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); SavePlayerInventory(); //Debug.Log(json); Debug.Log(fileName); } public void SavePlayerInventory() { PlayerInventory playerInventory = new PlayerInventory(); try { foreach (InventoryItemBase i in player.inventory) { playerInventory.inventoryItems.Add(i); } } catch { Debug.Log("Empty Inventory"); } string json = JsonUtility.ToJson(playerInventory); string fileName = Path.Combine(saveData, "inventory.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } public void LoadPlayerInventory() { try { fileName = Path.Combine(saveData, "inventory.json"); loadFile = File.ReadAllText(fileName); PlayerInventory load = JsonUtility.FromJson<PlayerInventory>(loadFile); if (load.inventoryItems.Count > 0) { player.inventory.Clear(); foreach (InventoryItemBase i in load.inventoryItems) { player.inventory.Add(i); } } } catch { Debug.Log("Problem loading inventory"); } } public void LoadPlayerData() { fileName = Path.Combine(saveData, "player.json"); loadFile = File.ReadAllText(fileName); PlayerSaveData load = JsonUtility.FromJson<PlayerSaveData>(loadFile); //Debug.Log(load.level+ "" + load.statPoints+""+ load.skillPoints+ "" +load.currentMap); player.level = load.level; player.statPoints = load.statPoints; player.skillPoints = load.skillPoints; player.spentStatPoints = load.spentStatPoints; player.spentSkillPoints = load.spentSkillPoints; player.maxHealth = load.maxHealth; player.currentHealth = load.currentHealth; player.xpToLevel = load.xpToLevel; player.currentXP = load.currentXP; player.atk = load.atk; player.statAtk = load.statAtk; player.atkItemBonus = load.atkItemBonus; player.def = load.def; player.statDef = load.statDef; player.defItemBonus = load.defItemBonus; player.skills[0].level = load.skill1Lvl; player.skills[1].level = load.skill2Lvl; player.skills[2].level = load.skill3Lvl; player.skills[3].level = load.skill4Lvl; player.looking = new Vector2(load.lookingX, load.lookingY); player.direction = load.direction; player.bronzeKeys = load.bronzeKeys; player.silverKeys = load.silverKeys; player.goldKeys = load.goldKeys; player.redOrbState = load.redOrbState; player.blueOrbState = load.blueOrbState; player.storyProgress = load.storyProgress; //for (int x = 0; x < load.sideQuests.Count; x++) // { // Debug.Log(load.sideQuests[x].questName); // Debug.Log(load.sideQuests[x].description); // Debug.Log(load.sideQuests[x].complete); // Debug.Log(load.sideQuests[x].progress); // player.quests.Add(new Quest(load.sideQuests[x].questName, load.sideQuests[x].description, load.sideQuests[x].complete, load.sideQuests[0].progress)); //} foreach (PlayerSaveData.PlayerQuests q in load.sideQuests) { //Debug.Log(q.questName); //Debug.Log(q.description); //Debug.Log(q.complete); //Debug.Log(q.progress); player.quests.Add(new Quest(q.questName, q.description, q.complete, q.progress)); //Debug.Log(player.quests[0].questName); } LoadPlayerInventory(); } public string SavedFloor() { //used to load in saved floor fileName = Path.Combine(saveData, "player.json"); loadFile = File.ReadAllText(fileName); PlayerSaveData load = JsonUtility.FromJson<PlayerSaveData>(loadFile); return load.currentMap; } //public void SaveMap(int x, int y) //{ // MapSaveData mapData = new MapSaveData() // { // returnPointX = x, // returnPointY = y // }; // string json = JsonUtility.ToJson(mapData); // string fileName = Path.Combine(saveData, SceneManager.GetActiveScene().name + ".json"); // if (File.Exists(fileName)) // { // File.Delete(fileName); // } // File.WriteAllText(fileName, json); //} //public void LoadMap(string nextMap) //{ // fileName = Path.Combine(saveData, nextMap + ".json"); // loadFile = File.ReadAllText(fileName); // MapSaveData load = JsonUtility.FromJson<MapSaveData>(loadFile); // player.gameObject.transform.position = new Vector2(load.returnPointX + .5f, load.returnPointY-.5f); //} /*public void SaveEnemies() { try { EnemiesOnMap mapEnemies = new EnemiesOnMap { mapEnemyInfo = new List<EnemiesOnMap.EnemyInfo>() }; foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy")) { EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>(); EnemiesOnMap.EnemyInfo newInfo = new EnemiesOnMap.EnemyInfo(); { newInfo.enemyName = currentEnemy.enemyName.ToString(); newInfo.posX = (int)currentEnemy.transform.position.x; newInfo.posY = (int)currentEnemy.transform.position.y; newInfo.alive = currentEnemy.alive; newInfo.heldItem = currentEnemy.heldItem; } mapEnemies.mapEnemyInfo.Add(newInfo); } string json = JsonUtility.ToJson(mapEnemies); string fileName = Path.Combine(saveData, Globals.currentMap + "enemies.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Enemies here"); } } public void SaveEnemiesDefault() { try { EnemiesOnMap mapEnemies = new EnemiesOnMap { mapEnemyInfo = new List<EnemiesOnMap.EnemyInfo>() }; foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy")) { EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>(); EnemiesOnMap.EnemyInfo newInfo = new EnemiesOnMap.EnemyInfo(); { newInfo.enemyName = currentEnemy.enemyName.ToString(); newInfo.posX = (int)currentEnemy.transform.position.x; newInfo.posY = (int)currentEnemy.transform.position.y; newInfo.alive = currentEnemy.alive; newInfo.heldItem = currentEnemy.heldItem; } mapEnemies.mapEnemyInfo.Add(newInfo); Destroy(enemy); } string json = JsonUtility.ToJson(mapEnemies); string fileName = Path.Combine(defaults, Globals.currentMap + "defaultenemies.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Enemies here"); } } public void LoadEnemies() {try { StartCoroutine(LoadEnemiesDelay()); } catch { Debug.Log("No Enemies Loaded"); } } public IEnumerator LoadEnemiesDelay() { yield return new WaitForSeconds(.5f); if (File.Exists(Path.Combine(saveData, Globals.currentMap + "enemies.json"))) { fileName = Path.Combine(saveData, Globals.currentMap + "enemies.json"); } else { fileName = Path.Combine(defaults, Globals.currentMap + "defaultenemies.json"); } Debug.Log("loading enemies from " + fileName); loadFile = File.ReadAllText(fileName); EnemiesOnMap load = JsonUtility.FromJson<EnemiesOnMap>(loadFile); Container enemyContainer = GameObject.FindWithTag("Container").GetComponent<Container>(); //foreach (EnemiesOnMap.EnemyInfo info in load.mapEnemyInfo) //{ // //load into a list. // //enemyContainer.CreateEnemy(info.enemyName, info.posX, info.posY, info.alive); //} for(int x = load.mapEnemyInfo.Count -1; x>-1; x--) { //start new enemy //set its info to load[x] //create from container //clear entry from list EnemiesOnMap.EnemyInfo e = load.mapEnemyInfo[x]; enemyContainer.CreateEnemy(e.enemyName, e.posX, e.posY, e.alive,e.heldItem); load.mapEnemyInfo.RemoveAt(x); } yield return null; } public void SaveItems() { try { ItemsOnMap mapItems = new ItemsOnMap { mapItemInfo = new List<ItemsOnMap.ItemInfo>() }; foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item")) { ItemBase currentItem = item.GetComponent<ItemBase>(); ItemsOnMap.ItemInfo newInfo = new ItemsOnMap.ItemInfo(); { newInfo.itemName = currentItem.itemName.ToString(); newInfo.value = currentItem.value; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; //newInfo.active = currentItem.active; } mapItems.mapItemInfo.Add(newInfo); } string json = JsonUtility.ToJson(mapItems); string fileName = Path.Combine(saveData, Globals.currentMap + "items.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Items Here"); } } public void SaveItemsDefault() { try { ItemsOnMap mapItems = new ItemsOnMap { mapItemInfo = new List<ItemsOnMap.ItemInfo>() }; foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item")) { ItemBase currentItem = item.GetComponent<ItemBase>(); ItemsOnMap.ItemInfo newInfo = new ItemsOnMap.ItemInfo(); { newInfo.itemName = currentItem.itemName.ToString(); newInfo.value = currentItem.value; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; //newInfo.active = currentItem.active; } mapItems.mapItemInfo.Add(newInfo); Destroy(item); } string json = JsonUtility.ToJson(mapItems); string fileName = Path.Combine(defaults, Globals.currentMap + "defaultitems.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Items Here"); } } public void LoadItems() { try { StartCoroutine(LoadItemsDelay()); } catch { Debug.Log("No items loaded"); } } public IEnumerator LoadItemsDelay() { yield return new WaitForSeconds(.5f); if (File.Exists(Path.Combine(saveData, Globals.currentMap + "items.json"))) { fileName = Path.Combine(saveData, Globals.currentMap + "items.json"); } else { fileName = Path.Combine(defaults, Globals.currentMap + "defaultitems.json"); } Debug.Log("loading items from " + fileName); loadFile = File.ReadAllText(fileName); ItemsOnMap load = JsonUtility.FromJson<ItemsOnMap>(loadFile); Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>(); //foreach (ItemsOnMap.ItemInfo info in load.mapItemInfo) //{ // Debug.Log(info.itemName); // itemContainer.CreateItem(info.itemName, info.value, info.posX, info.posY, info.active); //} for (int x = load.mapItemInfo.Count - 1; x > -1; x--) { ItemsOnMap.ItemInfo i = load.mapItemInfo[x]; itemContainer.CreateItem(i.itemName,i.value, i.posX, i.posY); load.mapItemInfo.RemoveAt(x); } yield return null; } public void SaveDoors() { try { DoorsOnMap mapDoors = new DoorsOnMap { mapDoorInfo = new List<DoorsOnMap.DoorInfo>() }; foreach (GameObject item in GameObject.FindGameObjectsWithTag("Door")) { DoorBase currentItem = item.GetComponent<DoorBase>(); DoorsOnMap.DoorInfo newInfo = new DoorsOnMap.DoorInfo(); { newInfo.doorType = currentItem.doorType.ToString(); newInfo.doorName = currentItem.doorName; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; } mapDoors.mapDoorInfo.Add(newInfo); } string json = JsonUtility.ToJson(mapDoors); string fileName = Path.Combine(saveData, Globals.currentMap + "doors.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Doors Here"); } } public void SaveDoorsDefault() { try { DoorsOnMap mapDoors = new DoorsOnMap { mapDoorInfo = new List<DoorsOnMap.DoorInfo>() }; foreach (GameObject item in GameObject.FindGameObjectsWithTag("Door")) { DoorBase currentItem = item.GetComponent<DoorBase>(); DoorsOnMap.DoorInfo newInfo = new DoorsOnMap.DoorInfo(); { newInfo.doorType = currentItem.doorType.ToString(); newInfo.doorName = currentItem.doorName; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; } mapDoors.mapDoorInfo.Add(newInfo); Destroy(item); } string json = JsonUtility.ToJson(mapDoors); string fileName = Path.Combine(defaults, Globals.currentMap + "defaultdoors.json"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); } catch { Debug.Log("No Doors Here"); } } public void LoadDoors() { StartCoroutine(LoadDoorsDelay()); } public IEnumerator LoadDoorsDelay() { yield return new WaitForSeconds(.5f); try { if (File.Exists(Path.Combine(saveData, Globals.currentMap + "doors.json"))) { fileName = Path.Combine(saveData, Globals.currentMap + "doors.json"); } else { fileName = Path.Combine(defaults, Globals.currentMap + "defaultdoors.json"); } Debug.Log("loading doors from " + fileName); loadFile = File.ReadAllText(fileName); DoorsOnMap load = JsonUtility.FromJson<DoorsOnMap>(loadFile); Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>(); //foreach (DoorsOnMap.DoorInfo info in load.mapDoorInfo) //{ // itemContainer.CreateDoor(info.doorType, info.posX, info.posY); //} try { for (int x = load.mapDoorInfo.Count - 1; x > -1; x--) { DoorsOnMap.DoorInfo d = load.mapDoorInfo[x]; itemContainer.CreateDoor(d.doorType, d.doorName, d.posX, d.posY); load.mapDoorInfo.RemoveAt(x); } } catch { for (int x = load.mapDoorInfo.Count - 1; x > -1; x--) { DoorsOnMap.DoorInfo d = load.mapDoorInfo[x]; itemContainer.CreateDoor(d.doorType, d.posX, d.posY); load.mapDoorInfo.RemoveAt(x); } } } catch { } yield return null; }*/ public void SaveMapData(bool d) { //true = default; false = other fileName = ""; MapData mapData = new MapData { mapDoorInfo = new List<MapData.Door>(), mapEnemyInfo = new List<MapData.Enemy>(), mapItemInfo = new List<MapData.Item>(), mapBinaryObjectInfo = new List<MapData.BinaryObject>() }; //Save Doors try { foreach (GameObject door in GameObject.FindGameObjectsWithTag("Door")) { DoorBase currentItem = door.GetComponent<DoorBase>(); MapData.Door newInfo = new MapData.Door(); { //newInfo.doorType = currentItem.doorType.ToString(); newInfo.doorName = currentItem.doorName; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; } mapData.mapDoorInfo.Add(newInfo); Destroy(door); } } catch { Debug.Log("problem saving doors"); } //Save Items try { foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item")) { ItemBase currentItem = item.GetComponent<ItemBase>(); MapData.Item newInfo = new MapData.Item(); { newInfo.itemName = currentItem.itemName.ToString(); newInfo.value = currentItem.value; newInfo.posX = (int)currentItem.transform.position.x; newInfo.posY = (int)currentItem.transform.position.y; //newInfo.active = currentItem.active; } mapData.mapItemInfo.Add(newInfo); Destroy(item); } } catch { Debug.Log("problem saving items"); } //Save Enemies try { foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy")) { EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>(); MapData.Enemy newInfo = new MapData.Enemy(); { newInfo.enemyName = currentEnemy.enemyName.ToString(); newInfo.posX = (int)currentEnemy.transform.position.x; newInfo.posY = (int)currentEnemy.transform.position.y; newInfo.alive = currentEnemy.alive; newInfo.heldItem = currentEnemy.heldItem; } mapData.mapEnemyInfo.Add(newInfo); Destroy(enemy); } } catch { Debug.Log("problem saving enemies"); } //Save BinaryItems try { foreach(GameObject binary in GameObject.FindGameObjectsWithTag("Button")) { BinaryObject currentObject = binary.GetComponent<BinaryObject>(); MapData.BinaryObject newObject = new MapData.BinaryObject(); { newObject.objectName = currentObject.objectName.ToString(); newObject.buttonState = currentObject.buttonState; newObject.objectState = currentObject.objectState; newObject.buttonX = (int)currentObject.transform.position.x; newObject.buttonY = (int)currentObject.transform.position.y; newObject.objectX = currentObject.objectLocationX; newObject.objectY = currentObject.objectLocationY; newObject.canToggle = currentObject.canToggle; } } } catch { //nothing to save } string json = JsonUtility.ToJson(mapData); if(d == true) { fileName = Path.Combine(defaults, Globals.currentMap + ".json"); Debug.Log(d); } else { fileName = Path.Combine(saveData, Globals.currentMap + ".json"); Debug.Log(d); } if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, json); Debug.Log("save complete" + fileName); } public IEnumerator LoadMapData() { yield return new WaitForSeconds(.5f); Debug.Log("loading map data"); try { if (File.Exists(Path.Combine(saveData, Globals.currentMap + ".json"))) { fileName = Path.Combine(saveData, Globals.currentMap + ".json"); } else { fileName = Path.Combine(defaults, Globals.currentMap + ".json"); } Debug.Log("loading from " + fileName); loadFile = File.ReadAllText(fileName); MapData load = JsonUtility.FromJson<MapData>(loadFile); Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>(); try { for (int x = load.mapDoorInfo.Count - 1; x > -1; x--) { MapData.Door d = load.mapDoorInfo[x]; itemContainer.CreateDoor(d.doorName, d.posX, d.posY); load.mapDoorInfo.RemoveAt(x); } } catch { Debug.Log("problem loading doors"); } try { for (int x = load.mapItemInfo.Count - 1; x > -1; x--) { MapData.Item i = load.mapItemInfo[x]; itemContainer.CreateItem(i.itemName, i.value, i.posX, i.posY); load.mapItemInfo.RemoveAt(x); } } catch { } try { for (int x = load.mapEnemyInfo.Count - 1; x > -1; x--) { MapData.Enemy e = load.mapEnemyInfo[x]; itemContainer.CreateEnemy(e.enemyName, e.posX, e.posY,e.alive,e.heldItem); load.mapEnemyInfo.RemoveAt(x); } } catch { } try { for (int x = load.mapBinaryObjectInfo.Count - 1; x > -1; x--) { MapData.BinaryObject o = load.mapBinaryObjectInfo[x]; itemContainer.CreateBinaryObject(o.objectName, o.buttonState, o.objectState, o.buttonX, o.buttonY, o.objectX, o.objectY, o.canToggle); load.mapBinaryObjectInfo.RemoveAt(x); } } catch { } } catch { } yield return null; } }
Java
package grid; import java.util.Comparator; import world.World; /* * AP(r) Computer Science GridWorld Case Study: * Copyright(c) 2002-2006 College Entrance Examination Board * (http://www.collegeboard.com). * * This code is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation. * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Alyce Brady * @author Chris Nevison * @author APCS Development Committee * @author Cay Horstmann */ /** * A <code>Location</code> object represents the row and column of a location * in a two-dimensional grid. <br /> * The API of this class is testable on the AP CS A and AB exams. */ public class Location implements Comparable { private int row; // row location in grid private int col; // column location in grid /** * The turn angle for turning 90 degrees to the left. */ public static final int LEFT = -90; /** * The turn angle for turning 90 degrees to the right. */ public static final int RIGHT = 90; /** * The turn angle for turning 45 degrees to the left. */ public static final int HALF_LEFT = -45; /** * The turn angle for turning 45 degrees to the right. */ public static final int HALF_RIGHT = 45; /** * The turn angle for turning a full circle. */ public static final int FULL_CIRCLE = 360; /** * The turn angle for turning a half circle. */ public static final int HALF_CIRCLE = 180; /** * The turn angle for making no turn. */ public static final int AHEAD = 0; /** * The compass direction for north. */ public static final int NORTH = 0; /** * The compass direction for northeast. */ public static final int NORTHEAST = 45; /** * The compass direction for east. */ public static final int EAST = 90; /** * The compass direction for southeast. */ public static final int SOUTHEAST = 135; /** * The compass direction for south. */ public static final int SOUTH = 180; /** * The compass direction for southwest. */ public static final int SOUTHWEST = 225; /** * The compass direction for west. */ public static final int WEST = 270; /** * The compass direction for northwest. */ public static final int NORTHWEST = 315; /** * Constructs a location with given row and column coordinates. * @param r the row * @param c the column */ public Location(int r, int c) { row = r; col = c; } /** * Gets the row coordinate. * @return the row of this location */ public int getRow() { return row; } /** * Gets the column coordinate. * @return the column of this location */ public int getCol() { return col; } /** * Gets the adjacent location in any one of the eight compass directions. * @param direction the direction in which to find a neighbor location * @return the adjacent location in the direction that is closest to * <tt>direction</tt> */ public Location getAdjacentLocation(int direction) { // reduce mod 360 and round to closest multiple of 45 int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE; if (adjustedDirection < 0) adjustedDirection += FULL_CIRCLE; adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT; int dc = 0; int dr = 0; if (adjustedDirection == EAST) dc = 1; else if (adjustedDirection == SOUTHEAST) { dc = 1; dr = 1; } else if (adjustedDirection == SOUTH) dr = 1; else if (adjustedDirection == SOUTHWEST) { dc = -1; dr = 1; } else if (adjustedDirection == WEST) dc = -1; else if (adjustedDirection == NORTHWEST) { dc = -1; dr = -1; } else if (adjustedDirection == NORTH) dr = -1; else if (adjustedDirection == NORTHEAST) { dc = 1; dr = -1; } return new Location(getRow() + dr, getCol() + dc); } /** * Returns the direction from this location toward another location. The * direction is rounded to the nearest compass direction. * @param target a location that is different from this location * @return the closest compass direction from this location toward * <code>target</code> */ public int getDirectionToward(Location target) { int dx = target.getCol() - getCol(); int dy = target.getRow() - getRow(); // y axis points opposite to mathematical orientation int angle = (int) Math.toDegrees(Math.atan2(-dy, dx)); // mathematical angle is counterclockwise from x-axis, // compass angle is clockwise from y-axis int compassAngle = RIGHT - angle; // prepare for truncating division by 45 degrees compassAngle += HALF_RIGHT / 2; // wrap negative angles if (compassAngle < 0) compassAngle += FULL_CIRCLE; // round to nearest multiple of 45 return (compassAngle / HALF_RIGHT) * HALF_RIGHT; } /** * Indicates whether some other <code>Location</code> object is "equal to" * this one. * @param other the other location to test * @return <code>true</code> if <code>other</code> is a * <code>Location</code> with the same row and column as this location; * <code>false</code> otherwise */ public boolean equals(Object other) { if (!(other instanceof Location)) return false; Location otherLoc = (Location) other; return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol(); } /** * Generates a hash code. * @return a hash code for this location */ public int hashCode() { return getRow() * 3737 + getCol(); } /** * Compares this location to <code>other</code> for ordering. Returns a * negative integer, zero, or a positive integer as this location is less * than, equal to, or greater than <code>other</code>. Locations are * ordered in row-major order. <br /> * (Precondition: <code>other</code> is a <code>Location</code> object.) * @param other the other location to test * @return a negative integer if this location is less than * <code>other</code>, zero if the two locations are equal, or a positive * integer if this location is greater than <code>other</code> */ public int compareTo(Object other) { Location otherLoc = (Location) other; if (getRow() < otherLoc.getRow()) return -1; if (getRow() > otherLoc.getRow()) return 1; if (getCol() < otherLoc.getCol()) return -1; if (getCol() > otherLoc.getCol()) return 1; return 0; } /** * (Added for RatBots) Calculates the distance to another location. * The distance is reported as the sum of the x and y distances * and therefore doesn't consider diagonal movement. * @param other the location that the distance is calculated to * @return the distance */ public int distanceTo(Location other) { int dx = Math.abs(row - other.getRow()); int dy = Math.abs(col - other.getCol()); return dx+dy; } public boolean isValidLocation() { if(this.getRow() < 0 || this.getRow() >= World.DEFAULT_ROWS) return false; if(this.getCol() < 0 || this.getCol() >= World.DEFAULT_COLS) return false; return true; } /** * Creates a string that describes this location. * @return a string with the row and column of this location, in the format * (row, col) */ public String toString() { return "(r:" + getRow() + ", c:" + getCol() + ")"; } }
Java
/* This file is part of LiveCG. * * Copyright (C) 2013 Sebastian Kuerten * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.topobyte.livecg.ui.geometryeditor.preferences; import java.awt.Component; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.plaf.basic.BasicComboBoxRenderer; import de.topobyte.livecg.preferences.Configuration; public class LAFSelector extends JComboBox { private static final long serialVersionUID = 6856865390726849784L; public LAFSelector(Configuration configuration) { super(buildValues()); setRenderer(new Renderer()); setEditable(false); String lookAndFeel = configuration.getSelectedLookAndFeel(); setSelectedIndex(-1); for (int i = 0; i < getModel().getSize(); i++) { LookAndFeelInfo info = (LookAndFeelInfo) getModel().getElementAt(i); if (info.getClassName().equals(lookAndFeel)) { setSelectedIndex(i); break; } } } private static LookAndFeelInfo[] buildValues() { LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels(); return lafs; } private class Renderer extends BasicComboBoxRenderer { private static final long serialVersionUID = 1L; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { LookAndFeelInfo item = (LookAndFeelInfo) value; setText(item.getName()); } else { setText("default"); } return this; } } }
Java
$DBversion = 'XXX'; # will be replaced by the RM if( CheckVersion( $DBversion ) ) { $dbh->do(" CREATE TABLE action_logs_cache ( action_id int(11) NOT NULL auto_increment, timestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, user int(11) NOT NULL default 0, module text, action text, object int(11) default NULL, info text, interface VARCHAR(30) DEFAULT NULL, PRIMARY KEY (action_id), KEY timestamp_idx (timestamp), KEY user_idx (user), KEY module_idx (module(255)), KEY action_idx (action(255)), KEY object_idx (object), KEY info_idx (info(255)), KEY interface (interface) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; "); # Always end with this (adjust the bug info) SetVersion( $DBversion ); print "Upgrade to $DBversion done (KD 2990 - MongoDB datawarehouse for storing the logging data.)\n"; }
Java
package com.yoavst.quickapps.calendar; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.CalendarContract; import android.provider.CalendarContract.Events; import com.yoavst.quickapps.Preferences_; import com.yoavst.quickapps.R; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.TimeZone; import static android.provider.CalendarContract.Events.ALL_DAY; import static android.provider.CalendarContract.Events.DISPLAY_COLOR; import static android.provider.CalendarContract.Events.DTEND; import static android.provider.CalendarContract.Events.DTSTART; import static android.provider.CalendarContract.Events.DURATION; import static android.provider.CalendarContract.Events.EVENT_LOCATION; import static android.provider.CalendarContract.Events.RRULE; import static android.provider.CalendarContract.Events.TITLE; import static android.provider.CalendarContract.Events._ID; /** * Created by Yoav. */ public class CalendarUtil { private CalendarUtil() { } private static final SimpleDateFormat dayFormatter = new SimpleDateFormat( "EEE, MMM d, yyyy"); private static final SimpleDateFormat dateFormatter = new SimpleDateFormat( "EEE, MMM d, HH:mm"); private static final SimpleDateFormat hourFormatter = new SimpleDateFormat("HH:mm"); private static final SimpleDateFormat fullDateFormat = new SimpleDateFormat("EEE, MMM d"); private static final SimpleDateFormat otherDayFormatter = new SimpleDateFormat("MMM d, HH:mm"); private static final TimeZone timezone = Calendar.getInstance().getTimeZone(); public static ArrayList<Event> getCalendarEvents(Context context) { CalendarResources.init(context); boolean showRepeating = new Preferences_(context).showRepeatingEvents().get(); ArrayList<Event> events = new ArrayList<>(); String selection = "((" + DTSTART + " >= ?) OR (" + DTEND + " >= ?))"; String milli = String.valueOf(System.currentTimeMillis()); String[] selectionArgs = new String[]{milli, milli}; Cursor cursor = context.getContentResolver() .query( Events.CONTENT_URI, new String[]{_ID, TITLE, DTSTART, DTEND, EVENT_LOCATION, ALL_DAY, DISPLAY_COLOR, RRULE, DURATION}, selection, selectionArgs, null ); cursor.moveToFirst(); int count = cursor.getCount(); if (count != 0) { //<editor-fold desc="Future Events"> for (int i = 0; i < count; i++) { int id = cursor.getInt(0); String title = cursor.getString(1); long startDate = Long.parseLong(cursor.getString(2)); String endDateString = cursor.getString(3); String location = cursor.getString(4); boolean isAllDay = cursor.getInt(5) != 0; int color = cursor.getInt(6); String rRule = cursor.getString(7); String duration = cursor.getString(8); if (!isAllDay) { // If the event not repeat itself - regular event if (rRule == null) { long endDate = endDateString == null || endDateString.equals("null") ? 0 : Long.parseLong(endDateString); if (endDate == 0) events.add(new Event(id, title, dayFormatter.format(new Date(startDate - timezone.getOffset(startDate))), location).setColor(color)); else events.add(new Event(id, title, startDate, endDate, location).setColor(color)); } else if (showRepeating) { // Event that repeat itself events = addEvents(events, getEventFromRepeating(context, rRule, startDate, duration, location, color, title, id, false)); } } else { if (rRule == null) { // One day event probably if (endDateString == null || Long.parseLong(endDateString) == 0) events.add(new Event(id, title, dayFormatter.format(new Date(startDate - timezone.getOffset(startDate))), location).setColor(color)); else if (showRepeating) { int offset = timezone.getOffset(startDate); long newTime = startDate - offset; long endTime = Long.parseLong(endDateString) - offset; events.add(new Event(id, title, newTime, endTime, location, true).setColor(color)); } } else if (showRepeating) { // Repeat all day event, god why?!? events = addEvents(events, getEventFromRepeating(context, rRule, startDate - timezone.getOffset(startDate), duration, location, color, title, id, true)); } } cursor.moveToNext(); } //</editor-fold> } cursor.close(); if (showRepeating) { String repeatingSections = "((" + DURATION + " IS NOT NULL) AND (" + RRULE + " IS NOT NULL) AND ((" + DTSTART + " < ?) OR (" + DTEND + " < ?)))"; Cursor repeatingCursor = context.getContentResolver() .query( Events.CONTENT_URI, new String[]{_ID, TITLE, DTSTART, EVENT_LOCATION, ALL_DAY, DISPLAY_COLOR, RRULE, DURATION}, repeatingSections, selectionArgs, null ); repeatingCursor.moveToFirst(); int repeatingCount = repeatingCursor.getCount(); if (repeatingCount != 0) { //<editor-fold desc="repeating past Events"> for (int i = 0; i < repeatingCount; i++) { int id = repeatingCursor.getInt(0); String title = repeatingCursor.getString(1); long startDate = Long.parseLong(repeatingCursor.getString(2)); String location = repeatingCursor.getString(3); boolean isAllDay = repeatingCursor.getInt(4) != 0; int color = repeatingCursor.getInt(5); String rRule = repeatingCursor.getString(6); String duration = repeatingCursor.getString(7); if (!isAllDay) { ArrayList<Event> repeatingEvents = getEventFromRepeating(context, rRule, startDate, duration, location, color, title, id, false); events = addEvents(events, repeatingEvents); } else { ArrayList<Event> repeatingEvents = getEventFromRepeating(context, rRule, startDate - timezone.getOffset(startDate), duration, location, color, title, id, true); events = addEvents(events, repeatingEvents); } repeatingCursor.moveToNext(); } //</editor-fold> repeatingCursor.close(); } } Collections.sort(events, new Comparator<Event>() { @Override //an integer < 0 if lhs is less than rhs, 0 if they are equal, and > 0 if lhs is greater than rhs. public int compare(Event lhs, Event rhs) { int first = (lhs.getStartDate() - rhs.getStartDate()) < 0 ? -1 : lhs.getStartDate() == rhs.getStartDate() ? 0 : 1; int second = (lhs.getEndDate() - rhs.getEndDate()) < 0 ? -1 : lhs.getEndDate() == rhs.getEndDate() ? 0 : 1; return first != 0 ? first : second; } }); return events; } private static ArrayList<Event> addEvents(ArrayList<Event> list, ArrayList<Event> toAdd) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 6); long milli = DateUtils.clearTime(calendar).getTimeInMillis(); long now = System.currentTimeMillis(); for (Event event : toAdd) { if (event.getEndDate() <= milli && event.getEndDate() >= now) list.add(event); } return list; } private static ArrayList<Event> getEventFromRepeating(Context context, String rRule, long startDate, String duration, String location, int color, String title, int id, boolean isAllDay) { ArrayList<Event> events = new ArrayList<>(); final String[] INSTANCE_PROJECTION = new String[]{ CalendarContract.Instances.EVENT_ID, // 0 CalendarContract.Instances.BEGIN, // 1 CalendarContract.Instances.END // 2 }; Calendar endTime = Calendar.getInstance(); endTime.add(Calendar.MONTH, 6); String selection = CalendarContract.Instances.EVENT_ID + " = ?"; Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, System.currentTimeMillis()); ContentUris.appendId(builder, endTime.getTimeInMillis()); Cursor cursor = context.getContentResolver().query(builder.build(), INSTANCE_PROJECTION, selection, new String[]{Integer.toString(id)}, null); if (cursor.moveToFirst()) { do { events.add(new Event(id, title, cursor.getLong(1) - (isAllDay ? timezone.getOffset(startDate) : 0), cursor.getLong(2) - (isAllDay ? timezone.getOffset(startDate) : 0), location, isAllDay).setColor(color)); } while (cursor.moveToNext()); } return events; } public static String getDateFromEvent(Event event) { if (event.getDate() != null) return event.getDate(); else if (event.isAllDay()) { Calendar startPlusOneDay = Calendar.getInstance(); startPlusOneDay.setTimeInMillis(event.getStartDate()); startPlusOneDay.add(Calendar.DAY_OF_YEAR, 1); Calendar endTime = Calendar.getInstance(); endTime.setTimeInMillis(event.getEndDate()); if (DateUtils.isSameDay(startPlusOneDay, endTime)) { startPlusOneDay.add(Calendar.DAY_OF_YEAR, -1); if (DateUtils.isToday(startPlusOneDay)) return CalendarResources.today + " " + CalendarResources.allDay; else if (DateUtils.isTomorrow(startPlusOneDay)) return CalendarResources.tomorrow + " " + CalendarResources.allDay; return dayFormatter.format(new Date(event.getStartDate())); } else { endTime.add(Calendar.DAY_OF_YEAR, -1); startPlusOneDay.add(Calendar.DAY_OF_YEAR, -1); if (DateUtils.isToday(startPlusOneDay)) { if (DateUtils.isTomorrow(endTime)) return CalendarResources.today + " - " + CalendarResources.tomorrow; else return CalendarResources.today + " " + CalendarResources.allDay + " - " + fullDateFormat.format(endTime.getTime()); } else if (DateUtils.isTomorrow(startPlusOneDay)) return CalendarResources.tomorrow + " - " + fullDateFormat.format(endTime.getTime()); return fullDateFormat.format(new Date(event.getStartDate())) + " - " + fullDateFormat.format(endTime.getTime()); } } else { String text; Date first = new Date(event.getStartDate()); Date end = new Date(event.getEndDate()); if (DateUtils.isSameDay(first, end)) { if (DateUtils.isToday(first)) text = CalendarResources.today + " " + hourFormatter.format(first) + " - " + hourFormatter.format(end); else if (DateUtils.isWithinDaysFuture(first, 1)) text = CalendarResources.tomorrow + " " + hourFormatter.format(first) + " - " + hourFormatter.format(end); else text = dateFormatter.format(first) + " - " + hourFormatter.format(end); } else if (DateUtils.isToday(first)) { text = CalendarResources.today + hourFormatter.format(first) + " - " + otherDayFormatter.format(end); } else { text = otherDayFormatter.format(first) + " - " + otherDayFormatter.format(end); } return text; } } public static Intent launchEventById(long id) { Intent intent = new Intent(Intent.ACTION_VIEW); Uri.Builder uri = Events.CONTENT_URI.buildUpon(); uri.appendPath(Long.toString(id)); intent.setData(uri.build()); return intent; } public static String getTimeToEvent(Event event) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(event.getStartDate()); Calendar now = Calendar.getInstance(); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); if (calendar.getTimeInMillis() <= now.getTimeInMillis()) return CalendarResources.now; else { long secondsLeft = (calendar.getTimeInMillis() - now.getTimeInMillis()) / 1000; if (secondsLeft < 60) return CalendarResources.in + " 1 " + CalendarResources.minute; long minutesLeft = secondsLeft / 60; if (minutesLeft < 60) return CalendarResources.in + " " + minutesLeft + " " + (minutesLeft > 1 ? CalendarResources.minutes : CalendarResources.minute); long hoursLeft = minutesLeft / 50; if (hoursLeft < 24) return CalendarResources.in + " " + hoursLeft + " " + (hoursLeft > 1 ? CalendarResources.hours : CalendarResources.hour); int days = (int) (hoursLeft / 24); if (days < 30) return CalendarResources.in + " " + days + " " + (days > 1 ? CalendarResources.days : CalendarResources.day); int months = days / 30; if (months < 12) return CalendarResources.in + " " + months + " " + (months > 1 ? CalendarResources.months : CalendarResources.month); else return CalendarResources.moreThenAYearLeft; } } public static class CalendarResources { public static String today; public static String tomorrow; public static String allDay; public static String now; public static String in; public static String minute; public static String minutes; public static String hour; public static String hours; public static String day; public static String days; public static String week; public static String weeks; public static String month; public static String months; public static String moreThenAYearLeft; public static void init(Context context) { if (today == null || moreThenAYearLeft == null) { today = context.getString(R.string.today); tomorrow = context.getString(R.string.tomorrow); allDay = context.getString(R.string.all_day); now = context.getString(R.string.now); in = context.getString(R.string.in); String[] min = context.getString(R.string.minute_s).split("/"); minute = min[0]; minutes = min[1]; String[] hoursArray = context.getString(R.string.hour_s).split("/"); hour = hoursArray[0]; hours = hoursArray[1]; String[] dayArray = context.getString(R.string.day_s).split("/"); day = dayArray[0]; days = dayArray[1]; String[] weekArray = context.getString(R.string.week_s).split("/"); week = weekArray[0]; weeks = weekArray[1]; String[] monthArray = context.getString(R.string.month_s).split("/"); month = monthArray[0]; months = monthArray[1]; moreThenAYearLeft = context.getString(R.string.more_then_year); } } } }
Java
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("3. Get Minion Names")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("3. Get Minion Names")] [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bc91e659-ee53-4238-ab47-d6f903948cb6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Java
#=============================================================================== # Filename: rgss.rb # # Developer: Raku (rakudayo@gmail.com) # # Description: This is the core file to include to enable loading and dumping # of RMXP's .rxdata files. #=============================================================================== require_relative 'rgss_internal' require_relative 'rgss_rpg' require_relative 'rgss_mod'
Java
/* * Copyright (c) 2018 Siloft * * 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. */ #ifndef BUNDLE_H_ #define BUNDLE_H_ int bundle(int argc, char *argv[], int command_index); #endif // BUNDLE_H_
Java
local render2d = ... or _G.render2d do local X, Y, W, H = 0,0 function render2d.SetScissor(x, y, w, h) X = x Y = y W = w or render.GetWidth() H = h or render.GetHeight() if not x then X = 0 Y = 0 render.SetScissor() else x, y = render2d.ScreenToWorld(-x, -y) render.SetScissor(-x, -y, w, h) end end function render2d.GetScissor() return X, Y, W, H end utility.MakePushPopFunction(render2d, "Scissor") end do function render2d.SetStencilState(tbl) if tbl.function_ then end end --[[ local function stencil_pass(func, ref) if func == "never" then return false end if func == "equal" then return pixel == ref end end local stencil_pass = stencil_pass(func, ref) local depth_pass = depth_pass() if depth_pass and stencil_pass then elseif not depth_pass and stencil_pass then elseif not stencil_pass then if op == "incr" then pixel = pixel + ref end end 1: 000000000 -- clear 2: 000111110 -- draw stencil rect 2: 000112210 -- draw stencil rect 2: 000111110 -- draw stencil rect ]] local i = 0 local X,Y,W,H function render2d.PushStencilRect(x,y,w,h, i_override) render.StencilFunction("never", 1) render.StencilOperation("increase", "keep", "zero") render2d.PushTexture() render.SetColorMask(0,0,0,0) render2d.DrawRect(x,y,w,h) render.SetColorMask(1,1,1,1) render2d.PopTexture() render.StencilFunction("equal", i) i = i + 1 X,Y,W,H = x,y,w,h end function render2d.PopStencilRect() render.StencilFunction("never", 1) render.StencilOperation("decrease", "keep", "zero") render2d.PushTexture() render.SetColorMask(0,0,0,0) render2d.DrawRect(X,Y,W,H) render.SetColorMask(1,1,1,1) render2d.PopTexture() if i >= 4 then i = 0 end end local i = 0 local X,Y,W,H function render2d.PushStencilRect2(x,y,w,h, i_override) render.StencilFunction("never", 1) render.StencilOperation("increase", "keep", "zero") render2d.PushTexture() render2d.DrawRect(x,y,w,h) render2d.PopTexture() render.StencilFunction("equal", i) i = i + 1 X,Y,W,H = x,y,w,h end function render2d.PopStencilRect2() render.StencilFunction("never", 1) render.StencilOperation("decrease", "keep", "zero") render2d.PushTexture() render2d.DrawRect(X,Y,W,H) render2d.PopTexture() if i >= 4 then i = 0 end end end do local X, Y, W, H function render2d.EnableClipRect(x, y, w, h, i) i = i or 1 render.SetStencil(true) render.GetFrameBuffer():ClearStencil(0) -- out = 0 render.StencilOperation("keep", "replace", "replace") -- if true then stencil = 33 return true end render.StencilFunction("always", i) -- on fail, keep zero value -- on success replace it with 33 -- write to the stencil buffer -- on fail is probably never reached render2d.PushTexture() render.SetColorMask(0,0,0,0) render2d.DrawRect(x, y, w, h) render.SetColorMask(1,1,1,1) render2d.PopTexture() -- if stencil == 33 then stencil = 33 return true else return false end render.StencilFunction("equal", i) X = x Y = y W = w H = h end function render2d.GetClipRect() return X or 0, Y or 0, W or render.GetWidth(), H or render.GetHeight() end function render2d.DisableClipRect() render.SetStencil(false) end end
Java
package uk.tim740.skUtilities.util; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import org.bukkit.event.Event; import uk.tim740.skUtilities.skUtilities; import javax.annotation.Nullable; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; /** * Created by tim740 on 11/09/2016 */ public class ExprTimeInTimeZone extends SimpleExpression<String> { private Expression<String> str; @Override @Nullable protected String[] get(Event e) { String s = str.getSingle(e); String[] sl = new String[0]; try { BufferedReader br = new BufferedReader(new FileReader(new File("plugins/Skript/config.sk").getAbsoluteFile())); sl = br.lines().toArray(String[]::new); br.close(); } catch (Exception x) { skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x); } String sf = ""; for (String aSl : sl) { if (aSl.contains("date format: ")) { sf = aSl.replaceFirst("date format: ", ""); } } String ff; if (sf.equalsIgnoreCase("default")) { ff = new SimpleDateFormat().toPattern(); } else { ff = sf; } return new String[]{ZonedDateTime.ofInstant(Instant.now(), ZoneId.of(s)).format(DateTimeFormatter.ofPattern(ff))}; } @SuppressWarnings("unchecked") @Override public boolean init(Expression<?>[] e, int i, Kleenean k, SkriptParser.ParseResult p) { str = (Expression<String>) e[0]; return true; } @Override public Class<? extends String> getReturnType() { return String.class; } @Override public boolean isSingle() { return true; } @Override public String toString(@Nullable Event e, boolean b) { return getClass().getName(); } }
Java
-- Erase all reading notes for this VMeasurementID CREATE OR REPLACE FUNCTION cpgdb.ClearReadingNotes( tblVMeasurement.VMeasurementID%TYPE -- the vmeasurement to tie this to ) RETURNS integer AS $_$ DECLARE _VMID ALIAS FOR $1; VMOp text; ret integer; BEGIN -- Get the VMeasurementOp SELECT op.name INTO VMOp FROM tblVMeasurement INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID) WHERE vmeasurementID=_VMID; IF NOT FOUND THEN RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID; END IF; -- Just delete all the notes! IF VMOp = 'Direct' THEN DELETE FROM tblReadingReadingNote WHERE ReadingID IN (SELECT readingID FROM tblVMeasurement INNER JOIN tblMeasurement USING (measurementID) INNER JOIN tblReading USING (measurementID) INNER JOIN tblReadingReadingNote USING (readingID) WHERE VMeasurementID=_VMID); ELSE DELETE FROM tblVMeasurementRelYearReadingNote WHERE VMeasurementID=_VMID; END IF; GET DIAGNOSTICS ret = ROW_COUNT; RETURN ret; END; $_$ LANGUAGE PLPGSQL VOLATILE; -- Add a reading note to this vmeasurement CREATE OR REPLACE FUNCTION cpgdb.AddReadingNote( tblVMeasurement.VMeasurementID%TYPE, -- the vmeasurement to tie this to int, -- The year to bind this note to (relative, starts at zero) int, -- The reading note ID to add boolean) -- Is this a force disabled override (only for non-direct, MUST BE NULL for direct) RETURNS void AS $_$ DECLARE _VMID ALIAS FOR $1; _RelYear ALIAS FOR $2; _ReadingNoteID ALIAS FOR $3; _Override ALIAS FOR $4; VMOp text; myReadingID tblReading.ReadingID%TYPE; myOverride boolean; VMReadingCount int; BEGIN -- Get the VMeasurementOp SELECT op.name INTO VMOp FROM tblVMeasurement INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID) WHERE vmeasurementID=_VMID; IF NOT FOUND THEN RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID; END IF; -- Direct VM -> Attach to Reading IF VMOp = 'Direct' THEN IF _Override IS NOT NULL THEN RAISE EXCEPTION 'Override must not be set for Direct VMs'; END IF; SELECT readingID INTO myReadingID FROM tblVMeasurement INNER JOIN tblMeasurement USING (measurementID) INNER JOIN tblReading USING (measurementID) WHERE VMeasurementID=_VMID AND RelYear=_RelYear; IF NOT FOUND THEN RAISE EXCEPTION 'No reading found for relyear % on vmeasurementid %. Year must exist.', _RelYear, _VMID; END IF; INSERT INTO tblReadingReadingNote (ReadingID, ReadingNoteID) VALUES (myReadingID, _ReadingNoteID); ELSE -- Derived VM -> Attach to vmeasurement myOverride := _Override; -- null override means false IF myOverride IS NULL THEN myOverride := FALSE; END IF; -- Validate relyear SELECT readingCount INTO VMReadingCount FROM tblVMeasurementMetaCache WHERE VMeasurementID=_VMID; IF NOT FOUND OR VMReadingCount <= _RelYear THEN RAISE EXCEPTION 'VMeasurement % does not exist, is malformed, or relyear % is out of range.', _VMID, _RelYear; END IF; INSERT INTO tblVMeasurementRelYearReadingNote (VMeasurementID, RelYear, ReadingNoteID, DisabledOverride) VALUES (_VMID, _RelYear, _ReadingNoteID, myOverride); END IF; END; $_$ LANGUAGE PLPGSQL VOLATILE; -- Add a CUSTOM reading note to this vmeasurement -- Tries to find an existing match first CREATE OR REPLACE FUNCTION cpgdb.AddCustomReadingNote( tblVMeasurement.VMeasurementID%TYPE, -- the vmeasurement to tie this to int, -- The year to bind this note to (relative, starts at zero) text) -- The custom reading note to add RETURNS tlkpReadingNote AS $_$ DECLARE _VMID ALIAS FOR $1; _RelYear ALIAS FOR $2; _NoteText ALIAS FOR $3; VMOp text; myReadingID tblReading.ReadingID%TYPE; myOverride boolean; VMReadingCount int; myReadingNoteID tlkpReadingNote.ReadingNoteID%TYPE; myVMRYRN tblVMeasurementRelYearReadingNote.RelYearReadingNoteID%TYPE; outrow tlkpReadingNote%ROWTYPE; BEGIN -- Look for existing vocabulary case insensitively SELECT ReadingNoteID INTO myReadingNoteID FROM tlkpReadingNote WHERE note ILIKE _NoteText; IF FOUND THEN PERFORM cpgdb.AddReadingNote(_VMID, _RelYear, myReadingNoteID, null); SELECT * INTO outrow FROM tlkpReadingNote WHERE ReadingNoteID=myReadingNoteID; RETURN outrow; END IF; -- Get the VMeasurementOp SELECT op.name INTO VMOp FROM tblVMeasurement INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID) WHERE vmeasurementID=_VMID; IF NOT FOUND THEN RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID; END IF; -- Create a new reading note myReadingNoteID := nextval('tlkpreadingnote_readingnoteid_seq'::regclass); -- Direct VM -> Attach to Reading IF VMOp = 'Direct' THEN IF _Override IS NOT NULL THEN RAISE EXCEPTION 'Override must not be set for Direct VMs'; END IF; SELECT readingID INTO myReadingID FROM tblVMeasurement INNER JOIN tblMeasurement USING (measurementID) INNER JOIN tblReading USING (measurementID) WHERE VMeasurementID=_VMID AND RelYear=_RelYear; IF NOT FOUND THEN RAISE EXCEPTION 'No reading found for relyear % on vmeasurementid %. Year must exist.', _RelYear, _VMID; END IF; INSERT INTO tlkpReadingNote(ReadingNoteID, note, vocabularyid, parentReadingID) VALUES (myReadingNoteID, _NoteText, 0, myReadingID); INSERT INTO tblReadingReadingNote (ReadingReadingNoteID, ReadingID, ReadingNoteID) VALUES (myRRNID, myReadingID, _ReadingNoteID); ELSE -- Validate relyear SELECT readingCount INTO VMReadingCount FROM tblVMeasurementMetaCache WHERE VMeasurementID=_VMID; IF NOT FOUND OR VMReadingCount <= _RelYear THEN RAISE EXCEPTION 'VMeasurement % does not exist, is malformed, or relyear % is out of range.', _VMID, _RelYear; END IF; -- Complicated circular reference here :< -- First, insert the new readingNote INSERT INTO tlkpReadingNote(ReadingNoteID, note, vocabularyid) VALUES (myReadingNoteID, _NoteText, 0); -- Now, insert a new tblVMeasurementRelYearReadingNote row myVMRYRN := nextval('tblvmeasurementrelyearreadingnote_relyearreadingnoteid_seq'::regclass); INSERT INTO tblVMeasurementRelYearReadingNote (RelYearReadingNoteID, VMeasurementID, RelYear, ReadingNoteID) VALUES (myVMRYRN, _VMID, _RelYear, myReadingNoteID); -- Now, tie the readingNote directly to the new row UPDATE tlkpReadingNote SET parentVMRelYearReadingNoteID=myVMRYRN WHERE ReadingNoteID=myReadingNoteID; END IF; SELECT * INTO outrow FROM tlkpReadingNote WHERE ReadingNoteID=myReadingNoteID; RETURN outrow; END; $_$ LANGUAGE PLPGSQL VOLATILE; -- Remove a reading note from this vmeasurement CREATE OR REPLACE FUNCTION cpgdb.RemoveReadingNote( tblVMeasurement.VMeasurementID%TYPE, -- the vmeasurement to tie this to int, -- The year to bind this note to (relative, starts at zero) int) -- The reading note ID to add RETURNS integer AS $_$ DECLARE _VMID ALIAS FOR $1; _RelYear ALIAS FOR $2; _ReadingNoteID ALIAS FOR $3; VMOp text; myReadingID tblReading.ReadingID%TYPE; ret integer; BEGIN -- Get the VMeasurementOp SELECT op.name INTO VMOp FROM tblVMeasurement INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID) WHERE vmeasurementID=_VMID; IF NOT FOUND THEN RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID; END IF; -- Direct VM -> Remove from Reading IF VMOp = 'Direct' THEN SELECT readingID INTO myReadingID FROM tblVMeasurement INNER JOIN tblMeasurement USING (measurementID) INNER JOIN tblReading USING (measurementID) WHERE VMeasurementID=_VMID AND RelYear=_RelYear; IF NOT FOUND THEN RAISE EXCEPTION 'No reading found for relyear % on vmeasurementid %. Year must exist.', _RelYear, _VMID; END IF; DELETE FROM tblReadingReadingNote WHERE ReadingID=myReadingID AND ReadingNoteID=_ReadingNoteID; ELSE -- Remove from RelYearReadingNote DELETE FROM tblVMeasurementRelYearReadingNote WHERE VMeasurementID=_VMID AND RelYear=_RelYear AND ReadingNoteID=_ReadingNoteID; END IF; GET DIAGNOSTICS ret = ROW_COUNT; RETURN ret; END; $_$ LANGUAGE PLPGSQL VOLATILE; -- Param 1: Vocabulary name -- Param 2: Note text CREATE OR REPLACE FUNCTION cpgdb.GetNote(text, text) RETURNS tlkpReadingNote AS $_$ DECLARE noterec tlkpReadingNote; BEGIN SELECT rnote.* INTO noterec FROM tlkpReadingNote rnote LEFT JOIN tlkpVocabulary voc USING (vocabularyid) WHERE voc.name=$1 AND rnote.note=$2; IF NOT FOUND THEN RAISE EXCEPTION 'Note "%" not found for vocabulary "%"', $2, $1; END IF; RETURN noterec; END; $_$ LANGUAGE PLPGSQL STABLE;
Java
""" Page view class """ import os from Server.Importer import ImportFromModule class PageView(ImportFromModule("Server.PageViewBase", "PageViewBase")): """ Page view class. """ _PAGE_TITLE = "Python Web Framework" def __init__(self, htmlToLoad): """ Constructor. - htmlToLoad : HTML to load """ self.SetPageTitle(self._PAGE_TITLE) self.AddMetaData("charset=\"UTF-8\"") self.AddMetaData("name=\"viewport\" content=\"width=device-width, initial-scale=1\"") self.AddStyleSheet("/css/styles.css") self.AddJavaScript("/js/http.js") self.LoadHtml(os.path.join(os.path.dirname(__file__), "%s.html" % htmlToLoad)) self.SetPageData({ "PageTitle" : self._PAGE_TITLE })
Java
/* * Copyright (C) 2010 The UAPI Authors * You may not use this file except in compliance with the License. * You may obtain a copy of the License at the LICENSE file. * * You must gained the permission from the authors if you want to * use the project into a commercial product */ package uapi.service; import uapi.InvalidArgumentException; import uapi.helper.ArgumentChecker; import java.util.HashMap; import java.util.Map; /** * Define response code */ public abstract class ResponseCode { private final Map<String, String> _codeMsgKeyMapping = new HashMap<>(); private final MessageExtractor _msgExtractor = new MessageExtractor(this.getClass().getClassLoader()); public void init() { getMessageLoader().registerExtractor(this._msgExtractor); } protected abstract MessageLoader getMessageLoader(); public String getMessageKey(final String code) { ArgumentChecker.required(code, "code"); return this._codeMsgKeyMapping.get("code"); } protected void addCodeMessageKeyMapping(String code, String messageKey) { ArgumentChecker.required(code, "code"); ArgumentChecker.required(messageKey, "messageKey"); if (this._codeMsgKeyMapping.containsKey(code)) { throw new InvalidArgumentException("Overwrite existing code message key is not allowed - {}", code); } this._codeMsgKeyMapping.put(code, messageKey); this._msgExtractor.addDefinedKeys(messageKey); } }
Java
<?php namespace SHC\Event; //Imports use RWF\Date\DateTime; use RWF\Util\StringUtils; use SHC\Condition\Condition; use SHC\Condition\ConditionEditor; use SHC\Core\SHC; use SHC\Switchable\Switchable; use SHC\Switchable\SwitchableEditor; /** * Ereignise Verwalten * * @author Oliver Kleditzsch * @copyright Copyright (c) 2014, Oliver Kleditzsch * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @since 2.0.0-0 * @version 2.0.0-0 */ class EventEditor { /** * Ereignis Luftfeuchte steigt * * @var Integer */ const EVENT_HUMIDITY_CLIMB = 1; /** * Ereignis Luftfeuchte faellt * * @var Integer */ const EVENT_HUMIDITY_FALLS = 2; /** * Ereignis Eingang wechselt von LOW auf HIGH * * @var Integer */ const EVENT_INPUT_HIGH = 4; /** * Ereignis EIngang wechselt von HIGH auf LOW * * @var Integer */ const EVENT_INPUT_LOW = 8; /** * Ereignis Lichtstaerke steigt * * @var Integer */ const EVENT_LIGHTINTENSITY_CLIMB = 16; /** * Ereignis Lichtsaerke faellt * * @var Integer */ const EVENT_LIGHTINTENSITY_FALLS = 32; /** * Ereignis Feuchtigkeit steigt * * @var Integer */ const EVENT_MOISTURE_CLIMB = 64; /** * Ereignis Feuchtigkeit steigt * * @var Integer */ const EVENT_MOISTURE_FALLS = 128; /** * Ereignis Temperatur steigt * * @var Integer */ const EVENT_TEMPERATURE_CLIMB = 256; /** * Ereignis Temperatur faellt * * @var Integer */ const EVENT_TEMPERATURE_FALLS = 512; /** * Ereignis Benutzer kommt nach Hause * * @var Integer */ const EVENT_USER_COMES_HOME = 1024; /** * Ereignis Benutzer verlaesst das Haus * * @var Integer */ const EVENT_USER_LEAVE_HOME = 2048; /** * Ereignis Sonnenaufgang * * @var Integer */ const EVENT_SUNRISE = 4096; /** * Ereignis Sonnenuntergang * * @var Integer */ const EVENT_SUNSET = 8192; /** * Ereignis Datei erstellt * * @var Integer */ const EVENT_FILE_CREATE = 16384; /** * Ereignis Datei geloescht * * @var Integer */ const EVENT_FILE_DELETE = 32768; /** * nach ID sortieren * * @var String */ const SORT_BY_ID = 'id'; /** * nach Namen sortieren * * @var String */ const SORT_BY_NAME = 'name'; /** * nicht sortieren * * @var String */ const SORT_NOTHING = 'unsorted'; /** * Ereignisse * * @var Array */ protected $events = array(); /** * Singleton Instanz * * @var \SHC\Event\EventEditor */ protected static $instance = null; /** * name der HashMap * * @var String */ protected static $tableName = 'shc:events'; protected function __construct() { $this->loadData(); } /** * laedt die Ereignisse aus den XML Daten und erzeugt die Objekte */ public function loadData() { //Daten Vorbereiten $oldEvents = $this->events; $this->events = array(); $events = SHC::getDatabase()->hGetAllArray(self::$tableName); //Daten einlesen foreach ($events as $event) { //Variablen Vorbereiten $class = (string) $event['class']; $data = array(); foreach ($event as $index => $value) { if (!in_array($index, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) { $data[$index] = $value; } } /* @var $eventObj \SHC\Event\Event */ $eventObj = new $class( (int) $event['id'], (string) $event['name'], $data, ((int) $event['enabled'] == true ? true : false), DateTime::createFromDatabaseDateTime((string) $event['lastExecute']) ); //Bedingungen anhaengen foreach ($event['conditions'] as $conditionId) { $condition = ConditionEditor::getInstance()->getConditionByID($conditionId); if ($condition instanceof Condition) { $eventObj->addCondition($condition); } } //schaltbare Elemente Hinzufuegen if(isset($event['switchable'])) { foreach ($event['switchable'] as $switchable) { $switchableObject = SwitchableEditor::getInstance()->getElementById((int) $switchable['id']); if ($switchableObject instanceof Switchable) { $eventObj->addSwitchable($switchableObject, (int) $switchable['command']); } } } //Objekt status vom alten Objekt ins neue übertragen if(isset($oldEvents[(int) $event['id']])) { /* @var $eventObj \SHC\Event\Event */ $eventObj->setState($oldEvents[(int) $event['id']]->getState()); if($oldEvents[(int) $event['id']]->getTime() instanceof DateTime) { $eventObj->setTime($oldEvents[(int) $event['id']]->getTime()); } } $this->events[(int) $event['id']] = $eventObj; } } /** * gibt das Ereignis mit der IOD zurueck * * @param int $id Ereignis ID * @return \SHC\Event\Event */ public function getEventById($id) { if (isset($this->events[$id])) { return $this->events[$id]; } return null; } /** * prueft ob der Name des Events schon verwendet wird * * @param String $name Name * @return Boolean */ public function isEventNameAvailable($name) { foreach ($this->events as $event) { /* @var $condition \SHC\Event\Event */ if (StringUtils::toLower($event->getName()) == StringUtils::toLower($name)) { return false; } } return true; } /** * gibt eine Liste mit allen Bedingungen zurueck * * @param String $orderBy Art der Sortierung ( * id => nach ID sorieren, * name => nach Namen sortieren, * unsorted => unsortiert * ) * @return Array */ public function listEvents($orderBy = 'id') { if ($orderBy == 'id') { //nach ID sortieren $events = $this->events; ksort($events, SORT_NUMERIC); return $events; } elseif ($orderBy == 'name') { //nach Namen sortieren $events = $this->events; //Sortierfunktion $orderFunction = function($a, $b) { if ($a->getName() == $b->getName()) { return 0; } if ($a->getName() < $b->getName()) { return -1; } return 1; }; usort($events, $orderFunction); return $events; } return $this->events; } /** * erstellt ein Event * * @param String $class Klassenname * @param String $name Name * @param Boolean $enabled Aktiv * @param Array $data Zusatzdaten * @param Array $conditions Liste der Bedingunen * @return Boolean * @throws \Exception */ protected function addEvent($class, $name, array $data = array(), $enabled = true, array $conditions) { //Ausnahme wenn Name des Events schon belegt if (!$this->isEventNameAvailable($name)) { throw new \Exception('Der Name des Events ist schon vergeben', 1502); } $db = SHC::getDatabase(); $index = $db->autoIncrement(self::$tableName); $newEvent = array( 'id' => $index, 'class' => $class, 'name' => $name, 'enabled' => ($enabled == true ? true : false), 'conditions' => $conditions, 'lastExecute' => '2000-01-01 00:00:00', 'switchable' => array() ); foreach ($data as $tag => $value) { if (!in_array($tag, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) { $newEvent[$tag] = $value; } } if($db->hSetNxArray(self::$tableName, $index, $newEvent) == 0) { return false; } return true; } /** * bearbeitet ein Event * * @param Integer $id ID * @param String $name Name * @param Array $data Zusatzdaten * @param Boolean $enabled Aktiv * @param Array $conditions Liste der Bedingunen * @return Boolean * @throws \Exception */ protected function editEvent($id, $name = null, array $data = null, $enabled = null, array $conditions = null) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $id)) { $event = $db->hGetArray(self::$tableName, $id); //Name if ($name !== null) { //Ausnahme wenn Name der Bedingung schon belegt if ((string) $event['name'] != $name && !$this->isEventNameAvailable($name)) { throw new \Exception('Der Name der Bedingung ist schon vergeben', 1502); } $event['name'] = $name; } //Aktiv if ($enabled !== null) { $event['enabled'] = ($enabled == true ? 1 : 0); } //Bedingungen if($conditions !== null) { $event['conditions'] = implode(',', $conditions); } //Zusatzdaten foreach($data as $tag => $value) { if (!in_array($tag, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) { if($value !== null) { $event[$tag] = $value; } } } if($db->hSetArray(self::$tableName, $id, $event) == 0) { return true; } } return false; } /** * Speichert den Zeitpunkt der letzten Ausfuehrung fuer ein Ereignis * * @param Integer $id Ereignis ID * @param \RWF\Date\DateTime $lastExecute letzte Ausfuehrung * @return Boolean */ public function updateLastExecute($id, DateTime $lastExecute) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $id)) { $event = $db->hGetArray(self::$tableName, $id); if(isset($event['id']) && $event['id'] == $id) { $event['lastExecute'] = $lastExecute->getDatabaseDateTime(); if($db->hSetArray(self::$tableName, $id, $event) == 0) { return true; } } else { //Datensatz nicht mehr vorhanden return false; } } return false; } /** * erstellt ein Luftfeuchte Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addHumidityClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\HumidityClimbOver', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Luftfeuchte Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editHumidityClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Luftfeuchte Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addHumidityFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\HumidityFallsBelow', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Luftfeuchte Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editHumidityFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Lichtstaerke Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addLightIntensityClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\LightIntensityClimbOver', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Lichtstaerke Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editLightIntensityClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Lichtstaerke Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addLightIntensityFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\LightIntensityFallsBelow', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Lichtstaerke Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editLightIntensityFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Feuchtigkeits Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addMoistureClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\MoistureClimbOver', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Feuchtigkeits Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editMoistureClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Feuchtigkeits Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addMoistureFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\MoistureFallsBelow', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Feuchtigkeits Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert (Prozent) * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editMoistureFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Temperatur Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addTemperatureClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\TemperatureClimbOver', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Temperatur Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editTemperatureClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Temperatur Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addTemperatureFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\TemperatureFallsBelow', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Temperatur Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $sensors Sensoren * @param Float $limit Grenzwert * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editTemperatureFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'sensors' => implode(',', $sensors), 'limit' => $limit, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Eingangsevent * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $inputs Eingaenge * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addInputHighEvent($name, $enabled, array $inputs, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'inputs' => implode(',', $inputs), 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\InputHigh', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Eingangsevent * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $inputs Eingaenge * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editInputHighEvent($id, $name = null, $enabled = null, array $inputs = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'inputs' => implode(',', $inputs), 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Eingangsevent * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $inputs Eingaenge * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addInputLowEvent($name, $enabled, array $inputs, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'inputs' => implode(',', $inputs), 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\InputLow', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Eingangsevent * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $inputs Eingaenge * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editInputLowEvent($id, $name = null, $enabled = null, array $inputs = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'inputs' => implode(',', $inputs), 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Benutzerevent * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $users benutzer zu Hause * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addUserComesHomeEvent($name, $enabled, array $users, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'users' => implode(',', $users), 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\UserComesHome', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Benutzerevent * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $users benutzer zu Hause * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editUserComesHomeEvent($id, $name = null, $enabled = null, array $users = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'users' => implode(',', $users), 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Benutzerevent * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $users benutzer zu Hause * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addUserLeavesHomeEvent($name, $enabled, array $users, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'users' => implode(',', $users), 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\UserLeavesHome', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Benutzerevent * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $users benutzer zu Hause * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editUserLeavesHomeEvent($id, $name = null, $enabled = null, array $users = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'users' => implode(',', $users), 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein neuen Event Sonnenaufgang * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $conditions Liste der Bedingunen */ public function addSunriseEvent($name, $enabled, array $conditions = null) { //Speichern return $this->addEvent('\SHC\Event\Events\Sunrise', $name, array(), $enabled, $conditions); } /** * bearbeitet ein Event Sonnenaufgang * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $conditions Liste der Bedingunen */ public function editSunriseEvent($id, $name = null, $enabled = null, array $conditions = null) { //Speichern return $this->editEvent($id, $name, array(), $enabled, $conditions); } /** * erstellt ein neuen Event Sonnenuntergang * * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $conditions Liste der Bedingunen */ public function addSunsetEvent($name, $enabled, array $conditions = null) { //Speichern return $this->addEvent('\SHC\Event\Events\Sunset', $name, array(), $enabled, $conditions); } /** * bearbeitet ein Event Sonnenuntergang * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param Array $conditions Liste der Bedingunen */ public function editSunsetEvent($id, $name = null, $enabled = null, array $conditions = null) { //Speichern return $this->editEvent($id, $name, array(), $enabled, $conditions); } /** * erstellt ein Datei erstellt Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param String $file Datei * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addFileCreateEvent($name, $enabled, $file, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'file' => $file, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\FileCreate', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Datei erstellt Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param String $file Datei * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editFileCreateEvent($id, $name = null, $enabled = null, $file = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'file' => $file, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * erstellt ein Datei geloescht Event * * @param String $name Name * @param Boolean $enabled Aktiviert * @param String $file Datei * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function addFileDeleteEvent($name, $enabled, $file, $interval, array $conditions = array()) { //Daten vorbereiten $data = array( 'file' => $file, 'interval' => $interval ); //Speichern return $this->addEvent('\SHC\Event\Events\FileDelete', $name, $data, $enabled, $conditions); } /** * bearbeitet ein Datei geloescht Event * * @param Integer $id ID * @param String $name Name * @param Boolean $enabled Aktiviert * @param String $file Datei * @param Integer $interval Sperrzeit * @param Array $conditions Liste der Bedingunen * @return bool */ public function editFileDeleteEvent($id, $name = null, $enabled = null, $file = null, $interval = null, array $conditions = null) { //Daten vorbereiten $data = array( 'file' => $file, 'interval' => $interval ); //Speichern return $this->editEvent($id, $name, $data, $enabled, $conditions); } /** * loascht ein Event * * @param Integer $id ID * @return Boolean */ public function removeEvent($id) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $id)) { if($db->hDel(self::$tableName, $id)) { return true; } } return false; } /** * fuegt einem Event eine Bedingung hinzu * * @param Integer $eventId ID des Events * @param Integer $conditionId ID der Bedingung * @return Boolean */ public function addConditionToEvent($eventId, $conditionId) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $eventId)) { $event = $db->hGetArray(self::$tableName, $eventId); $event['conditions'][] = $conditionId; if($db->hSetArray(self::$tableName, $eventId, $event) == 0) { return true; } } return false; } /** * entfernt eine Bedingung aus einem Event * * @param Integer $eventId ID des Events * @param Integer $conditionId ID der Bedingung * @return Boolean */ public function removeConditionFromEvent($eventId, $conditionId) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $eventId)) { $event = $db->hGetArray(self::$tableName, $eventId); $event['conditions'] = array_diff($event['conditions'], array($conditionId)); if($db->hSetArray(self::$tableName, $eventId, $event) == 0) { return true; } } return false; } /** * fuegt einem Event ein Schaltbares Element hinzu * * @param Integer $eventId ID des Events * @param Integer $switchableId ID des Schaltbaren Elements * @param Integer $command Befehl * @return Boolean */ public function addSwitchableToEvent($eventId, $switchableId, $command) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $eventId)) { $event = $db->hGetArray(self::$tableName, $eventId); $event['switchable'][] = array('id' => $switchableId, 'command' => $command); if($db->hSetArray(self::$tableName, $eventId, $event) == 0) { return true; } } return false; } /** * setzt den Befehl eines Schaltbaren Elements in einem Event * * @param Integer $eventId ID des Events * @param Integer $switchableId ID des Schaltbaren Elements * @param Integer $command Befehl * @return Boolean */ public function setEventSwitchableCommand($eventId, $switchableId, $command) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $eventId)) { $event = $db->hGetArray(self::$tableName, $eventId); foreach($event['switchable'] as $index => $switchable) { if($switchable['id'] == $switchableId) { $event['switchable'][$index]['command'] = $command; break; } } if($db->hSetArray(self::$tableName, $eventId, $event) == 0) { return true; } } return false; } /** * entfernt ein Schaltbares Element von einem Event * * @param Integer $eventId ID des Events * @param Integer $switchableId ID des Schaltbaren Elements * @return Boolean */ public function removeSwitchableFromEvent($eventId, $switchableId) { $db = SHC::getDatabase(); //pruefen ob Datensatz existiert if($db->hExists(self::$tableName, $eventId)) { $event = $db->hGetArray(self::$tableName, $eventId); foreach($event['switchable'] as $index => $switchable) { if($switchable['id'] == $switchableId) { unset($event['switchable'][$index]); break; } } if($db->hSetArray(self::$tableName, $eventId, $event) == 0) { return true; } } return false; } /** * geschuetzt wegen Singleton */ private function __clone() { } /** * gibt den Ereignis Editor Editor zurueck * * @return \SHC\Event\EventEditor */ public static function getInstance() { if (self::$instance === null) { self::$instance = new EventEditor(); } return self::$instance; } }
Java
/* * jQuery JavaScript Library v1.10.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-30T21:49Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-27 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function() { return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied if the test fails * @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler */ function addHandle( attrs, handler, test ) { attrs = attrs.split("|"); var current, i = attrs.length, setHandle = test ? null : handler; while ( i-- ) { // Don't override a user's handler if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) { Expr.attrHandle[ attrs[i] ] = setHandle; } } } /** * Fetches boolean attributes by node * @param {Element} elem * @param {String} name */ function boolHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents var val = elem.getAttributeNode( name ); return val && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } /** * Fetches attributes without interpolation * http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx * @param {Element} elem * @param {String} name */ function interpolationHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } /** * Uses defaultValue to retrieve value in IE6/7 * @param {Element} elem * @param {String} name */ function valueHandler( elem ) { // Ignore the value *property* on inputs by using defaultValue // Fallback to Sizzle.attr by returning undefined where appropriate // XML does not need to be checked as this will not be assigned for XML documents if ( elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns Returns -1 if a precedes b, 1 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.parentWindow; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 if ( parent && parent.frameElement ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { // Support: IE<8 // Prevent attribute/property "interpolation" div.innerHTML = "<a href='#'></a>"; addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" ); // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies addHandle( booleans, boolHandler, div.getAttribute("disabled") == null ); div.className = "i"; return !div.getAttribute("className"); }); // Support: IE<9 // Retrieving value should defer to defaultValue support.input = assert(function( div ) { div.innerHTML = "<input>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }); // IE6/7 still return empty string for value, // but are actually retrieving the property addHandle( "value", valueHandler, support.attributes && support.input ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( doc.createElement("div") ) & 1; }); // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined ); return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Initialize against the default document setDocument(); // Support: Chrome<<14 // Always assume duplicates if they aren't passed to the comparison function [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
Java
#include <iostream> using namespace std; #define FLOAT(name, value) float name = value #define CONST_FLOAT(name, value) const FLOAT(name, value) #define VAR_FLOAT(name) FLOAT(name, 0) #define VAR_INT(name) int name = 0 #define DEFINE_LINEAR_EQUATION(n)\ VAR_FLOAT(a##n);\ VAR_FLOAT(b##n);\ VAR_FLOAT(c##n)\ #define READ(input) cin >> input #define IS_LESS_THAN_EPSILON(diff) ((diff < EPSILON) && (diff > -EPSILON)) #define READ_LINEAR_EQUATION(n)\ READ(a##n);\ READ(b##n);\ READ(c##n)\ #define IS_ZERO(value) IS_LESS_THAN_EPSILON(value) #define IS_NOT_ZERO(value) (!IS_LESS_THAN_EPSILON(value)) #define IS_NOT_ZERO_LINE(line) (IS_NOT_ZERO(a##line) || IS_NOT_ZERO(b##line) || IS_NOT_ZERO(c##line)) #define SOLUTION_PART_1(n, divisor) c##n / divisor##n #define SOLUTION_PART_2(n, multiplier, found, divisor) (c##n - (multiplier##n * found)) / divisor##n #define ONE_SOLUTION() solution = One #define NO_SOLUTION() solution = No #define GAUSE(n1, n2, n3, cnt , calc)\ CONST_FLOAT(k##n1, (-cnt##n2) / cnt##n1);\ CONST_FLOAT(calc##n3, (calc##n1 * k##n1) + calc##n2);\ CONST_FLOAT(c##n3, (c##n1 * k##n1) + c##n2)\ #define IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(zero, first, second, divisor1, divisor2, n1, n2)\ if(IS_ZERO(zero) && (solution == Many)) {\ if IS_ZERO(divisor1##n1) {\ NO_SOLUTION();\ } else {\ first = SOLUTION_PART_1(n1, divisor1);\ second = SOLUTION_PART_2(n2, divisor1, first, divisor2);\ ONE_SOLUTION();\ }\ }\ #define FIND_SOLUTION(n, first, second, k, divisor1, divisor2)\ CONST_FLOAT(first##n, SOLUTION_PART_1(k, divisor1));\ CONST_FLOAT(second##n, SOLUTION_PART_2(n, divisor1, first##n, divisor2))\ #define DIFF(F, f) CONST_FLOAT(DIFF_##F, f##1 - f##2) #define PRINT(value) cout << value #define PRINT_CASE(what, message)\ case what:\ PRINT(message);\ break\ #define IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(a, b, m)\ if((absWholePart >= a) && (absWholePart < b)) {\ multiplier = m;\ }\ #define FORMAT(num)\ sign = (num <= -EPSILON ? -1 : 1);\ wholePart = num + (sign * EPSILON);\ multiplier = 1;\ absWholePart = sign * wholePart;\ IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(0, 10, 10000)\ IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(10, 100, 1000)\ IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(100, 1000, 100)\ IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(1000, 10000, 10)\ floatPart = (int)((num + (sign * EPSILON)) * multiplier) - (wholePart * multiplier);\ num = ((float)floatPart / multiplier) + wholePart\ /* @begin */ enum Solution { No, One, Many }; CONST_FLOAT(EPSILON, 0.00001); int main() { DEFINE_LINEAR_EQUATION(1); DEFINE_LINEAR_EQUATION(2); VAR_FLOAT(x); VAR_FLOAT(y); Solution solution = Many; READ_LINEAR_EQUATION(1); READ_LINEAR_EQUATION(2); if(IS_NOT_ZERO_LINE(1) && IS_NOT_ZERO_LINE(2)) { IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(a1, y, x, b, a, 1, 2) IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(a2, y, x, b, a, 2, 1) IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(b1, x, y, a, b, 1, 2) IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(b2, x, y, a, b, 2, 1) if(solution == Many) { GAUSE(1, 2, 3, a, b); GAUSE(2, 1, 4, b, a); if((IS_ZERO(b3) && IS_NOT_ZERO(c3)) || (IS_ZERO(a4) && IS_NOT_ZERO(c4))) { NO_SOLUTION(); } else { FIND_SOLUTION(1, y, x, 3, b, a); FIND_SOLUTION(2, x, y, 4, a, b); DIFF(X, x); DIFF(Y, y); if(IS_LESS_THAN_EPSILON(DIFF_X) && IS_LESS_THAN_EPSILON(DIFF_Y)) { x = x1; y = y1; ONE_SOLUTION(); } } } } switch(solution) { PRINT_CASE(No, "No solution"); PRINT_CASE(Many, "Many solutions"); case One: VAR_INT(sign); VAR_INT(wholePart); VAR_INT(absWholePart); VAR_INT(floatPart); VAR_INT(multiplier); FORMAT(x); FORMAT(y); PRINT(x) << ' ' << y; break; } PRINT('\n'); return 0; }
Java
/** * Copyright (C) 2011 Whisper Systems * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.smssecure.smssecure.recipients; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import org.smssecure.smssecure.contacts.avatars.ContactPhotoFactory; import org.smssecure.smssecure.database.CanonicalAddressDatabase; import org.smssecure.smssecure.util.Util; import org.whispersystems.libaxolotl.util.guava.Optional; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; public class RecipientFactory { private static final RecipientProvider provider = new RecipientProvider(); public static Recipients getRecipientsForIds(Context context, String recipientIds, boolean asynchronous) { if (TextUtils.isEmpty(recipientIds)) return new Recipients(); return getRecipientsForIds(context, Util.split(recipientIds, " "), asynchronous); } public static Recipients getRecipientsFor(Context context, List<Recipient> recipients, boolean asynchronous) { long[] ids = new long[recipients.size()]; int i = 0; for (Recipient recipient : recipients) { ids[i++] = recipient.getRecipientId(); } return provider.getRecipients(context, ids, asynchronous); } public static Recipients getRecipientsFor(Context context, Recipient recipient, boolean asynchronous) { long[] ids = new long[1]; ids[0] = recipient.getRecipientId(); return provider.getRecipients(context, ids, asynchronous); } public static Recipient getRecipientForId(Context context, long recipientId, boolean asynchronous) { return provider.getRecipient(context, recipientId, asynchronous); } public static Recipients getRecipientsForIds(Context context, long[] recipientIds, boolean asynchronous) { return provider.getRecipients(context, recipientIds, asynchronous); } public static Recipients getRecipientsFromString(Context context, @NonNull String rawText, boolean asynchronous) { StringTokenizer tokenizer = new StringTokenizer(rawText, ","); List<String> ids = new LinkedList<>(); while (tokenizer.hasMoreTokens()) { Optional<Long> id = getRecipientIdFromNumber(context, tokenizer.nextToken()); if (id.isPresent()) { ids.add(String.valueOf(id.get())); } } return getRecipientsForIds(context, ids, asynchronous); } private static Recipients getRecipientsForIds(Context context, List<String> idStrings, boolean asynchronous) { long[] ids = new long[idStrings.size()]; int i = 0; for (String id : idStrings) { ids[i++] = Long.parseLong(id); } return provider.getRecipients(context, ids, asynchronous); } private static Optional<Long> getRecipientIdFromNumber(Context context, String number) { number = number.trim(); if (number.isEmpty()) return Optional.absent(); if (hasBracketedNumber(number)) { number = parseBracketedNumber(number); } return Optional.of(CanonicalAddressDatabase.getInstance(context).getCanonicalAddressId(number)); } private static boolean hasBracketedNumber(String recipient) { int openBracketIndex = recipient.indexOf('<'); return (openBracketIndex != -1) && (recipient.indexOf('>', openBracketIndex) != -1); } private static String parseBracketedNumber(String recipient) { int begin = recipient.indexOf('<'); int end = recipient.indexOf('>', begin); String value = recipient.substring(begin + 1, end); return value; } public static void clearCache() { provider.clearCache(); } }
Java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. * */ package ai.grakn.generator; import ai.grakn.concept.Label; import ai.grakn.graql.admin.RelationPlayer; import ai.grakn.graql.admin.VarPatternAdmin; import static ai.grakn.graql.Graql.var; /** * @author Felix Chapman */ public class RelationPlayers extends AbstractGenerator<RelationPlayer> { public RelationPlayers() { super(RelationPlayer.class); } @Override public RelationPlayer generate() { if (random.nextBoolean()) { return RelationPlayer.of(gen(VarPatternAdmin.class)); } else { VarPatternAdmin varPattern; if (random.nextBoolean()) { varPattern = var().label(gen(Label.class)).admin(); } else { varPattern = gen(VarPatternAdmin.class); } return RelationPlayer.of(varPattern, gen(VarPatternAdmin.class)); } } }
Java
package org.janus.miniforth; import org.janus.data.DataContext; public class Compare extends WordImpl { public enum Comp { EQ, NEQ, LT, GT, LEQ, GEQ } Comp comp; public Compare(Comp comp) { super(-1); this.comp = comp; } @Override public void perform(DataContext context) { super.perform(context); MiniForthContext withStack = (MiniForthContext) context; Comparable a = (Comparable) withStack.pop(); Comparable b = (Comparable) withStack.pop(); boolean result = false; if (a.getClass().equals(b.getClass())) { result = compare(a, b); } else { throw new IllegalArgumentException("Vergleich nicht möglich"); } withStack.pushBoolean(result); } private boolean compare(Comparable a, Comparable b) { int c = a.compareTo(b); if (c == 0) { if (comp.equals(Comp.NEQ)) { return false; } else { return comp.equals(Comp.EQ) || comp.equals(Comp.LEQ) || comp.equals(Comp.GEQ); } } else { if (c > 0) { return comp.equals(Comp.NEQ) || comp.equals(Comp.LEQ) || comp.equals(Comp.LT); } else { return comp.equals(Comp.NEQ) || comp.equals(Comp.GEQ) || comp.equals(Comp.GT); } } } }
Java
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SCIDE_SC_SYNTAX_HIGHLIGHTER_HPP_INCLUDED #define SCIDE_SC_SYNTAX_HIGHLIGHTER_HPP_INCLUDED #include "tokens.hpp" #include <QSyntaxHighlighter> #include <QVector> namespace ScIDE { namespace Settings { class Manager; } class Main; enum SyntaxFormat { PlainFormat, ClassFormat, KeywordFormat, BuiltinFormat, PrimitiveFormat, SymbolFormat, StringFormat, CharFormat, NumberFormat, EnvVarFormat, CommentFormat, FormatCount }; struct SyntaxRule { SyntaxRule(): type(Token::Unknown) {} SyntaxRule( Token::Type t, const QString &s ): type(t), expr(s) {} Token::Type type; QRegExp expr; }; class SyntaxHighlighterGlobals : public QObject { Q_OBJECT public: SyntaxHighlighterGlobals( Main *, Settings::Manager * settings ); inline const QTextCharFormat * formats() const { return mFormats; } inline const QTextCharFormat & format( SyntaxFormat type ) const { return mFormats[type]; } inline static const SyntaxHighlighterGlobals * instance() { Q_ASSERT(mInstance); return mInstance; } public Q_SLOTS: void applySettings( Settings::Manager * ); Q_SIGNALS: void syntaxFormatsChanged(); private: friend class SyntaxHighlighter; void initSyntaxRules(); void initKeywords(); void initBuiltins(); void applySettings( Settings::Manager*, const QString &key, SyntaxFormat ); QTextCharFormat mFormats[FormatCount]; QVector<SyntaxRule> mInCodeRules; QRegExp mInSymbolRegexp, mInStringRegexp; static SyntaxHighlighterGlobals *mInstance; }; class SyntaxHighlighter: public QSyntaxHighlighter { Q_OBJECT static const int inCode = 0; static const int inString = 1; static const int inSymbol = 2; static const int inComment = 100; // NOTE: Integers higher than inComment are reserved for multi line comments, // and indicate the comment nesting level! public: SyntaxHighlighter(QTextDocument *parent = 0); private: void highlightBlock(const QString &text); void highlightBlockInCode(const QString& text, int & currentIndex, int & currentState); void highlightBlockInString(const QString& text, int & currentIndex, int & currentState); void highlightBlockInSymbol(const QString& text, int & currentIndex, int & currentState); void highlightBlockInComment(const QString& text, int & currentIndex, int & currentState); Token::Type findMatchingRule(QString const & text, int & currentIndex, int & lengthOfMatch); const SyntaxHighlighterGlobals *mGlobals; }; } #endif
Java
/* * Copyright (C) 2018 The "MysteriumNetwork/node" Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package service import ( "encoding/json" "errors" log "github.com/cihub/seelog" "github.com/mysteriumnetwork/node/communication" "github.com/mysteriumnetwork/node/identity" "github.com/mysteriumnetwork/node/market" "github.com/mysteriumnetwork/node/session" ) var ( // ErrorLocation error indicates that action (i.e. disconnect) ErrorLocation = errors.New("failed to detect service location") // ErrUnsupportedServiceType indicates that manager tried to create an unsupported service type ErrUnsupportedServiceType = errors.New("unsupported service type") ) // Service interface represents pluggable Mysterium service type Service interface { Serve(providerID identity.Identity) error Stop() error ProvideConfig(publicKey json.RawMessage) (session.ServiceConfiguration, session.DestroyCallback, error) } // DialogWaiterFactory initiates communication channel which waits for incoming dialogs type DialogWaiterFactory func(providerID identity.Identity, serviceType string) (communication.DialogWaiter, error) // DialogHandlerFactory initiates instance which is able to handle incoming dialogs type DialogHandlerFactory func(market.ServiceProposal, session.ConfigNegotiator) communication.DialogHandler // DiscoveryFactory initiates instance which is able announce service discoverability type DiscoveryFactory func() Discovery // Discovery registers the service to the discovery api periodically type Discovery interface { Start(ownIdentity identity.Identity, proposal market.ServiceProposal) Stop() Wait() } // NewManager creates new instance of pluggable instances manager func NewManager( serviceRegistry *Registry, dialogWaiterFactory DialogWaiterFactory, dialogHandlerFactory DialogHandlerFactory, discoveryFactory DiscoveryFactory, ) *Manager { return &Manager{ serviceRegistry: serviceRegistry, servicePool: NewPool(), dialogWaiterFactory: dialogWaiterFactory, dialogHandlerFactory: dialogHandlerFactory, discoveryFactory: discoveryFactory, } } // Manager entrypoint which knows how to start pluggable Mysterium instances type Manager struct { dialogWaiterFactory DialogWaiterFactory dialogHandlerFactory DialogHandlerFactory serviceRegistry *Registry servicePool *Pool discoveryFactory DiscoveryFactory } // Start starts an instance of the given service type if knows one in service registry. // It passes the options to the start method of the service. // If an error occurs in the underlying service, the error is then returned. func (manager *Manager) Start(providerID identity.Identity, serviceType string, options Options) (id ID, err error) { service, proposal, err := manager.serviceRegistry.Create(serviceType, options) if err != nil { return id, err } dialogWaiter, err := manager.dialogWaiterFactory(providerID, serviceType) if err != nil { return id, err } providerContact, err := dialogWaiter.Start() if err != nil { return id, err } proposal.SetProviderContact(providerID, providerContact) dialogHandler := manager.dialogHandlerFactory(proposal, service) if err = dialogWaiter.ServeDialogs(dialogHandler); err != nil { return id, err } discovery := manager.discoveryFactory() discovery.Start(providerID, proposal) instance := Instance{ state: Starting, options: options, service: service, proposal: proposal, dialogWaiter: dialogWaiter, discovery: discovery, } id, err = manager.servicePool.Add(&instance) if err != nil { return id, err } go func() { instance.state = Running serveErr := service.Serve(providerID) if serveErr != nil { log.Error("Service serve failed: ", serveErr) } instance.state = NotRunning stopErr := manager.servicePool.Stop(id) if stopErr != nil { log.Error("Service stop failed: ", stopErr) } discovery.Wait() }() return id, nil } // List returns array of running service instances. func (manager *Manager) List() map[ID]*Instance { return manager.servicePool.List() } // Kill stops all services. func (manager *Manager) Kill() error { return manager.servicePool.StopAll() } // Stop stops the service. func (manager *Manager) Stop(id ID) error { return manager.servicePool.Stop(id) } // Service returns a service instance by requested id. func (manager *Manager) Service(id ID) *Instance { return manager.servicePool.Instance(id) }
Java
<!DOCTYPE html > <html> <head> <title>IndexRange - ScalaFX API 8.0.0-R4 - scalafx.scene.control.IndexRange</title> <meta name="description" content="IndexRange - ScalaFX API 8.0.0 - R4 - scalafx.scene.control.IndexRange" /> <meta name="keywords" content="IndexRange ScalaFX API 8.0.0 R4 scalafx.scene.control.IndexRange" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'scalafx.scene.control.IndexRange$'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="value"> <div id="definition"> <a href="IndexRange.html" title="Go to companion"><img src="../../../lib/object_to_class_big.png" /></a> <p id="owner"><a href="../../package.html" class="extype" name="scalafx">scalafx</a>.<a href="../package.html" class="extype" name="scalafx.scene">scene</a>.<a href="package.html" class="extype" name="scalafx.scene.control">control</a></p> <h1><a href="IndexRange.html" title="Go to companion">IndexRange</a></h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <span class="name">IndexRange</span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="scalafx.scene.control.IndexRange"><span>IndexRange</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scalafx.scene.control.IndexRange#VALUE_DELIMITER" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="VALUE_DELIMITER:String"></a> <a id="VALUE_DELIMITER:String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">val</span> </span> <span class="symbol"> <span class="name">VALUE_DELIMITER</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <p class="shortcomment cmt">Index range value delimiter.</p> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scalafx.scene.control.IndexRange#normalize" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="normalize(v1:Int,v2:Int):scalafx.scene.control.IndexRange"></a> <a id="normalize(Int,Int):IndexRange"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">normalize</span><span class="params">(<span name="v1">v1: <span class="extype" name="scala.Int">Int</span></span>, <span name="v2">v2: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <a href="IndexRange.html" class="extype" name="scalafx.scene.control.IndexRange">IndexRange</a></span> </span> </h4> <p class="shortcomment cmt">Convenience method to create an IndexRange instance that has the smaller value as the start index, and the larger value as the end index.</p> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scalafx.scene.control.IndexRange#sfxIndexRange" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="sfxIndexRange(r:scalafx.scene.control.IndexRange):javafx.scene.control.IndexRange"></a> <a id="sfxIndexRange(IndexRange):javafx.scene.control.IndexRange"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">implicit </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">sfxIndexRange</span><span class="params">(<span name="r">r: <a href="IndexRange.html" class="extype" name="scalafx.scene.control.IndexRange">IndexRange</a></span>)</span><span class="result">: <span class="extype" name="javafx.scene.control.IndexRange">javafx.scene.control.IndexRange</span></span> </span> </h4> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scalafx.scene.control.IndexRange#valueOf" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="valueOf(value:String):scalafx.scene.control.IndexRange"></a> <a id="valueOf(String):IndexRange"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">valueOf</span><span class="params">(<span name="value">value: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <a href="IndexRange.html" class="extype" name="scalafx.scene.control.IndexRange">IndexRange</a></span> </span> </h4> <p class="shortcomment cmt">Convenience method to parse in a String of the form '2,6', which will create an IndexRange instance with a start value of 2, and an end value of 6.</p> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
Java
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINIKIN_CMAP_COVERAGE_H #define MINIKIN_CMAP_COVERAGE_H #include <minikin/SparseBitSet.h> namespace android { class CmapCoverage { public: static bool getCoverage(SparseBitSet &coverage, const uint8_t* cmap_data, size_t cmap_size); }; } // namespace android #endif // MINIKIN_CMAP_COVERAGE_H
Java
/* * This file is part of Track It!. * Copyright (C) 2013 Henrique Malheiro * Copyright (C) 2015 Pedro Gomes * * TrackIt! is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Track It! is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Track It!. If not, see <http://www.gnu.org/licenses/>. * */ package com.trackit.business.domain; import java.util.ArrayList; import java.util.List; import com.trackit.business.exception.TrackItException; import com.trackit.presentation.event.Event; import com.trackit.presentation.event.EventManager; import com.trackit.presentation.event.EventPublisher; public class Folder extends TrackItBaseType implements DocumentItem { private String name; private List<GPSDocument> documents; public Folder(String name) { super(); this.name = name; documents = new ArrayList<GPSDocument>(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<GPSDocument> getDocuments() { return documents; } public void add(GPSDocument document) { documents.add(document); } public void remove(GPSDocument document) { documents.remove(document); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Folder other = (Folder) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return String.format("Folder [name=%s]", name); } @Override public void publishSelectionEvent(EventPublisher publisher) { EventManager.getInstance().publish(publisher, Event.FOLDER_SELECTED, this); } @Override public void accept(Visitor visitor) throws TrackItException { visitor.visit(this); } }
Java
#!/bin/bash # # SLURM batch script to launch BLAST # #SBATCH -p nbi-medium # partition (queue) #SBATCH -N 1 # number of nodes #SBATCH -n 1 # number of cores #SBATCH --mem 30000 # memory pool for all cores #SBATCH -t 2-00:00 # time (D-HH:MM) #SBATCH -o /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/TF_analysis/slurm_output/extractNAC.%N.%j.out # STDOUT #SBATCH -e /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/TF_analysis/slurm_output/extractNAC.%N.%j.err # STDERR #SBATCH -J extractNAC #SBATCH --mail-type=END,FAIL # notifications for job done & fail #SBATCH --mail-user=philippa.borrill\@jic.ac.uk # send-to address source perl-5.22.1 cd /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/TF_analysis/ perl /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/scripts/fasta_extract_by_pattern.pl -r -p "|NAC|" Tritcum_aestivum_seq.fas > Triticum_aestivum_NAC.fa
Java
Namespace Items.Standard <Item(615, "Fossilized Dino")> Public Class FossilizedDino Inherits FossilItem Public Overrides ReadOnly Property Description As String = "The fossil of an ancient Pokémon that once lived in the sea. What it looked like is a mystery." Public Sub New() _textureRectangle = New Rectangle(24, 72, 24, 24) End Sub End Class End Namespace
Java
<?php namespace eduTrac\Classes\Models; if ( ! defined('BASE_PATH') ) exit('No direct script access allowed'); /** * Profile Model * * PHP 5.4+ * * eduTrac(tm) : Student Information System (http://www.7mediaws.org/) * @copyright (c) 2013 7 Media Web Solutions, LLC * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License, version 3 * @link http://www.7mediaws.org/ * @since 3.0.0 * @package eduTrac * @author Joshua Parker <josh@7mediaws.org> */ use \eduTrac\Classes\Core\DB; use \eduTrac\Classes\Libraries\Util; class ProfileModel { private $_auth; public function __construct() { $this->_auth = new \eduTrac\Classes\Libraries\Cookies; } public function index() {} public function runProfile($data) { $update1 = [ "fname" => $data['fname'],"lname" => $data['lname'], "mname" => Util::_trim($data['mname']),"email" => Util::_trim($data['email']), "ssn" => Util::_trim($data['ssn']),"dob" => $data['dob'] ]; $bind = [ ":personID" => $this->_auth->getPersonField('personID') ]; $q = DB::inst()->update("person",$update1,"personID = :personID",$bind); if(!empty($data['password'])) { $update2 = ["password" => et_hash_password($data['password'])]; DB::inst()->update("person",$update2,"personID = :personID",$bind); } redirect( BASE_URL . 'profile/' ); } public function __destruct() { DB::inst()->close(); } }
Java
using System; namespace UnstuckMeLoggers { public enum ERR_TYPES_SERVER { // if you add one of these please add it in the switch statement to be handled SERVER_GUI_LOGIN, SERVER_GUI_LOGOUT, SERVER_CONNECTION_ERROR, SERVER_GUI_INTERACTION_ERROR, SERVER_START, SERVER_STOP, DATABASE_RETURN_ERROR, DATABASE_CONNECTION_ERROR } internal class ErrContainerServer { string i_ErrorMsg; // the error message string contained by the thrown exception string i_ErrTypeStartMark; // the xml like tag that defines the start of the error string i_ErrTypeEndMark; // the xml like tag that defines the end of the error string i_ErrorTime; // the string representaition of the time the errors occurance string i_AdditionalInfo; // a string that holds any additional info you would like logged such as what caused the error internal ErrContainerServer(string ErrorMsg, string ErrTypeStartMark, string ErrTypeEndMark, string ErrorTime, string AdditionalInfo = null) { i_ErrorMsg = ErrorMsg; i_ErrTypeStartMark = ErrTypeStartMark; i_ErrTypeEndMark = ErrTypeEndMark; i_ErrorTime = ErrorTime; i_AdditionalInfo = AdditionalInfo; } public override string ToString() { string temp = i_ErrTypeStartMark + Environment.NewLine + "\t" + "<ErrMsg=" + i_ErrorMsg + "/>"; if (i_AdditionalInfo != null) temp = temp + Environment.NewLine + "<AdditionalInfo=" + i_AdditionalInfo + "/>"; temp = temp + Environment.NewLine + "\t" + "<ErrTime=" + i_ErrorTime + "/>" + Environment.NewLine + i_ErrTypeEndMark; return temp; } } }
Java
import discord import asyncio import datetime import time import aiohttp import threading import glob import re import json import os import urllib.request from discord.ext import commands from random import randint from random import choice as randchoice from random import choice as rndchoice from random import shuffle from .utils.dataIO import fileIO from .utils import checks from bs4 import BeautifulSoup class Runescapecompare: """Runescape-relate commands""" def __init__(self, bot): self.bot = bot """ imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player= nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player= """ @commands.group(name="compare", pass_context=True) async def _compare(self, ctx): if ctx.invoked_subcommand is None: await self.bot.say("Please, choose a skill to compare!") #####Overall##### @_compare.command(name="overall", pass_context=True) async def compare_overall(self, ctx, name1 : str, name2 : str): address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1 address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2 try: website1 = urllib.request.urlopen(address1) website2 = urllib.request.urlopen(address2) website_html1 = website1.read().decode(website1.headers.get_content_charset()) website_html2 = website2.read().decode(website2.headers.get_content_charset()) stats1 = website_html1.split("\n") stats2 = website_html2.split("\n") stat1 = stats1[0].split(",") stat2= stats2[0].split(",") if stat1[2] > stat2[2]: comparerank = int(stat2[0]) - int(stat1[0]) comparelvl = int(stat1[1]) - int(stat2[1]) comparexp = int(stat1[2]) - int(stat2[2]) await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```") if stat2[2] > stat1[2]: comparerank = stat2[0] - stat1[0] comparelvl = stat2[1] - stat1[1] comparexp = stat2[2] - stat1[2] await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```") except: await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?") def setup(bot): n = Runescapecompare(bot) bot.add_cog(n)
Java
package com.snail.webgame.game.protocal.relation.getRequest; import org.epilot.ccf.config.Resource; import org.epilot.ccf.core.processor.ProtocolProcessor; import org.epilot.ccf.core.processor.Request; import org.epilot.ccf.core.processor.Response; import org.epilot.ccf.core.protocol.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.snail.webgame.game.common.GameMessageHead; import com.snail.webgame.game.common.util.Command; import com.snail.webgame.game.protocal.relation.service.RoleRelationMgtService; public class GetAddRequestProcessor extends ProtocolProcessor{ private static Logger logger = LoggerFactory.getLogger("logs"); private RoleRelationMgtService roleRelationMgtService; public void setRoleRelationMgtService(RoleRelationMgtService roleRelationMgtService) { this.roleRelationMgtService = roleRelationMgtService; } @Override public void execute(Request request, Response response) { Message msg = request.getMessage(); GameMessageHead header = (GameMessageHead) msg.getHeader(); header.setMsgType(Command.GET_ADD_REQUEST_RESP); int roleId = header.getUserID0(); GetAddRequestReq req = (GetAddRequestReq) msg.getBody(); GetAddRequestResp resp = roleRelationMgtService.getAddFriendRequestList(roleId, req); msg.setHeader(header); msg.setBody(resp); response.write(msg); if(logger.isInfoEnabled()){ logger.info(Resource.getMessage("game", "GAME_ROLE_RELATION_INFO_4") + ": result=" + resp.getResult() + ",roleId=" + roleId); } } }
Java
'use strict'; var ParameterDef = function(object) { this.id = object.id; this.summary = object.summary; this.description = object.description; this.type = object.type; this.mandatory = object.mandatory; this.defaultValue = object.defaultValue; }; module.exports = ParameterDef;
Java
/******************************************************************************* * Copyright (c) 2000, 2013 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.core; import java.util.ArrayList; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IInitializer; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IModuleDescription; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; /** * @see IJavaElementRequestor */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class JavaElementRequestor implements IJavaElementRequestor { /** * True if this requestor no longer wants to receive * results from its <code>IRequestorNameLookup</code>. */ protected boolean canceled= false; /** * A collection of the resulting fields, or <code>null</code> * if no field results have been received. */ protected ArrayList fields= null; /** * A collection of the resulting initializers, or <code>null</code> * if no initializer results have been received. */ protected ArrayList initializers= null; /** * A collection of the resulting member types, or <code>null</code> * if no member type results have been received. */ protected ArrayList memberTypes= null; /** * A collection of the resulting methods, or <code>null</code> * if no method results have been received. */ protected ArrayList methods= null; /** * A collection of the resulting package fragments, or <code>null</code> * if no package fragment results have been received. */ protected ArrayList packageFragments= null; /** * A collection of the resulting types, or <code>null</code> * if no type results have been received. */ protected ArrayList types= null; /** * A collection of the resulting modules, or <code>null</code> * if no module results have been received */ protected ArrayList<IModuleDescription> modules = null; /** * Empty arrays used for efficiency */ protected static final IField[] EMPTY_FIELD_ARRAY= new IField[0]; protected static final IInitializer[] EMPTY_INITIALIZER_ARRAY= new IInitializer[0]; protected static final IType[] EMPTY_TYPE_ARRAY= new IType[0]; protected static final IPackageFragment[] EMPTY_PACKAGE_FRAGMENT_ARRAY= new IPackageFragment[0]; protected static final IMethod[] EMPTY_METHOD_ARRAY= new IMethod[0]; protected static final IModuleDescription[] EMPTY_MODULE_ARRAY= new IModuleDescription[0]; /** * @see IJavaElementRequestor */ @Override public void acceptField(IField field) { if (this.fields == null) { this.fields= new ArrayList(); } this.fields.add(field); } /** * @see IJavaElementRequestor */ @Override public void acceptInitializer(IInitializer initializer) { if (this.initializers == null) { this.initializers= new ArrayList(); } this.initializers.add(initializer); } /** * @see IJavaElementRequestor */ @Override public void acceptMemberType(IType type) { if (this.memberTypes == null) { this.memberTypes= new ArrayList(); } this.memberTypes.add(type); } /** * @see IJavaElementRequestor */ @Override public void acceptMethod(IMethod method) { if (this.methods == null) { this.methods = new ArrayList(); } this.methods.add(method); } /** * @see IJavaElementRequestor */ @Override public void acceptPackageFragment(IPackageFragment packageFragment) { if (this.packageFragments== null) { this.packageFragments= new ArrayList(); } this.packageFragments.add(packageFragment); } /** * @see IJavaElementRequestor */ @Override public void acceptType(IType type) { if (this.types == null) { this.types= new ArrayList(); } this.types.add(type); } /** * @see IJavaElementRequestor */ @Override public void acceptModule(IModuleDescription module) { if (this.modules == null) { this.modules= new ArrayList(); } this.modules.add(module); } /** * @see IJavaElementRequestor */ public IField[] getFields() { if (this.fields == null) { return EMPTY_FIELD_ARRAY; } int size = this.fields.size(); IField[] results = new IField[size]; this.fields.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IInitializer[] getInitializers() { if (this.initializers == null) { return EMPTY_INITIALIZER_ARRAY; } int size = this.initializers.size(); IInitializer[] results = new IInitializer[size]; this.initializers.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IType[] getMemberTypes() { if (this.memberTypes == null) { return EMPTY_TYPE_ARRAY; } int size = this.memberTypes.size(); IType[] results = new IType[size]; this.memberTypes.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IMethod[] getMethods() { if (this.methods == null) { return EMPTY_METHOD_ARRAY; } int size = this.methods.size(); IMethod[] results = new IMethod[size]; this.methods.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IPackageFragment[] getPackageFragments() { if (this.packageFragments== null) { return EMPTY_PACKAGE_FRAGMENT_ARRAY; } int size = this.packageFragments.size(); IPackageFragment[] results = new IPackageFragment[size]; this.packageFragments.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IType[] getTypes() { if (this.types== null) { return EMPTY_TYPE_ARRAY; } int size = this.types.size(); IType[] results = new IType[size]; this.types.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IModuleDescription[] getModules() { if (this.modules == null) { return EMPTY_MODULE_ARRAY; } int size = this.modules.size(); IModuleDescription[] results = new IModuleDescription[size]; this.modules.toArray(results); return results; } /** * @see IJavaElementRequestor */ @Override public boolean isCanceled() { return this.canceled; } /** * Reset the state of this requestor. */ public void reset() { this.canceled = false; this.fields = null; this.initializers = null; this.memberTypes = null; this.methods = null; this.packageFragments = null; this.types = null; } /** * Sets the #isCanceled state of this requestor to true or false. */ public void setCanceled(boolean b) { this.canceled= b; } }
Java
import string import ast from state_machine import PSM, Source class SpecialPattern: individual_chars = ('t', 'n', 'v', 'f', 'r', '0') range_chars = ('d', 'D', 'w', 'W', 's', 'S') special_chars = ('^', '$', '[', ']', '(', ')', '{', '}', '\\', '.', '*', '?', '+', '|', '.') restrict_special_chars = ('\\', '[', ']') posix_classes = ("alnum", "alpha", "blank", "cntrl", "digit", "graph", "lower", "print", "punct", "space", "upper", "xdigit", "d", "w", "s") min_len_posix_class = 1 #------------------------------------- # Group class WrappedGroup: def __init__(self): self.group = ast.Group() self.is_alt = False def add(self, other): if self.is_alt: last_alt = self.alt.parts[-1] + (other,) self.alt.parts = self.alt.parts[:-1] + (last_alt,) else: self.group.seq = self.group.seq + (other,) @property def alt(self) -> ast.Alternative: assert self.is_alt return self.group.seq[0] def collapse_alt(self): if self.is_alt: self.alt.parts = self.alt.parts + ((),) else: self.is_alt = True first_alt_elems = self.group.seq self.group.seq = (ast.Alternative(),) self.alt.parts = (first_alt_elems,()) class OpeningOfGroup: def __init__(self, parent: None, initial: bool=False): self.is_initial = initial self.parent = parent # OpeningOfGroup or ContentOfGroup self.g = WrappedGroup() self.content_of_initial = None # forward of function self.add = self.g.add # if this group is the initial, their is no parent but we must refer # to itself as the returning state # but if it is a nested group, it must be added into its global group if self.is_initial: self.content_of_initial = ContentOfGroup(self, initial) else: self.parent.add(self.g.group) def next(self, psm: PSM): if not self.is_initial and psm.char == "?": return FirstOptionOfGroup(self) elif psm.char == ")": if self.is_initial: psm.error = 'unexpected ")"' else: return self.parent elif psm.char == "(": return OpeningOfGroup(self) elif self.is_initial: return self.content_of_initial.next(psm) else: t = ContentOfGroup(self) return t.next(psm) class FirstOptionOfGroup: def __init__(self, parent: OpeningOfGroup): self.parent = parent def next(self, psm: PSM): if psm.char == ":": self.parent.g.group.ignored = True return ContentOfGroup(self.parent) elif psm.char == "!": self.parent.g.group.lookhead = ast.Group.NegativeLookhead return ContentOfGroup(self.parent) elif psm.char == "=": self.parent.g.group.lookhead = ast.Group.PositiveLookhead return ContentOfGroup(self.parent) elif psm.char == "<": self.parent.g.group.name = "" return NameOfGroup(self.parent) else: psm.error = 'expected ":", "!", "<" or "="' class NameOfGroup: def __init__(self, parent: OpeningOfGroup): self.parent = parent def next(self, psm: PSM): if psm.char.isalpha() or psm.char == "_": self.parent.g.group.name += psm.char return self elif psm.char == ">": return self.parent else: psm.error = 'expected a letter, "_" or ">"' class ContentOfGroup: NotQuantified = 0 Quantified = 1 UngreedyQuantified = 2 def __init__(self, parent: OpeningOfGroup, initial: bool=False): self.parent = parent self.is_initial = initial self.limited_prev = parent if initial else self self.quantified = ContentOfGroup.NotQuantified # forward of function self.add = self.parent.add def next(self, psm: PSM): quantified = self.quantified self.quantified = ContentOfGroup.NotQuantified if psm.char == ")": if self.is_initial: psm.error = "unbalanced parenthesis" else: return self.parent.parent elif psm.char == "(": return OpeningOfGroup(self.limited_prev) elif psm.char == "^": self.add(ast.MatchBegin()) return self.limited_prev elif psm.char == "$": self.add(ast.MatchEnd()) return self.limited_prev elif psm.char == ".": t = ast.PatternChar() t.pattern = psm.char self.add(t) return self.limited_prev elif psm.char == "\\": return EscapedChar(self.limited_prev, as_single_chars=SpecialPattern.special_chars) elif psm.char == "[": return CharClass(self.limited_prev) elif psm.char == "|": self.parent.g.collapse_alt() return self.limited_prev # >>> Quantifiers elif psm.char == "?" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified last = self._last_or_fail(psm) if last: last.quantifier = ast.NoneOrOnce() return self.limited_prev elif psm.char == "*" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified last = self._last_or_fail(psm) if last: last.quantifier = ast.NoneOrMore() return self.limited_prev elif psm.char == "+" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified last = self._last_or_fail(psm) if last: last.quantifier = ast.OneOrMore() return self.limited_prev elif psm.char == "{" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified t = MinimumOfRepetition(self.limited_prev) last = self._last_or_fail(psm) if last: last.quantifier = t.between return t elif psm.char == "?" and quantified == ContentOfGroup.Quantified: self.quantified = ContentOfGroup.UngreedyQuantified last = self._last_or_fail(psm) if last: last.quantifier.greedy = False return self.limited_prev elif quantified == ContentOfGroup.Quantified: psm.error = "unexpected quantifier" elif quantified == ContentOfGroup.UngreedyQuantified: psm.error = "quantifier repeated" # <<< Quantifier else: t = ast.SingleChar() t.char = psm.char self.add(t) return self.limited_prev def _last_or_fail(self, psm: PSM): if self.parent.g.group.seq: return self.parent.g.group.seq[-1] else: psm.error = "nothing to repeat" class MinimumOfRepetition: def __init__(self, parent: ContentOfGroup): self.parent = parent self.between = ast.Between() self.min = [] def next(self, psm: PSM): if psm.char.isdigit(): self.min.append(psm.char) return self elif psm.char == ",": self._interpret() return MaximumOfRepetition(self) elif psm.char == "}": self._interpret() return self.parent else: psm.error = 'expected digit, "," or "}"' def _interpret(self): if not self.min: return try: count = int("".join(self.min)) except ValueError: assert False, "internal error: cannot convert to number minimum of repetition" self.between.min = count class MaximumOfRepetition: def __init__(self, repeat: MinimumOfRepetition): self.repeat = repeat self.max = [] def next(self, psm: PSM): if psm.char.isdigit(): self.max.append(psm.char) return self elif psm.char == "}": self._interpret() return self.repeat.parent else: psm.error = 'expected digit, "," or "}"' def _interpret(self): if not self.max: return try: count = int("".join(self.max)) except ValueError: assert False, "internal error: cannot convert to number maximum of repetition" self.repeat.between.max = count #-------------------------------------- # Escaping class EscapedChar: def __init__(self, prev, as_single_chars=(), as_pattern_chars=()): self.prev = prev # ContentOfGroup or CharClass self.single_chars = as_single_chars self.pattern_chars = as_pattern_chars def next(self, psm: PSM): if psm.char in SpecialPattern.individual_chars \ or psm.char in SpecialPattern.range_chars \ or psm.char in self.pattern_chars: t = ast.PatternChar() t.pattern = psm.char self.prev.add(t) return self.prev elif psm.char in self.single_chars: t = ast.SingleChar() t.char = psm.char self.prev.add(t) return self.prev elif psm.char == "x": return AsciiChar(self.prev) elif psm.char == "u": return UnicodeChar(self.prev) else: psm.error = "unauthorized escape of {}".format(psm.char) class AsciiChar: def __init__(self, prev): self.prev = prev # ContentOfGroup or CharClass self.pattern = ast.PatternChar() self.pattern.type = ast.PatternChar.Ascii self.prev.add(self.pattern) def next(self, psm: PSM): if psm.char in string.hexdigits: self.pattern.pattern += psm.char count = len(self.pattern.pattern) return self.prev if count >= 2 else self else: psm.error = "expected ASCII hexadecimal character" class UnicodeChar: def __init__(self, prev): self.prev = prev # ContentOfGroup or CharClass self.pattern = ast.PatternChar() self.pattern.type = ast.PatternChar.Unicode self.prev.add(self.pattern) def next(self, psm: PSM): if psm.char in string.hexdigits: self.pattern.pattern += psm.char count = len(self.pattern.pattern) return self.prev if count >= 4 else self else: psm.error = "expected ASCII hexadecimal character" #------------------------------------- # Character class class WrappedCharClass: def __init__(self): # ast is CharClass or may be changed to PatternClass in one case self.ast = ast.CharClass() def add(self, other): assert isinstance(self.ast, ast.CharClass) self.ast.elems = self.ast.elems + (other,) def pop(self): assert isinstance(self.ast, ast.CharClass) last = self.ast.elems[-1] self.ast.elems = self.ast.elems[:-1] return last class CharClass: def __init__(self, prev): self.prev = prev # ContentOfGroup or CharClass self.q = WrappedCharClass() # forward function self.add = self.q.add self.next_is_range = False self.empty = True self.can_mutate = True def next(self, psm: PSM): this_should_be_range = self.next_is_range self.next_is_range = False this_is_empty = self.empty self.empty = False if psm.char == "\\": self.can_mutate = False self.next_is_range = this_should_be_range return EscapedChar(self, as_single_chars=SpecialPattern.restrict_special_chars) elif this_should_be_range and psm.char != "]": assert isinstance(self.q.ast, ast.CharClass) assert len(self.q.ast.elems) >= 1 self.next_is_range = False t = ast.Range() t.begin = self.q.pop() t.end = ast.SingleChar() t.end.char = psm.char self.q.add(t) return self elif psm.char == "^": # if at the begining, it has a special meaning if this_is_empty: self.can_mutate = False self.q.ast.negate = True else: t = ast.SingleChar() t.char = psm.char self.q.add(t) return self elif psm.char == "]": if this_should_be_range: t = ast.SingleChar() t.char = "-" self.q.add(t) else: self.mutate_if_posix_like() self.prev.add(self.q.ast) return self.prev elif psm.char == "[": return CharClass(self) elif psm.char == "-" and len(self.q.ast.elems) >= 1: self.next_is_range = True return self else: t = ast.SingleChar() t.char = psm.char self.q.add(t) return self def mutate_if_posix_like(self): """ Change from character class to pattern char if the content is matching POSIX-like classe. """ assert isinstance(self.q.ast, ast.CharClass) # put in this variable everything that had happen but not saved into # the single char object # because mutation is only possible if the exact string of the content # match a pre-definied list, so if an unlogged char is consumed, it # must prevent mutation if not self.can_mutate: return if len(self.q.ast.elems) < SpecialPattern.min_len_posix_class + 2: return opening = self.q.ast.elems[0] if not isinstance(opening, ast.SingleChar) or opening.char != ":": return closing = self.q.ast.elems[-1] if not isinstance(closing, ast.SingleChar) or closing.char != ":": return is_only_ascii = lambda x: (isinstance(x, ast.SingleChar) and len(x.char) == 1 and x.char.isalpha()) class_may_be_a_word = not any( not is_only_ascii(x) for x in self.q.ast.elems[1:-1]) if not class_may_be_a_word: return word = "".join(s.char for s in self.q.ast.elems[1:-1]) if word not in SpecialPattern.posix_classes: return t = ast.PatternChar() t.pattern = word t.type = ast.PatternChar.Posix self.q.ast = t #------------------------------------- def parse(expr, **kw): sm = PSM() sm.source = Source(expr) sm.starts_with(OpeningOfGroup(parent=None, initial=True)) sm.pre_action = kw.get("pre_action", None) sm.post_action = kw.get("post_action", None) sm.parse() return sm.state.g.group
Java
{ am_pm_abbreviated => [ "Munkyo", "Eigulo" ], available_formats => { E => "ccc", EHm => "E HH:mm", EHms => "E HH:mm:ss", Ed => "d, E", Ehm => "E h:mm a", Ehms => "E h:mm:ss a", Gy => "G y", GyMMM => "G y MMM", GyMMMEd => "G y MMM d, E", GyMMMd => "G y MMM d", H => "HH", Hm => "HH:mm", Hms => "HH:mm:ss", Hmsv => "HH:mm:ss v", Hmv => "HH:mm v", M => "L", MEd => "E, M/d", MMM => "LLL", MMMEd => "E, MMM d", MMMMEd => "E, MMMM d", "MMMMW-count-other" => "'week' W 'of' MMMM", MMMMd => "MMMM d", MMMd => "MMM d", Md => "M/d", d => "d", h => "h a", hm => "h:mm a", hms => "h:mm:ss a", hmsv => "h:mm:ss a v", hmv => "h:mm a v", ms => "mm:ss", y => "y", yM => "M/y", yMEd => "E, M/d/y", yMMM => "MMM y", yMMMEd => "E, MMM d, y", yMMMM => "MMMM y", yMMMd => "y MMM d", yMd => "y-MM-dd", yQQQ => "QQQ y", yQQQQ => "QQQQ y", "yw-count-other" => "'week' w 'of' y" }, code => "xog", date_format_full => "EEEE, d MMMM y", date_format_long => "d MMMM y", date_format_medium => "d MMM y", date_format_short => "dd/MM/y", datetime_format_full => "{1} {0}", datetime_format_long => "{1} {0}", datetime_format_medium => "{1} {0}", datetime_format_short => "{1} {0}", day_format_abbreviated => [ "Bala", "Kubi", "Kusa", "Kuna", "Kuta", "Muka", "Sabi" ], day_format_narrow => [ "B", "B", "S", "K", "K", "M", "S" ], day_format_wide => [ "Balaza", "Owokubili", "Owokusatu", "Olokuna", "Olokutaanu", "Olomukaaga", "Sabiiti" ], day_stand_alone_abbreviated => [ "Bala", "Kubi", "Kusa", "Kuna", "Kuta", "Muka", "Sabi" ], day_stand_alone_narrow => [ "B", "B", "S", "K", "K", "M", "S" ], day_stand_alone_wide => [ "Balaza", "Owokubili", "Owokusatu", "Olokuna", "Olokutaanu", "Olomukaaga", "Sabiiti" ], era_abbreviated => [ "AZ", "AF" ], era_narrow => [ "AZ", "AF" ], era_wide => [ "Kulisto nga azilawo", "Kulisto nga affile" ], first_day_of_week => 1, glibc_date_1_format => "%a %b %e %H:%M:%S %Z %Y", glibc_date_format => "%m/%d/%y", glibc_datetime_format => "%a %b %e %H:%M:%S %Y", glibc_time_12_format => "%I:%M:%S %p", glibc_time_format => "%H:%M:%S", language => "Soga", month_format_abbreviated => [ "Jan", "Feb", "Mar", "Apu", "Maa", "Juu", "Jul", "Agu", "Seb", "Oki", "Nov", "Des" ], month_format_narrow => [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], month_format_wide => [ "Janwaliyo", "Febwaliyo", "Marisi", "Apuli", "Maayi", "Juuni", "Julaayi", "Agusito", "Sebuttemba", "Okitobba", "Novemba", "Desemba" ], month_stand_alone_abbreviated => [ "Jan", "Feb", "Mar", "Apu", "Maa", "Juu", "Jul", "Agu", "Seb", "Oki", "Nov", "Des" ], month_stand_alone_narrow => [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], month_stand_alone_wide => [ "Janwaliyo", "Febwaliyo", "Marisi", "Apuli", "Maayi", "Juuni", "Julaayi", "Agusito", "Sebuttemba", "Okitobba", "Novemba", "Desemba" ], name => "Soga", native_language => "Olusoga", native_name => "Olusoga", native_script => undef, native_territory => undef, native_variant => undef, quarter_format_abbreviated => [ "Q1", "Q2", "Q3", "Q4" ], quarter_format_narrow => [ 1, 2, 3, 4 ], quarter_format_wide => [ "Ebisera ebyomwaka ebisoka", "Ebisera ebyomwaka ebyokubiri", "Ebisera ebyomwaka ebyokusatu", "Ebisera ebyomwaka ebyokuna" ], quarter_stand_alone_abbreviated => [ "Q1", "Q2", "Q3", "Q4" ], quarter_stand_alone_narrow => [ 1, 2, 3, 4 ], quarter_stand_alone_wide => [ "Ebisera ebyomwaka ebisoka", "Ebisera ebyomwaka ebyokubiri", "Ebisera ebyomwaka ebyokusatu", "Ebisera ebyomwaka ebyokuna" ], script => undef, territory => undef, time_format_full => "HH:mm:ss zzzz", time_format_long => "HH:mm:ss z", time_format_medium => "HH:mm:ss", time_format_short => "HH:mm", variant => undef, version => 31 }
Java
/* * eGov suite of products aim to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) <2015> eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org. */ package org.egov.search.service; import org.egov.search.domain.entities.Address; import org.egov.search.domain.entities.Person; import org.json.simple.JSONObject; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static com.jayway.jsonassert.JsonAssert.with; public class SimpleFieldsResourceGeneratorTest { private String json; @Before public void before() { Person person = Person.newInstance(); ResourceGenerator<Person> resourceGenerator = new ResourceGenerator<>(Person.class, person); JSONObject resource = resourceGenerator.generate(); json = resource.toJSONString(); } @Test public void withMultipleFields() { with(json).assertEquals("$.searchable.citizen", true); with(json).assertEquals("$.searchable.age", 37); with(json).assertEquals("$.clauses.status", "ACTIVE"); with(json).assertNotDefined("$.searchable.role"); } @Test public void withMultipleFields_WithGivenName() { with(json).assertEquals("$.searchable.citizen_name", "Elzan"); } @Test public void withAListField() { with(json).assertEquals("$.searchable.jobs", Arrays.asList("Job One", "Job Two")); } @Test public void withAMapField() { with(json).assertEquals("$.searchable.serviceHistory.company1", "Job One"); with(json).assertEquals("$.searchable.serviceHistory.company2", "Job Two"); } @Test public void shouldGroupFields() { Address address = new Address("street1", "560001"); ResourceGenerator<Address> resourceGenerator = new ResourceGenerator<>(Address.class, address); JSONObject resource = resourceGenerator.generate(); String json = resource.toJSONString(); with(json).assertEquals("$.searchable.street", "street1"); with(json).assertEquals("$.searchable.pincode", "560001"); with(json).assertNotDefined("$.clauses"); with(json).assertNotDefined("$.common"); } }
Java
Fox.define('views/email/fields/from-email-address', 'views/fields/link', function (Dep) { return Dep.extend({ listTemplate: 'email/fields/from-email-address/detail', detailTemplate: 'email/fields/from-email-address/detail', }); });
Java
package com.mx.fic.inventory.business.builder; import com.mx.fic.inventory.business.builder.config.AbstractDTOBuilder; import com.mx.fic.inventory.business.builder.config.BuilderConfiguration; import com.mx.fic.inventory.dto.BaseDTO; import com.mx.fic.inventory.dto.UserDetailDTO; import com.mx.fic.inventory.persistent.BaseEntity; import com.mx.fic.inventory.persistent.UserDetail; @BuilderConfiguration (dtoClass = UserDetailDTO.class, entityClass= UserDetail.class) public class UserDetailBuilder extends AbstractDTOBuilder { public BaseDTO createDTO(BaseEntity entity) { UserDetailDTO userDetailDTO = new UserDetailDTO(); UserDetail userDetail = (UserDetail) entity; userDetailDTO.setAddress(userDetail.getAddress()); userDetailDTO.setCurp(userDetail.getCurp()); userDetailDTO.setEmail(userDetail.getEmail()); userDetailDTO.setId(userDetail.getId()); userDetailDTO.setLastAccess(userDetail.getLastAccess()); userDetailDTO.setLastName(userDetail.getLastName()); userDetailDTO.setName(userDetail.getName()); userDetailDTO.setRfc(userDetail.getRfc()); userDetailDTO.setShortName(userDetail.getShortName()); userDetailDTO.setSurName(userDetail.getSurName()); return userDetailDTO; } }
Java
export function Bounds(width, height) { this.width = width; this.height = height; } Bounds.prototype.equals = function(o) { return ((o != null) && (this.width == o.width) && (this.height == o.height)); };
Java
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- qsqlquerymodel.cpp --> <title>List of All Members for QSqlQueryModel | Qt SQL 5.7</title> <link rel="stylesheet" type="text/css" href="style/offline-simple.css" /> <script type="text/javascript"> window.onload = function(){document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");}; </script> </head> <body> <div class="header" id="qtdocheader"> <div class="main"> <div class="main-rounded"> <div class="navigationbar"> <table><tr> <td ><a href="../qtdoc/supported-platforms-and-configurations.html#qt-5-7">Qt 5.7</a></td><td ><a href="qtsql-index.html">Qt SQL</a></td><td ><a href="qtsql-module.html">C++ Classes</a></td><td >QSqlQueryModel</td></tr></table><table class="buildversion"><tr> <td id="buildversion" width="100%" align="right">Qt 5.7.0 Reference Documentation</td> </tr></table> </div> </div> <div class="content"> <div class="line"> <div class="content mainContent"> <div class="sidebar"><div class="sidebar-content" id="sidebar-content"></div></div> <h1 class="title">List of All Members for QSqlQueryModel</h1> <p>This is the complete list of members for <a href="qsqlquerymodel.html">QSqlQueryModel</a>, including inherited members.</p> <div class="table"><table class="propsummary"> <tr><td class="topAlign"><ul> <li class="fn">enum <span class="name"><b><a href="../qtcore/qabstractitemmodel.html#LayoutChangeHint-enum">LayoutChangeHint</a></b></span></li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#QSqlQueryModel">QSqlQueryModel</a></b></span>(QObject *)</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#dtor.QSqlQueryModel">~QSqlQueryModel</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginInsertColumns">beginInsertColumns</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginInsertRows">beginInsertRows</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginMoveColumns">beginMoveColumns</a></b></span>(const QModelIndex &amp;, int , int , const QModelIndex &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginMoveRows">beginMoveRows</a></b></span>(const QModelIndex &amp;, int , int , const QModelIndex &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginRemoveColumns">beginRemoveColumns</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginRemoveRows">beginRemoveRows</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginResetModel">beginResetModel</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#blockSignals">blockSignals</a></b></span>(bool )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#buddy">buddy</a></b></span>(const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#canDropMimeData">canDropMimeData</a></b></span>(const QMimeData *, Qt::DropAction , int , int , const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#canFetchMore">canFetchMore</a></b></span>(const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#canFetchMore">canFetchMore</a></b></span>(const QModelIndex &amp;) const : bool</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#changePersistentIndex">changePersistentIndex</a></b></span>(const QModelIndex &amp;, const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#changePersistentIndexList">changePersistentIndexList</a></b></span>(const QModelIndexList &amp;, const QModelIndexList &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#childEvent">childEvent</a></b></span>(QChildEvent *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#children">children</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#clear">clear</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnCount">columnCount</a></b></span>(const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#columnCount">columnCount</a></b></span>(const QModelIndex &amp;) const : int</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsAboutToBeInserted">columnsAboutToBeInserted</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsAboutToBeMoved">columnsAboutToBeMoved</a></b></span>(const QModelIndex &amp;, int , int , const QModelIndex &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsAboutToBeRemoved">columnsAboutToBeRemoved</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsInserted">columnsInserted</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsMoved">columnsMoved</a></b></span>(const QModelIndex &amp;, int , int , const QModelIndex &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsRemoved">columnsRemoved</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect">connect</a></b></span>(const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect-1">connect</a></b></span>(const QObject *, const QMetaMethod &amp;, const QObject *, const QMetaMethod &amp;, Qt::ConnectionType )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect-2">connect</a></b></span>(const QObject *, const char *, const char *, Qt::ConnectionType ) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect-3">connect</a></b></span>(const QObject *, PointerToMemberFunction , const QObject *, PointerToMemberFunction , Qt::ConnectionType )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect-4">connect</a></b></span>(const QObject *, PointerToMemberFunction , Functor )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect-5">connect</a></b></span>(const QObject *, PointerToMemberFunction , const QObject *, Functor , Qt::ConnectionType )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connectNotify">connectNotify</a></b></span>(const QMetaMethod &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#createIndex">createIndex</a></b></span>(int , int , void *) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#createIndex-1">createIndex</a></b></span>(int , int , quintptr ) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#customEvent">customEvent</a></b></span>(QEvent *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#d_ptr-var">d_ptr</a></b></span> : </li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#data">data</a></b></span>(const QModelIndex &amp;, int ) const</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#data">data</a></b></span>(const QModelIndex &amp;, int ) const : QVariant</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#dataChanged">dataChanged</a></b></span>(const QModelIndex &amp;, const QModelIndex &amp;, const QVector&lt;int&gt; &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#deleteLater">deleteLater</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#destroyed">destroyed</a></b></span>(QObject *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect">disconnect</a></b></span>(const QObject *, const char *, const QObject *, const char *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect-1">disconnect</a></b></span>(const QObject *, const QMetaMethod &amp;, const QObject *, const QMetaMethod &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect-4">disconnect</a></b></span>(const QMetaObject::Connection &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect-2">disconnect</a></b></span>(const char *, const QObject *, const char *) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect-3">disconnect</a></b></span>(const QObject *, const char *) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect-5">disconnect</a></b></span>(const QObject *, PointerToMemberFunction , const QObject *, PointerToMemberFunction )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnectNotify">disconnectNotify</a></b></span>(const QMetaMethod &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#dropMimeData">dropMimeData</a></b></span>(const QMimeData *, Qt::DropAction , int , int , const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstracttablemodel.html#dropMimeData">dropMimeData</a></b></span>(const QMimeData *, Qt::DropAction , int , int , const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#dumpObjectInfo">dumpObjectInfo</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#dumpObjectTree">dumpObjectTree</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#dynamicPropertyNames">dynamicPropertyNames</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endInsertColumns">endInsertColumns</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endInsertRows">endInsertRows</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endMoveColumns">endMoveColumns</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endMoveRows">endMoveRows</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endRemoveColumns">endRemoveColumns</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endRemoveRows">endRemoveRows</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endResetModel">endResetModel</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#event">event</a></b></span>(QEvent *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#eventFilter">eventFilter</a></b></span>(QObject *, QEvent *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#fetchMore">fetchMore</a></b></span>(const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#fetchMore">fetchMore</a></b></span>(const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#findChild">findChild</a></b></span>(const QString &amp;, Qt::FindChildOptions ) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#findChildren">findChildren</a></b></span>(const QString &amp;, Qt::FindChildOptions ) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#findChildren-1">findChildren</a></b></span>(const QRegExp &amp;, Qt::FindChildOptions ) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#findChildren-2">findChildren</a></b></span>(const QRegularExpression &amp;, Qt::FindChildOptions ) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#flags">flags</a></b></span>(const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstracttablemodel.html#flags">flags</a></b></span>(const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#hasChildren">hasChildren</a></b></span>(const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#hasIndex">hasIndex</a></b></span>(int , int , const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#headerData">headerData</a></b></span>(int , Qt::Orientation , int ) const</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#headerData">headerData</a></b></span>(int , Qt::Orientation , int ) const : QVariant</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#headerDataChanged">headerDataChanged</a></b></span>(Qt::Orientation , int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#index">index</a></b></span>(int , int , const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstracttablemodel.html#index">index</a></b></span>(int , int , const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#indexInQuery">indexInQuery</a></b></span>(const QModelIndex &amp;) const : QModelIndex</li> </ul></td><td class="topAlign"><ul> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#inherits">inherits</a></b></span>(const char *) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#insertColumn">insertColumn</a></b></span>(int , const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#insertColumns">insertColumns</a></b></span>(int , int , const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#insertColumns">insertColumns</a></b></span>(int , int , const QModelIndex &amp;) : bool</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#insertRow">insertRow</a></b></span>(int , const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#insertRows">insertRows</a></b></span>(int , int , const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#installEventFilter">installEventFilter</a></b></span>(QObject *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#isSignalConnected">isSignalConnected</a></b></span>(const QMetaMethod &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#isWidgetType">isWidgetType</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#isWindowType">isWindowType</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#itemData">itemData</a></b></span>(const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#killTimer">killTimer</a></b></span>(int )</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#lastError">lastError</a></b></span>() const : QSqlError</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#layoutAboutToBeChanged">layoutAboutToBeChanged</a></b></span>(const QList&lt;QPersistentModelIndex&gt; &amp;, QAbstractItemModel::LayoutChangeHint )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#layoutChanged">layoutChanged</a></b></span>(const QList&lt;QPersistentModelIndex&gt; &amp;, QAbstractItemModel::LayoutChangeHint )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#match">match</a></b></span>(const QModelIndex &amp;, int , const QVariant &amp;, int , Qt::MatchFlags ) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#metaObject">metaObject</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#mimeData">mimeData</a></b></span>(const QModelIndexList &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#mimeTypes">mimeTypes</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#modelAboutToBeReset">modelAboutToBeReset</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#modelReset">modelReset</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#moveColumn">moveColumn</a></b></span>(const QModelIndex &amp;, int , const QModelIndex &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#moveColumns">moveColumns</a></b></span>(const QModelIndex &amp;, int , int , const QModelIndex &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#moveRow">moveRow</a></b></span>(const QModelIndex &amp;, int , const QModelIndex &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#moveRows">moveRows</a></b></span>(const QModelIndex &amp;, int , int , const QModelIndex &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#moveToThread">moveToThread</a></b></span>(QThread *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#objectName-prop">objectName</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#objectNameChanged">objectNameChanged</a></b></span>(const QString &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#parent">parent</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#parent">parent</a></b></span>(const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#persistentIndexList">persistentIndexList</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#property">property</a></b></span>(const char *) const</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#query">query</a></b></span>() const : QSqlQuery</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#queryChange">queryChange</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#receivers">receivers</a></b></span>(const char *) const</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#record">record</a></b></span>(int ) const : QSqlRecord</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#record-1">record</a></b></span>() const : QSqlRecord</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#removeColumn">removeColumn</a></b></span>(int , const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#removeColumns">removeColumns</a></b></span>(int , int , const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#removeColumns">removeColumns</a></b></span>(int , int , const QModelIndex &amp;) : bool</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#removeEventFilter">removeEventFilter</a></b></span>(QObject *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#removeRow">removeRow</a></b></span>(int , const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#removeRows">removeRows</a></b></span>(int , int , const QModelIndex &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#resetInternalData">resetInternalData</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#revert">revert</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#roleNames">roleNames</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowCount">rowCount</a></b></span>(const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#rowCount">rowCount</a></b></span>(const QModelIndex &amp;) const : int</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsAboutToBeInserted">rowsAboutToBeInserted</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsAboutToBeMoved">rowsAboutToBeMoved</a></b></span>(const QModelIndex &amp;, int , int , const QModelIndex &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsAboutToBeRemoved">rowsAboutToBeRemoved</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsInserted">rowsInserted</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsMoved">rowsMoved</a></b></span>(const QModelIndex &amp;, int , int , const QModelIndex &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsRemoved">rowsRemoved</a></b></span>(const QModelIndex &amp;, int , int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#sender">sender</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#senderSignalIndex">senderSignalIndex</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#setData">setData</a></b></span>(const QModelIndex &amp;, const QVariant &amp;, int )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#setHeaderData">setHeaderData</a></b></span>(int , Qt::Orientation , const QVariant &amp;, int )</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#setHeaderData">setHeaderData</a></b></span>(int , Qt::Orientation , const QVariant &amp;, int ) : bool</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#setItemData">setItemData</a></b></span>(const QModelIndex &amp;, const QMap&lt;int, QVariant&gt; &amp;)</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#setLastError">setLastError</a></b></span>(const QSqlError &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#objectName-prop">setObjectName</a></b></span>(const QString &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#setParent">setParent</a></b></span>(QObject *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#setProperty">setProperty</a></b></span>(const char *, const QVariant &amp;)</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#setQuery">setQuery</a></b></span>(const QSqlQuery &amp;)</li> <li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#setQuery-1">setQuery</a></b></span>(const QString &amp;, const QSqlDatabase &amp;)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#sibling">sibling</a></b></span>(int , int , const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstracttablemodel.html#sibling">sibling</a></b></span>(int , int , const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#signalsBlocked">signalsBlocked</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#sort">sort</a></b></span>(int , Qt::SortOrder )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#span">span</a></b></span>(const QModelIndex &amp;) const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#startTimer">startTimer</a></b></span>(int , Qt::TimerType )</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#staticMetaObject-var">staticMetaObject</a></b></span> : </li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#staticQtMetaObject-var">staticQtMetaObject</a></b></span> : </li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#submit">submit</a></b></span>()</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#supportedDragActions">supportedDragActions</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#supportedDropActions">supportedDropActions</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#thread">thread</a></b></span>() const</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#timerEvent">timerEvent</a></b></span>(QTimerEvent *)</li> <li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#tr">tr</a></b></span>(const char *, const char *, int )</li> </ul> </td></tr> </table></div> </div> </div> </div> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners.<br> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.<br> Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. </p> </div> </body> </html>
Java
import { ATTENDANCE_STATUS_CONFIG_ID, AttendanceStatusType, NullAttendanceStatusType, } from "./attendance-status"; import { DatabaseField } from "../../../core/entity/database-field.decorator"; /** * Simple relationship object to represent an individual child's status at an event including context information. */ export class EventAttendance { private _status: AttendanceStatusType; @DatabaseField({ dataType: "configurable-enum", innerDataType: ATTENDANCE_STATUS_CONFIG_ID, }) get status(): AttendanceStatusType { return this._status; } set status(value) { if (typeof value === "object") { this._status = value; } else { this._status = NullAttendanceStatusType; } } @DatabaseField() remarks: string; constructor( status: AttendanceStatusType = NullAttendanceStatusType, remarks: string = "" ) { this.status = status; this.remarks = remarks; } }
Java
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue'; import BootstrapVue from 'bootstrap-vue'; import 'bootstrap-vue/dist/bootstrap-vue.css'; import 'bootstrap/dist/css/bootstrap.css'; import { mapActions } from 'vuex'; import App from './App'; import websock from './websock'; import * as mtype from './store/mutation-types'; import store from './store'; Vue.config.productionTip = false; Vue.use(BootstrapVue); /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App/>', store, components: { App }, created() { websock.connect(message => this.newMessage(message)); setInterval(() => { store.commit(mtype.UPDATE_CALLS_DUR); }, 1000); }, methods: mapActions(['newMessage']), });
Java
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - Surname - RAINSFORD</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li class = "CurrentSection"><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../families.html" title="Families">Families</a></li> <li><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="SurnameDetail"> <h3>RAINSFORD</h3> <p id="description"> This page contains an index of all the individuals in the database with the surname of RAINSFORD. Selecting the person&#8217;s name will take you to that person&#8217;s individual page. </p> <table class="infolist primobjlist surname"> <thead> <tr> <th class="ColumnName">Given Name</th> <th class="ColumnDate">Birth</th> <th class="ColumnDate">Death</th> <th class="ColumnPartner">Partner</th> <th class="ColumnParents">Parents</th> </tr> </thead> <tbody> <tr> <td class="ColumnName"> <a href="../../../ppl/b/1/d15f5fe0c5b127625ca75ac491b.html">Margaret<span class="grampsid"> [I3099]</span></a> </td> <td class="ColumnBirth">&nbsp;</td> <td class="ColumnDeath">&nbsp;</td> <td class="ColumnPartner"> <a href="../../../ppl/3/1/d15f5fe0c4a27430484a60d8013.html">GROVES, Henry<span class="grampsid"> [I3098]</span></a> </td> <td class="ColumnParents">&nbsp;</td> </tr> </tbody> </table> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:14<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
Java
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/> <meta charset="utf-8"/> <title> &raquo; Deprecated elements </title> <meta name="author" content=""/> <meta name="description" content=""/> <link href="../css/bootstrap-combined.no-icons.min.css" rel="stylesheet"> <link href="../css/font-awesome.min.css" rel="stylesheet"> <link href="../css/prism.css" rel="stylesheet" media="all"/> <link href="../css/template.css" rel="stylesheet" media="all"/> <!--[if lt IE 9]> <script src="../js/html5.js"></script> <![endif]--> <script src="../js/jquery-1.11.0.min.js"></script> <script src="../js/ui/1.10.4/jquery-ui.min.js"></script> <script src="../js/bootstrap.min.js"></script> <script src="../js/jquery.smooth-scroll.js"></script> <script src="../js/prism.min.js"></script> <!-- TODO: Add http://jscrollpane.kelvinluck.com/ to style the scrollbars for browsers not using webkit--> <link rel="shortcut icon" href="../images/favicon.ico"/> <link rel="apple-touch-icon" href="../images/apple-touch-icon.png"/> <link rel="apple-touch-icon" sizes="72x72" href="../images/apple-touch-icon-72x72.png"/> <link rel="apple-touch-icon" sizes="114x114" href="../images/apple-touch-icon-114x114.png"/> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <i class="icon-ellipsis-vertical"></i> </a> <a class="brand" href="../index.html">DataUtilities</a> <div class="nav-collapse"> <ul class="nav pull-right"> <li class="dropdown"> <a href="../index.html" class="dropdown-toggle" data-toggle="dropdown"> API Documentation <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="../namespaces/Battis.html">\Battis</a></li> </ul> </li> <li class="dropdown" id="charts-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> Charts <b class="caret"></b> </a> <ul class="dropdown-menu"> <li> <a href="../graphs/class.html"> <i class="icon-list-alt"></i>&#160;Class hierarchy diagram </a> </li> </ul> </li> <li class="dropdown" id="reports-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> Reports <b class="caret"></b> </a> <ul class="dropdown-menu"> <li> <a href="../reports/errors.html"> <i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">0</span> </a> </li> <li> <a href="../reports/markers.html"> <i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">2</span> </a> </li> <li> <a href="../reports/deprecated.html"> <i class="icon-list-alt"></i>&#160;Deprecated <span class="label label-info pull-right">0</span> </a> </li> </ul> </li> </ul> </div> </div> </div> <!--<div class="go_to_top">--> <!--<a href="#___" style="color: inherit">Back to top&#160;&#160;<i class="icon-upload icon-white"></i></a>--> <!--</div>--> </div> <div id="___" class="container-fluid"> <div class="row-fluid"> <div class="span2 sidebar"> <ul class="side-nav nav nav-list"> <li class="nav-header">Navigation</li> </ul> </div> <div class="span10 offset2"> <ul class="breadcrumb"> <li><a href="../"><i class="icon-remove-sign"></i></a><span class="divider">\</span></li> <li>Deprecated elements</li> </ul> <div id="marker-accordion"> <div class="alert alert-info">No deprecated elements have been found in this project.</div> </table> </div> </div> </div> </div> <footer class="row-fluid"> <section class="span10 offset2"> <section class="row-fluid"> <section class="span10 offset1"> <section class="row-fluid footer-sections"> <section class="span4"> <h1><i class="icon-code"></i></h1> <div> <ul> <li><a href="../namespaces/Battis.html">\Battis</a></li> </ul> </div> </section> <section class="span4"> <h1><i class="icon-bar-chart"></i></h1> <div> <ul> <li><a href="../graphs/class.html">Class Hierarchy Diagram</a></li> </ul> </div> </section> <section class="span4"> <h1><i class="icon-pushpin"></i></h1> <div> <ul> <li><a href="../reports/errors.html">Errors</a></li> <li><a href="../reports/markers.html">Markers</a></li> </ul> </div> </section> </section> </section> </section> <section class="row-fluid"> <section class="span10 offset1"> <hr /> Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored on May 29th, 2017 at 14:17. </section> </section> </section> </footer> </div> </body> </html>
Java
#include "hal/time/time.hpp" namespace hal { namespace time { static u64 currentTime = 0; u64 milliseconds() { return currentTime; } } // namespace time } // namespace hal namespace stub { namespace time { void setCurrentTime(u64 milliseconds) { hal::time::currentTime = milliseconds; } void forwardTime(u64 milliseconds) { hal::time::currentTime += milliseconds; } } // namespace time } // namespace stub
Java
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * @package backup-convert * @subpackage cc-library * @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once 'cc_utils.php'; require_once 'cc_version_base.php'; require_once 'cc_organization.php'; /** * Version 1 class of Common Cartridge * */ class cc_version1 extends cc_version_base { const webcontent = 'webcontent'; const questionbank = 'imsqti_xmlv1p2/imscc_xmlv1p0/question-bank'; const assessment = 'imsqti_xmlv1p2/imscc_xmlv1p0/assessment'; const associatedcontent = 'associatedcontent/imscc_xmlv1p0/learning-application-resource'; const discussiontopic = 'imsdt_xmlv1p0'; const weblink = 'imswl_xmlv1p0'; public static $checker = array(self::webcontent, self::assessment, self::associatedcontent, self::discussiontopic, self::questionbank, self::weblink); /** * Validate if the type are valid or not * * @param string $type * @return bool */ public function valid($type) { return in_array($type, self::$checker); } public function __construct() { $this->ccnamespaces = array('imscc' => 'http://www.imsglobal.org/xsd/imscc/imscp_v1p1', 'lomimscc' => 'http://ltsc.ieee.org/xsd/imscc/LOM', 'lom' => 'http://ltsc.ieee.org/xsd/LOM', 'voc' => 'http://ltsc.ieee.org/xsd/LOM/vocab', 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance' ); $this->ccnsnames = array('imscc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/imscp_v1p2_localised.xsd' , 'lom' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_2/lomLoose_localised.xsd' , 'lomimscc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_1/lomLoose_localised.xsd', 'voc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_2/vocab/loose.xsd' ); $this->ccversion = '1.0.0'; $this->camversion = '1.0.0'; $this->_generator = 'Moodle 2 Common Cartridge generator'; } protected function on_create(DOMDocument &$doc, $rootmanifestnode=null,$nmanifestID=null) { $doc->formatOutput = true; $doc->preserveWhiteSpace = true; $this->manifestID = is_null($nmanifestID) ? cc_helpers::uuidgen('M_') : $nmanifestID; $mUUID = $doc->createAttribute('identifier'); $mUUID->nodeValue = $this->manifestID; if (is_null($rootmanifestnode)) { if (!empty($this->_generator)) { $comment = $doc->createComment($this->_generator); $doc->appendChild($comment); } $rootel = $doc->createElementNS($this->ccnamespaces['imscc'],'manifest'); $rootel->appendChild($mUUID); $doc->appendChild($rootel); //add all namespaces foreach ($this->ccnamespaces as $key => $value) { if ($key != 'lom' ){ $dummy_attr = $key.":dummy"; $doc->createAttributeNS($value,$dummy_attr); } } // add location of schemas $schemaLocation=''; foreach ($this->ccnsnames as $key => $value) { $vt = empty($schemaLocation) ? '' : ' '; $schemaLocation .= $vt.$this->ccnamespaces[$key].' '.$value; } $aSchemaLoc = $doc->createAttributeNS($this->ccnamespaces['xsi'],'xsi:schemaLocation'); $aSchemaLoc->nodeValue=$schemaLocation; $rootel->appendChild($aSchemaLoc); } else { $rootel = $doc->createElementNS($this->ccnamespaces['imscc'],'imscc:manifest'); $rootel->appendChild($mUUID); } $metadata = $doc->createElementNS($this->ccnamespaces['imscc'],'metadata'); $schema = $doc->createElementNS($this->ccnamespaces['imscc'],'schema','IMS Common Cartridge'); $schemaversion = $doc->createElementNS($this->ccnamespaces['imscc'],'schemaversion',$this->ccversion); $metadata->appendChild($schema); $metadata->appendChild($schemaversion); $rootel->appendChild($metadata); if (!is_null($rootmanifestnode)) { $rootmanifestnode->appendChild($rootel); } $organizations = $doc->createElementNS($this->ccnamespaces['imscc'],'organizations'); $rootel->appendChild($organizations); $resources = $doc->createElementNS($this->ccnamespaces['imscc'],'resources'); $rootel->appendChild($resources); return true; } protected function update_attribute(DOMDocument &$doc, $attrname, $attrvalue, DOMElement &$node) { $busenew = (is_object($node) && $node->hasAttribute($attrname)); $nResult = null; if (!$busenew && is_null($attrvalue)) { $node->removeAttribute($attrname); } else { $nResult = $busenew ? $node->getAttributeNode($attrname) : $doc->createAttribute($attrname); $nResult->nodeValue = $attrvalue; if (!$busenew) { $node->appendChild($nResult); } } return $nResult; } protected function update_attribute_ns(DOMDocument &$doc, $attrname, $attrnamespace,$attrvalue, DOMElement &$node) { $busenew = (is_object($node) && $node->hasAttributeNS($attrnamespace, $attrname)); $nResult = null; if (!$busenew && is_null($attrvalue)) { $node->removeAttributeNS($attrnamespace, $attrname); } else { $nResult = $busenew ? $node->getAttributeNodeNS($attrnamespace, $attrname) : $doc->createAttributeNS($attrnamespace, $attrname); $nResult->nodeValue = $attrvalue; if (!$busenew) { $node->appendChild($nResult); } } return $nResult; } protected function get_child_node(DOMDocument &$doc, $itemname, DOMElement &$node) { $nlist = $node->getElementsByTagName($itemname); $item = is_object($nlist) && ($nlist->length > 0) ? $nlist->item(0) : null; return $item; } protected function update_child_item(DOMDocument &$doc, $itemname, $itemvalue, DOMElement &$node, $attrtostore=null) { $tnode = $this->get_child_node($doc,'title',$node); $usenew = is_null($tnode); $tnode = $usenew ? $doc->createElementNS($this->ccnamespaces['imscc'], $itemname) : $tnode; if (!is_null($attrtostore)) { foreach ($attrtostore as $key => $value) { $this->update_attribute($doc,$key,$value,$tnode); } } $tnode->nodeValue = $itemvalue; if ($usenew) { $node->appendChild($tnode); } } protected function update_items($items, DOMDocument &$doc, DOMElement &$xmlnode) { foreach ($items as $key => $item) { $itemnode = $doc->createElementNS($this->ccnamespaces['imscc'], 'item'); $this->update_attribute($doc, 'identifier' , $key , $itemnode); $this->update_attribute($doc, 'identifierref', $item->identifierref, $itemnode); $this->update_attribute($doc, 'parameters' , $item->parameters , $itemnode); if (!empty($item->title)) { $titlenode = $doc->createElementNS($this->ccnamespaces['imscc'], 'title', $item->title); $itemnode->appendChild($titlenode); } if ($item->has_child_items()) { $this->update_items($item->childitems, $doc, $itemnode); } $xmlnode->appendChild($itemnode); } } /** * Create a Resource (How to) * * @param cc_i_resource $res * @param DOMDocument $doc * @param object $xmlnode * @return DOMNode */ protected function create_resource(cc_i_resource &$res, DOMDocument &$doc, $xmlnode=null) { $usenew = is_object($xmlnode); $dnode = $usenew ? $xmlnode : $doc->createElementNS($this->ccnamespaces['imscc'], "resource"); $this->update_attribute($doc,'identifier',$res->identifier,$dnode); $this->update_attribute($doc,'type' ,$res->type ,$dnode); !is_null($res->href) ? $this->update_attribute($doc,'href',$res->href,$dnode): null; $this->update_attribute($doc,'base' ,$res->base ,$dnode); foreach ($res->files as $file) { $nd = $doc->createElementNS($this->ccnamespaces['imscc'],'file'); $ndatt = $doc->createAttribute('href'); $ndatt->nodeValue = $file; $nd->appendChild($ndatt); $dnode->appendChild($nd); } $this->resources[$res->identifier] = $res; foreach ($res->dependency as $dependency){ $nd = $doc->createElementNS($this->ccnamespaces['imscc'],'dependency'); $ndatt = $doc->createAttribute('identifierref'); $ndatt->nodeValue = $dependency; $nd->appendChild($ndatt); $dnode->appendChild($nd); } return $dnode; } /** * Create an Item Folder (How To) * * @param cc_i_organization $org * @param DOMDocument $doc * @param DOMElement $xmlnode */ protected function create_item_folder (cc_i_organization &$org, DOMDocument &$doc, DOMElement &$xmlnode=null){ $itemfoldernode = $doc->createElementNS($this->ccnamespaces['imscc'],'item'); $this->update_attribute($doc,'identifier', "root", $itemfoldernode); if ($org->has_items()) { $this->update_items($org->itemlist, $doc, $itemfoldernode); } if (is_null($this->organizations)) { $this->organizations = array(); } $this->organizations[$org->identifier] = $org; $xmlnode->appendChild($itemfoldernode); } /** * Create an Organization (How To) * * @param cc_i_organization $org * @param DOMDocument $doc * @param object $xmlnode * @return DOMNode */ protected function create_organization (cc_i_organization &$org, DOMDocument &$doc, $xmlnode=null){ $usenew = is_object($xmlnode); $dnode = $usenew ? $xmlnode : $doc->createElementNS($this->ccnamespaces['imscc'], "organization"); $this->update_attribute($doc,'identifier' ,$org->identifier,$dnode); $this->update_attribute($doc,'structure' ,$org->structure ,$dnode); $this->create_item_folder($org,$doc,$dnode); return $dnode; } /** * Create Metadata For Manifest (How To) * * @param cc_i_metadata_manifest $met * @param DOMDocument $doc * @param object $xmlnode * @return DOMNode */ protected function create_metadata_manifest (cc_i_metadata_manifest $met,DOMDocument &$doc,$xmlnode=null) { $dnode = $doc->createElementNS($this->ccnamespaces['lomimscc'], "lom"); if (!empty($xmlnode)) { $xmlnode->appendChild($dnode); } $dnodegeneral = empty($met->arraygeneral ) ? null : $this->create_metadata_general ($met, $doc, $xmlnode); $dnodetechnical = empty($met->arraytech ) ? null : $this->create_metadata_technical($met, $doc, $xmlnode); $dnoderights = empty($met->arrayrights ) ? null : $this->create_metadata_rights ($met, $doc, $xmlnode); $dnodelifecycle = empty($met->arraylifecycle) ? null : $this->create_metadata_lifecycle($met, $doc, $xmlnode); !is_null($dnodegeneral)?$dnode->appendChild($dnodegeneral):null; !is_null($dnodetechnical)?$dnode->appendChild($dnodetechnical):null; !is_null($dnoderights)?$dnode->appendChild($dnoderights):null; !is_null($dnodelifecycle)?$dnode->appendChild($dnodelifecycle):null; return $dnode; } /** * Create Metadata For Resource (How To) * * @param cc_i_metadata_resource $met * @param DOMDocument $doc * @param object $xmlnode * @return DOMNode */ protected function create_metadata_resource (cc_i_metadata_resource $met,DOMDocument &$doc,$xmlnode=null) { $dnode = $doc->createElementNS($this->ccnamespaces['lom'], "lom"); !empty($xmlnode)? $xmlnode->appendChild($dnode):null; !empty($met->arrayeducational) ? $this->create_metadata_educational($met,$doc,$dnode):null; return $dnode; } /** * Create Metadata For File (How To) * * @param cc_i_metadata_file $met * @param DOMDocument $doc * @param Object $xmlnode * @return DOMNode */ protected function create_metadata_file (cc_i_metadata_file $met,DOMDocument &$doc,$xmlnode=null) { $dnode = $doc->createElementNS($this->ccnamespaces['lom'], "lom"); !empty($xmlnode)? $xmlnode->appendChild($dnode):null; !empty($met->arrayeducational) ? $this->create_metadata_educational($met,$doc,$dnode):null; return $dnode; } /** * Create General Metadata (How To) * * @param object $met * @param DOMDocument $doc * @param object $xmlnode * @return DOMNode */ protected function create_metadata_general($met,DOMDocument &$doc,$xmlnode){ ($xmlnode); $nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'general'); foreach ($met->arraygeneral as $name => $value) { !is_array($value)?$value =array($value):null; foreach ($value as $k => $v){ ($k); if ($name != 'language' && $name != 'catalog' && $name != 'entry'){ $nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name); $nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'string',$v[1]); $ndatt = $doc->createAttribute('language'); $ndatt->nodeValue = $v[0]; $nd3->appendChild($ndatt); $nd2->appendChild($nd3); $nd->appendChild($nd2); }else{ if ($name == 'language'){ $nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name,$v[0]); $nd->appendChild($nd2); } } } } if (!empty($met->arraygeneral['catalog']) || !empty($met->arraygeneral['entry'])){ $nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'identifier'); $nd->appendChild($nd2); if (!empty($met->arraygeneral['catalog'])){ $nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'catalog',$met->arraygeneral['catalog'][0][0]); $nd2->appendChild($nd3); } if (!empty($met->arraygeneral['entry'])){ $nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'entry',$met->arraygeneral['entry'][0][0]); $nd2->appendChild($nd4); } } return $nd; } /** * Create Technical Metadata (How To) * * @param object $met * @param DOMDocument $doc * @param object $xmlnode * @return DOMNode */ protected function create_metadata_technical($met,DOMDocument &$doc,$xmlnode){ ($xmlnode); $nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'technical'); $xmlnode->appendChild($nd); foreach ($met->arraytech as $name => $value) { ($name); !is_array($value)?$value =array($value):null; foreach ($value as $k => $v){ ($k); $nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name,$v[0]); $nd->appendChild($nd2); } } return $nd; } /** * Create Rights Metadata (How To) * * @param object $met * @param DOMDocument $doc * @param object $xmlnode * @return DOMNode */ protected function create_metadata_rights($met,DOMDocument &$doc,$xmlnode){ ($xmlnode); $nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'rights'); foreach ($met->arrayrights as $name => $value) { !is_array($value)?$value =array($value):null; foreach ($value as $k => $v){ ($k); if ($name == 'description'){ $nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name); $nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'string',$v[1]); $ndatt = $doc->createAttribute('language'); $ndatt->nodeValue = $v[0]; $nd3->appendChild($ndatt); $nd2->appendChild($nd3); $nd->appendChild($nd2); }elseif ($name == 'copyrightAndOtherRestrictions' || $name == 'cost'){ $nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name); $nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'value',$v[0]); $nd2->appendChild($nd3); $nd->appendChild($nd2); } } } return $nd; } /** * Create LifeCyle Metadata (How To) * * @param object $met * @param DOMDocument $doc * @param object $xmlnode * @return DOMNode */ protected function create_metadata_lifecycle($met,DOMDocument &$doc,$xmlnode){ ($xmlnode); $nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'lifeCycle'); $nd2= $doc->createElementNS($this->ccnamespaces['lomimscc'],'contribute'); $nd->appendChild ($nd2); $xmlnode->appendChild ($nd); foreach ($met->arraylifecycle as $name => $value) { !is_array($value)?$value =array($value):null; foreach ($value as $k => $v){ ($k); if ($name == 'role'){ $nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name); $nd2->appendChild($nd3); $nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'value',$v[0]); $nd3->appendChild($nd4); }else{ if ($name == 'date'){ $nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name); $nd2->appendChild($nd3); $nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'dateTime',$v[0]); $nd3->appendChild($nd4); }else{ $nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name,$v[0]); $nd2->appendChild($nd3); } } } } return $nd; } /** * Create Education Metadata (How To) * * @param object $met * @param DOMDocument $doc * @param object $xmlnode * @return DOMNode */ protected function create_metadata_educational ($met,DOMDocument &$doc, $xmlnode){ $nd = $doc->createElementNS($this->ccnamespaces['lom'],'educational'); $nd2 = $doc->createElementNS($this->ccnamespaces['lom'],'intendedEndUserRole'); $nd3 = $doc->createElementNS($this->ccnamespaces['voc'],'vocabulary'); $xmlnode->appendChild($nd); $nd->appendChild($nd2); $nd2->appendChild($nd3); foreach ($met->arrayeducational as $name => $value) { !is_array($value)?$value =array($value):null; foreach ($value as $k => $v){ ($k); $nd4 = $doc->createElementNS($this->ccnamespaces['voc'],$name,$v[0]); $nd3->appendChild($nd4); } } return $nd; } }
Java
package com.programandoapasitos.facturador.gui; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JLabel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import com.programandoapasitos.facturador.gui.superclases.FramePadre; import com.programandoapasitos.facturador.utiles.ManejadorProperties; @SuppressWarnings("serial") public class MenuPrincipal extends FramePadre { // Propiedades private JLabel lblIcono; private JMenuBar menuBar; private JMenu mnClientes; private JMenu mnFacturas; private JMenuItem mntmNuevaFactura; private JMenuItem mntmNuevoCliente; private JMenuItem mntmBuscarFactura; private JMenuItem mntmBuscarCliente; // Constructor public MenuPrincipal(int ancho, int alto, String titulo) { super(ancho, alto, titulo); this.inicializar(); } // Métodos public void inicializar() { this.inicializarMenuBar(); this.iniciarLabels(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Sobrescribe setDefaultCloseOperation de FramePadre setVisible(true); } public void inicializarMenuBar() { menuBar = new JMenuBar(); menuBar.setBounds(0, 0, 900, 21); this.panel.add(menuBar); this.inicializarMenuFacturas(); this.inicializarMenuClientes(); } /** * Initialize submenu Bills */ public void inicializarMenuFacturas() { mnFacturas = new JMenu(ManejadorProperties.verLiteral("MENU_FACTURAS")); menuBar.add(mnFacturas); mntmNuevaFactura = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_NEW_BILL")); mntmNuevaFactura.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { new FrameNuevaFactura(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_NEW_BILL")); } }); mnFacturas.add(mntmNuevaFactura); mntmBuscarFactura = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_BILL")); mntmBuscarFactura.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new FrameBuscarFacturas(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_BILL")); } }); mnFacturas.add(mntmBuscarFactura); } public void inicializarMenuClientes() { mnClientes = new JMenu(ManejadorProperties.verLiteral("MENU_CLIENTES")); menuBar.add(mnClientes); mntmNuevoCliente = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_NEW_CLIENT")); mntmNuevoCliente.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new FrameNuevoCliente(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_NEW_CLIENT")); } }); mnClientes.add(mntmNuevoCliente); mntmBuscarCliente = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_CLIENT")); mntmBuscarCliente.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { new FrameBuscarClientes(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_CLIENT")); } }); mnClientes.add(mntmBuscarCliente); } /** * Initialize icon label */ public void iniciarLabels() { lblIcono = new JLabel(""); lblIcono.setIcon(new ImageIcon(ManejadorProperties.verRuta("MENU_ITEM_SEARCH_CLIENT"))); lblIcono.setBounds(342, 240, 210, 124); this.panel.add(lblIcono); } }
Java
# Sweep with the pawns This rule will have all pawns sweep the board, trying to defeat as many pieces as possible. We will assume we have all pawns in the front row. The idea is to have them all stay in a row: first, they will all advance to row 2, then to row 3, and so on, without breaking formation. ``` (defrule EQUIPO-A::advance_pawns_f2 (declare (salience 60)) (tiempo ?t) (ficha (equipo "A") (num ?n) (pos-y 2) (puntos 2)) => (assert (mueve (num ?n) (mov 3) (tiempo ?t))) ) (defrule EQUIPO-A::advance_pawns_f3 (declare (salience 59)) (tiempo ?t) (ficha (equipo "A") (num ?n) (pos-y 3) (puntos 2)) => (assert (mueve (num ?n) (mov 3) (tiempo ?t))) ) (defrule EQUIPO-A::advance_pawns_f4 (declare (salience 58)) (tiempo ?t) (ficha (equipo "A") (num ?n) (pos-y 4) (puntos 2)) => (assert (mueve (num ?n) (mov 3) (tiempo ?t))) ) (defrule EQUIPO-A::advance_pawns_f5 (declare (salience 57)) (tiempo ?t) (ficha (equipo "A") (num ?n) (pos-y 5) (puntos 2)) => (assert (mueve (num ?n) (mov 3) (tiempo ?t))) ) (defrule EQUIPO-A::advance_pawns_f6 (declare (salience 56)) (tiempo ?t) (ficha (equipo "A") (num ?n) (pos-y 6) (puntos 2)) => (assert (mueve (num ?n) (mov 3) (tiempo ?t))) ) (defrule EQUIPO-A::advance_pawns_f7 (declare (salience 55)) (tiempo ?t) (ficha (equipo "A") (num ?n) (pos-y 7) (puntos 2)) => (assert (mueve (num ?n) (mov 3) (tiempo ?t))) ) ``` There is a rule for each piece, since doing it in a more parametric form would increase the complexity significantly. This also allows for tweaking the priority, changing the order in which pawns advance to the next row.
Java
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ #include "common.h" #include "seafile-session.h" #include "bloom-filter.h" #include "gc-core.h" #include "utils.h" #define DEBUG_FLAG SEAFILE_DEBUG_OTHER #include "log.h" #define MAX_BF_SIZE (((size_t)1) << 29) /* 64 MB */ /* Total number of blocks to be scanned. */ static guint64 total_blocks; static guint64 removed_blocks; static guint64 reachable_blocks; /* * The number of bits in the bloom filter is 4 times the number of all blocks. * Let m be the bits in the bf, n be the number of blocks to be added to the bf * (the number of live blocks), and k = 3 (closed to optimal for m/n = 4), * the probability of false-positive is * * p = (1 - e^(-kn/m))^k = 0.15 * * Because m = 4 * total_blocks >= 4 * (live blocks) = 4n, we should have p <= 0.15. * Put it another way, we'll clean up at least 85% dead blocks in each gc operation. * See http://en.wikipedia.org/wiki/Bloom_filter. * * Supose we have 8TB space, and the avg block size is 1MB, we'll have 8M blocks, then * the size of bf is (8M * 4)/8 = 4MB. * * If total_blocks is a small number (e.g. < 100), we should try to clean all dead blocks. * So we set the minimal size of the bf to 1KB. */ static Bloom * alloc_gc_index () { size_t size; size = (size_t) MAX(total_blocks << 2, 1 << 13); size = MIN (size, MAX_BF_SIZE); seaf_message ("GC index size is %u Byte.\n", (int)size >> 3); return bloom_create (size, 3, 0); } typedef struct { SeafRepo *repo; Bloom *index; GHashTable *visited; /* > 0: keep a period of history; * == 0: only keep data in head commit; * < 0: keep all history data. */ gint64 truncate_time; gboolean traversed_head; int traversed_commits; gint64 traversed_blocks; gboolean ignore_errors; } GCData; static int add_blocks_to_index (SeafFSManager *mgr, GCData *data, const char *file_id) { SeafRepo *repo = data->repo; Bloom *index = data->index; Seafile *seafile; int i; seafile = seaf_fs_manager_get_seafile (mgr, repo->store_id, repo->version, file_id); if (!seafile) { seaf_warning ("Failed to find file %s.\n", file_id); return -1; } for (i = 0; i < seafile->n_blocks; ++i) { bloom_add (index, seafile->blk_sha1s[i]); ++data->traversed_blocks; } seafile_unref (seafile); return 0; } static gboolean fs_callback (SeafFSManager *mgr, const char *store_id, int version, const char *obj_id, int type, void *user_data, gboolean *stop) { GCData *data = user_data; if (data->visited != NULL) { if (g_hash_table_lookup (data->visited, obj_id) != NULL) { *stop = TRUE; return TRUE; } char *key = g_strdup(obj_id); g_hash_table_insert (data->visited, key, key); } if (type == SEAF_METADATA_TYPE_FILE && add_blocks_to_index (mgr, data, obj_id) < 0) return FALSE; return TRUE; } static gboolean traverse_commit (SeafCommit *commit, void *vdata, gboolean *stop) { GCData *data = vdata; int ret; if (data->truncate_time == 0) { *stop = TRUE; /* Stop after traversing the head commit. */ } else if (data->truncate_time > 0 && (gint64)(commit->ctime) < data->truncate_time && data->traversed_head) { /* Still traverse the first commit older than truncate_time. * If a file in the child commit of this commit is deleted, * we need to access this commit in order to restore it * from trash. */ *stop = TRUE; } if (!data->traversed_head) data->traversed_head = TRUE; seaf_debug ("Traversed commit %.8s.\n", commit->commit_id); ++data->traversed_commits; ret = seaf_fs_manager_traverse_tree (seaf->fs_mgr, data->repo->store_id, data->repo->version, commit->root_id, fs_callback, data, data->ignore_errors); if (ret < 0 && !data->ignore_errors) return FALSE; return TRUE; } static int populate_gc_index_for_repo (SeafRepo *repo, Bloom *index, gboolean ignore_errors) { GList *branches, *ptr; SeafBranch *branch; GCData *data; int ret = 0; seaf_message ("Populating index for repo %.8s.\n", repo->id); branches = seaf_branch_manager_get_branch_list (seaf->branch_mgr, repo->id); if (branches == NULL) { seaf_warning ("[GC] Failed to get branch list of repo %s.\n", repo->id); return -1; } data = g_new0(GCData, 1); data->repo = repo; data->index = index; data->visited = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); gint64 truncate_time = seaf_repo_manager_get_repo_truncate_time (repo->manager, repo->id); if (truncate_time > 0) { seaf_repo_manager_set_repo_valid_since (repo->manager, repo->id, truncate_time); } else if (truncate_time == 0) { /* Only the head commit is valid after GC if no history is kept. */ SeafCommit *head = seaf_commit_manager_get_commit (seaf->commit_mgr, repo->id, repo->version, repo->head->commit_id); if (head) seaf_repo_manager_set_repo_valid_since (repo->manager, repo->id, head->ctime); seaf_commit_unref (head); } data->truncate_time = truncate_time; data->ignore_errors = ignore_errors; for (ptr = branches; ptr != NULL; ptr = ptr->next) { branch = ptr->data; gboolean res = seaf_commit_manager_traverse_commit_tree (seaf->commit_mgr, repo->id, repo->version, branch->commit_id, traverse_commit, data, ignore_errors); seaf_branch_unref (branch); if (!res && !ignore_errors) { ret = -1; break; } } seaf_message ("Traversed %d commits, %"G_GINT64_FORMAT" blocks.\n", data->traversed_commits, data->traversed_blocks); reachable_blocks += data->traversed_blocks; g_list_free (branches); g_hash_table_destroy (data->visited); g_free (data); return ret; } typedef struct { Bloom *index; int dry_run; } CheckBlocksData; static gboolean check_block_liveness (const char *store_id, int version, const char *block_id, void *vdata) { CheckBlocksData *data = vdata; Bloom *index = data->index; if (!bloom_test (index, block_id)) { ++removed_blocks; if (!data->dry_run) seaf_block_manager_remove_block (seaf->block_mgr, store_id, version, block_id); } return TRUE; } static int populate_gc_index_for_virtual_repos (SeafRepo *repo, Bloom *index, int ignore_errors) { GList *vrepo_ids = NULL, *ptr; char *repo_id; SeafRepo *vrepo; int ret = 0; vrepo_ids = seaf_repo_manager_get_virtual_repo_ids_by_origin (seaf->repo_mgr, repo->id); for (ptr = vrepo_ids; ptr; ptr = ptr->next) { repo_id = ptr->data; vrepo = seaf_repo_manager_get_repo (seaf->repo_mgr, repo_id); if (!vrepo) { seaf_warning ("Failed to get repo %s.\n", repo_id); if (!ignore_errors) { ret = -1; goto out; } else continue; } ret = populate_gc_index_for_repo (vrepo, index, ignore_errors); seaf_repo_unref (vrepo); if (ret < 0 && !ignore_errors) goto out; } out: string_list_free (vrepo_ids); return ret; } int gc_v1_repo (SeafRepo *repo, int dry_run, int ignore_errors) { Bloom *index; int ret; total_blocks = seaf_block_manager_get_block_number (seaf->block_mgr, repo->store_id, repo->version); removed_blocks = 0; reachable_blocks = 0; if (total_blocks == 0) { seaf_message ("No blocks. Skip GC.\n"); return 0; } seaf_message ("GC started. Total block number is %"G_GUINT64_FORMAT".\n", total_blocks); /* * Store the index of live blocks in bloom filter to save memory. * Since bloom filters only have false-positive, we * may skip some garbage blocks, but we won't delete * blocks that are still alive. */ index = alloc_gc_index (); if (!index) { seaf_warning ("GC: Failed to allocate index.\n"); return -1; } seaf_message ("Populating index.\n"); ret = populate_gc_index_for_repo (repo, index, ignore_errors); if (ret < 0 && !ignore_errors) goto out; /* Since virtual repos share fs and block store with the origin repo, * it's necessary to do GC for them together. */ ret = populate_gc_index_for_virtual_repos (repo, index, ignore_errors); if (ret < 0 && !ignore_errors) goto out; if (!dry_run) seaf_message ("Scanning and deleting unused blocks.\n"); else seaf_message ("Scanning unused blocks.\n"); CheckBlocksData data; data.index = index; data.dry_run = dry_run; ret = seaf_block_manager_foreach_block (seaf->block_mgr, repo->store_id, repo->version, check_block_liveness, &data); if (ret < 0) { seaf_warning ("GC: Failed to clean dead blocks.\n"); goto out; } if (!dry_run) seaf_message ("GC finished. %"G_GUINT64_FORMAT" blocks total, " "about %"G_GUINT64_FORMAT" reachable blocks, " "%"G_GUINT64_FORMAT" blocks are removed.\n", total_blocks, reachable_blocks, removed_blocks); else seaf_message ("GC finished. %"G_GUINT64_FORMAT" blocks total, " "about %"G_GUINT64_FORMAT" reachable blocks, " "%"G_GUINT64_FORMAT" blocks can be removed.\n", total_blocks, reachable_blocks, removed_blocks); out: bloom_destroy (index); return ret; } int gc_core_run (int dry_run) { GList *repos = NULL, *del_repos = NULL, *ptr; SeafRepo *repo; GList *corrupt_repos = NULL; gboolean error = FALSE; repos = seaf_repo_manager_get_repo_list (seaf->repo_mgr, -1, -1, &error); if (error) { seaf_warning ("Failed to load repo list.\n"); return -1; } for (ptr = repos; ptr; ptr = ptr->next) { repo = ptr->data; if (repo->is_corrupted) { corrupt_repos = g_list_prepend (corrupt_repos, g_strdup(repo->id)); continue; } if (!repo->is_virtual) { seaf_message ("GC version %d repo %s(%.8s)\n", repo->version, repo->name, repo->id); if (gc_v1_repo (repo, dry_run, FALSE) < 0) corrupt_repos = g_list_prepend (corrupt_repos, g_strdup(repo->id)); } seaf_repo_unref (repo); } g_list_free (repos); seaf_message ("=== GC deleted repos ===\n"); del_repos = seaf_repo_manager_list_garbage_repos (seaf->repo_mgr); for (ptr = del_repos; ptr; ptr = ptr->next) { char *repo_id = ptr->data; /* Confirm repo doesn't exist before removing blocks. */ if (!seaf_repo_manager_repo_exists (seaf->repo_mgr, repo_id)) { if (!dry_run) { seaf_message ("GC deleted repo %.8s.\n", repo_id); seaf_block_manager_remove_store (seaf->block_mgr, repo_id); } else { seaf_message ("Repo %.8s can be GC'ed.\n", repo_id); } } if (!dry_run) seaf_repo_manager_remove_garbage_repo (seaf->repo_mgr, repo_id); g_free (repo_id); } g_list_free (del_repos); seaf_message ("=== GC is finished ===\n"); if (corrupt_repos) { seaf_message ("The following repos are corrupted. " "You can run seaf-fsck to fix them.\n"); for (ptr = corrupt_repos; ptr; ptr = ptr->next) { char *repo_id = ptr->data; seaf_message ("%s\n", repo_id); g_free (repo_id); } g_list_free (corrupt_repos); } return 0; }
Java
\hypertarget{_factory_controller_8cpp}{\section{src/interfaces/\+Factory\+Controller.cpp File Reference} \label{_factory_controller_8cpp}\index{src/interfaces/\+Factory\+Controller.\+cpp@{src/interfaces/\+Factory\+Controller.\+cpp}} } {\ttfamily \#include \char`\"{}I\+Controller.\+h\char`\"{}}\\* {\ttfamily \#include $<$src/logic/controller/\+Controller.\+h$>$}\\* Include dependency graph for Factory\+Controller.\+cpp\+:
Java
<?php use Respect\Validation\Validator as DataValidator; /** * @api {post} /staff/search-tickets Search tickets * @apiVersion 4.5.0 * * @apiName Search tickets * * @apiGroup Staff * * @apiDescription This path search some tickets. * * @apiPermission staff1 * * @apiParam {String} query Query string to search. * @apiParam {Number} page The page number. * * @apiUse NO_PERMISSION * @apiUse INVALID_QUERY * @apiUse INVALID_PAGE * * @apiSuccess {Object} data Information about tickets * @apiSuccess {[Ticket](#api-Data_Structures-ObjectTicket)[]} data.tickets Array of tickets found * @apiSuccess {Number} data.pages Number of pages * */ class SearchTicketStaffController extends Controller { const PATH = '/search-tickets'; const METHOD = 'POST'; public function validations() { return[ 'permission' => 'staff_1', 'requestData' => [ 'query' => [ 'validation' => DataValidator::length(1), 'error' => ERRORS::INVALID_QUERY ], 'page' => [ 'validation' => DataValidator::numeric(), 'error' => ERRORS::INVALID_PAGE ] ] ]; } public function handler() { Response::respondSuccess([ 'tickets' => $this->getTicketList()->toArray(), 'pages' => $this->getTotalPages() ]); } private function getTicketList() { $query = $this->getSearchQuery(); return Ticket::find($query, [ Controller::request('query') . '%', '%' . Controller::request('query') . '%', Controller::request('query') . '%' ]); } private function getSearchQuery() { $page = Controller::request('page'); $query = " (title LIKE ? OR title LIKE ?) AND "; $query .= $this->getStaffDepartmentsQueryFilter(); $query .= "ORDER BY CASE WHEN (title LIKE ?) THEN 1 ELSE 2 END ASC LIMIT 10 OFFSET " . (($page-1)*10); return $query; } private function getTotalPages() { $query = " (title LIKE ? OR title LIKE ?) AND "; $query .= $this->getStaffDepartmentsQueryFilter(); $ticketQuantity = Ticket::count($query, [ Controller::request('query') . '%', '%' . Controller::request('query') . '%' ]); return ceil($ticketQuantity / 10); } private function getStaffDepartmentsQueryFilter() { $user = Controller::getLoggedUser(); $query = ' ('; foreach ($user->sharedDepartmentList as $department) { $query .= 'department_id=' . $department->id . ' OR '; } $query = substr($query, 0, -3); $query .= ') '; return $query; } }
Java
/* radare - LGPL - Copyright 2008-2014 - pancake */ // TODO: implement a more inteligent way to store cached memory // TODO: define limit of max mem to cache #include "r_io.h" static void cache_item_free(RIOCache *cache) { if (!cache) return; if (cache->data) free (cache->data); free (cache); } R_API void r_io_cache_init(RIO *io) { io->cache = r_list_new (); io->cache->free = (RListFree)cache_item_free; io->cached = R_FALSE; // cache write ops io->cached_read = R_FALSE; // cached read ops } R_API void r_io_cache_enable(RIO *io, int read, int write) { io->cached = read | write; io->cached_read = read; } R_API void r_io_cache_commit(RIO *io) { RListIter *iter; RIOCache *c; if (io->cached) { io->cached = R_FALSE; r_list_foreach (io->cache, iter, c) { if (!r_io_write_at (io, c->from, c->data, c->size)) eprintf ("Error writing change at 0x%08"PFMT64x"\n", c->from); } io->cached = R_TRUE; r_io_cache_reset (io, io->cached); } } R_API void r_io_cache_reset(RIO *io, int set) { io->cached = set; r_list_purge (io->cache); } R_API int r_io_cache_invalidate(RIO *io, ut64 from, ut64 to) { RListIter *iter, *iter_tmp; RIOCache *c; if (from>=to) return R_FALSE; r_list_foreach_safe (io->cache, iter, iter_tmp, c) { if (c->from >= from && c->to <= to) { r_list_delete (io->cache, iter); } } return R_FALSE; } R_API int r_io_cache_list(RIO *io, int rad) { int i, j = 0; RListIter *iter; RIOCache *c; r_list_foreach (io->cache, iter, c) { if (rad) { io->printf ("wx "); for (i=0; i<c->size; i++) io->printf ("%02x", c->data[i]); io->printf (" @ 0x%08"PFMT64x"\n", c->from); } else { io->printf ("idx=%d addr=0x%08"PFMT64x" size=%d ", j, c->from, c->size); for (i=0; i<c->size; i++) io->printf ("%02x", c->data[i]); io->printf ("\n"); } j++; } return R_FALSE; } R_API int r_io_cache_write(RIO *io, ut64 addr, const ut8 *buf, int len) { RIOCache *ch = R_NEW (RIOCache); ch->from = addr; ch->to = addr + len; ch->size = len; ch->data = (ut8*)malloc (len); memcpy (ch->data, buf, len); r_list_append (io->cache, ch); return len; } R_API int r_io_cache_read(RIO *io, ut64 addr, ut8 *buf, int len) { int l, ret, da, db; RListIter *iter; RIOCache *c; r_list_foreach (io->cache, iter, c) { if (r_range_overlap (addr, addr+len-1, c->from, c->to, &ret)) { if (ret>0) { da = ret; db = 0; l = c->size-da; } else if (ret<0) { da = 0; db = -ret; l = c->size-db; } else { da = 0; db = 0; l = c->size; } if (l>len) l = len; if (l<1) l = 1; // XXX: fail else memcpy (buf+da, c->data+db, l); } } return len; }
Java
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {SharedModule} from '../../../../shared/shared.module'; import {SearchAllComponent} from './search-all.component'; import {SearchCollectionsModule} from '../search-collections/search-collections.module'; import {SearchViewsModule} from '../search-views/search-views.module'; import {SearchTasksModule} from '../search-tasks/search-tasks.module'; @NgModule({ imports: [CommonModule, SharedModule, SearchCollectionsModule, SearchViewsModule, SearchTasksModule], declarations: [SearchAllComponent], exports: [SearchAllComponent], }) export class SearchAllModule {}
Java
/* =========================================================================== Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of Spearmint Source Code. Spearmint Source Code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Spearmint Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Spearmint Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, Spearmint Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ /***************************************************************************** * name: l_precomp.h * * desc: pre compiler * * $Archive: /source/code/botlib/l_precomp.h $ * *****************************************************************************/ #ifndef MAX_PATH #define MAX_PATH MAX_QPATH #endif #ifndef PATH_SEPERATORSTR #if defined(WIN32)|defined(_WIN32)|defined(__NT__)|defined(__WINDOWS__)|defined(__WINDOWS_386__) #define PATHSEPERATOR_STR "\\" #else #define PATHSEPERATOR_STR "/" #endif #endif #ifndef PATH_SEPERATORCHAR #if defined(WIN32)|defined(_WIN32)|defined(__NT__)|defined(__WINDOWS__)|defined(__WINDOWS_386__) #define PATHSEPERATOR_CHAR '\\' #else #define PATHSEPERATOR_CHAR '/' #endif #endif #if defined(BSPC) && !defined(QDECL) #define QDECL #endif #define DEFINE_FIXED 0x0001 #define BUILTIN_LINE 1 #define BUILTIN_FILE 2 #define BUILTIN_DATE 3 #define BUILTIN_TIME 4 #define BUILTIN_STDC 5 #define INDENT_IF 0x0001 #define INDENT_ELSE 0x0002 #define INDENT_ELIF 0x0004 #define INDENT_IFDEF 0x0008 #define INDENT_IFNDEF 0x0010 //macro definitions typedef struct define_s { char *name; //define name int flags; //define flags int builtin; // > 0 if builtin define int numparms; //number of define parameters token_t *parms; //define parameters token_t *tokens; //macro tokens (possibly containing parm tokens) struct define_s *next; //next defined macro in a list struct define_s *hashnext; //next define in the hash chain } define_t; //indents //used for conditional compilation directives: //#if, #else, #elif, #ifdef, #ifndef typedef struct indent_s { int type; //indent type int skip; //true if skipping current indent script_t *script; //script the indent was in struct indent_s *next; //next indent on the indent stack } indent_t; //source file typedef struct source_s { char filename[1024]; //file name of the script char includepath[1024]; //path to include files punctuation_t *punctuations; //punctuations to use script_t *scriptstack; //stack with scripts of the source token_t *tokens; //tokens to read first define_t *defines; //list with macro definitions define_t **definehash; //hash chain with defines indent_t *indentstack; //stack with indents int skip; // > 0 if skipping conditional code token_t token; //last read token } source_t; //read a token from the source int PC_ReadToken(source_t *source, token_t *token); //expect a certain token int PC_ExpectTokenString(source_t *source, char *string); //expect a certain token type int PC_ExpectTokenType(source_t *source, int type, int subtype, token_t *token); //expect a token int PC_ExpectAnyToken(source_t *source, token_t *token); //returns true when the token is available int PC_CheckTokenString(source_t *source, char *string); //returns true and reads the token when a token with the given type is available int PC_CheckTokenType(source_t *source, int type, int subtype, token_t *token); //skip tokens until the given token string is read int PC_SkipUntilString(source_t *source, char *string); //unread the last token read from the script void PC_UnreadLastToken(source_t *source); //unread the given token void PC_UnreadToken(source_t *source, token_t *token); //read a token only if on the same line, lines are concatenated with a slash int PC_ReadLine(source_t *source, token_t *token); //returns true if there was a white space in front of the token int PC_WhiteSpaceBeforeToken(token_t *token); //add a define to the source int PC_AddDefine(source_t *source, char *string); //add a globals define that will be added to all opened sources int PC_AddGlobalDefine(char *string); //remove the given global define int PC_RemoveGlobalDefine(char *name); //remove all globals defines void PC_RemoveAllGlobalDefines(void); //add builtin defines void PC_AddBuiltinDefines(source_t *source); //set the source include path void PC_SetIncludePath(source_t *source, char *path); //set the punction set void PC_SetPunctuations(source_t *source, punctuation_t *p); //set the base folder to load files from void PC_SetBaseFolder(const char *path); //load a source file source_t *LoadSourceFile(const char *filename); //load a source from memory source_t *LoadSourceMemory(char *ptr, int length, char *name); //free the given source void FreeSource(source_t *source); //print a source error void QDECL SourceError(source_t *source, char *str, ...) __attribute__ ((format (printf, 2, 3))); //print a source warning void QDECL SourceWarning(source_t *source, char *str, ...) __attribute__ ((format (printf, 2, 3))); #ifdef BSPC // some of BSPC source does include qcommon/q_shared.h and some does not // we define pc_token_s pc_token_t if needed (yes, it's ugly) #ifndef __Q_SHARED_H #define MAX_TOKENLENGTH 1024 typedef struct pc_token_s { int type; int subtype; int intvalue; float floatvalue; char string[MAX_TOKENLENGTH]; } pc_token_t; #endif //!_Q_SHARED_H #endif //BSPC // int PC_LoadSourceHandle(const char *filename, const char *basepath); int PC_FreeSourceHandle(int handle); int PC_ReadTokenHandle(int handle, pc_token_t *pc_token); void PC_UnreadLastTokenHandle( int handle ); int PC_SourceFileAndLine(int handle, char *filename, int *line); void PC_CheckOpenSourceHandles(void);
Java
// you can call this function to create a window to tweak a float value // if it is called multiple times, it will add more tweakable bars to that window void tweak(float *var);
Java
/*- * Copyright (c) 2003-2017 Lev Walkin <vlm@lionet.info>. All rights reserved. * Redistribution and modifications are permitted subject to BSD license. */ #ifndef ASN_TYPE_NULL_H #define ASN_TYPE_NULL_H #include <asn_application.h> #ifdef __cplusplus extern "C" { #endif /* * The value of the NULL type is meaningless. * Use the BOOLEAN type if you need to carry true/false semantics. */ typedef int NULL_t; extern asn_TYPE_descriptor_t asn_DEF_NULL; extern asn_TYPE_operation_t asn_OP_NULL; asn_struct_free_f NULL_free; asn_struct_print_f NULL_print; asn_struct_compare_f NULL_compare; ber_type_decoder_f NULL_decode_ber; der_type_encoder_f NULL_encode_der; xer_type_decoder_f NULL_decode_xer; xer_type_encoder_f NULL_encode_xer; oer_type_decoder_f NULL_decode_oer; oer_type_encoder_f NULL_encode_oer; per_type_decoder_f NULL_decode_uper; per_type_encoder_f NULL_encode_uper; per_type_decoder_f NULL_decode_aper; per_type_encoder_f NULL_encode_aper; asn_random_fill_f NULL_random_fill; #define NULL_constraint asn_generic_no_constraint #ifdef __cplusplus } #endif #endif /* NULL_H */
Java
package com.diggime.modules.email.model.impl; import com.diggime.modules.email.model.EMail; import com.diggime.modules.email.model.MailContact; import org.json.JSONObject; import java.time.LocalDateTime; import java.util.List; import static org.foilage.utils.checkers.NullChecker.notNull; public class PostmarkEMail implements EMail { private final int id; private final String messageId; private final LocalDateTime sentDate; private final MailContact sender; private final List<MailContact> receivers; private final List<MailContact> carbonCopies; private final List<MailContact> blindCarbonCopies; private final String subject; private final String tag; private final String htmlBody; private final String textBody; public PostmarkEMail(LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) { this.id = 0; this.messageId = ""; this.sentDate = notNull(sentDate); this.sender = notNull(sender); this.receivers = notNull(receivers); this.carbonCopies = notNull(carbonCopies); this.blindCarbonCopies = notNull(blindCarbonCopies); this.subject = notNull(subject); this.tag = notNull(tag); this.htmlBody = notNull(htmlBody); this.textBody = notNull(textBody); } public PostmarkEMail(String messageId, LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) { this.id = 0; this.messageId = notNull(messageId); this.sentDate = notNull(sentDate); this.sender = notNull(sender); this.receivers = notNull(receivers); this.carbonCopies = notNull(carbonCopies); this.blindCarbonCopies = notNull(blindCarbonCopies); this.subject = notNull(subject); this.tag = notNull(tag); this.htmlBody = notNull(htmlBody); this.textBody = notNull(textBody); } public PostmarkEMail(EMail mail, String messageId) { this.id = mail.getId(); this.messageId = notNull(messageId); this.sentDate = mail.getSentDate(); this.sender = mail.getSender(); this.receivers = mail.getReceivers(); this.carbonCopies = mail.getCarbonCopies(); this.blindCarbonCopies = mail.getBlindCarbonCopies(); this.subject = mail.getSubject(); this.tag = mail.getTag(); this.htmlBody = mail.getHtmlBody(); this.textBody = mail.getTextBody(); } public PostmarkEMail(int id, String messageId, LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) { this.id = id; this.messageId = notNull(messageId); this.sentDate = notNull(sentDate); this.sender = notNull(sender); this.receivers = notNull(receivers); this.carbonCopies = notNull(carbonCopies); this.blindCarbonCopies = notNull(blindCarbonCopies); this.subject = notNull(subject); this.tag = notNull(tag); this.htmlBody = notNull(htmlBody); this.textBody = notNull(textBody); } @Override public int getId() { return id; } @Override public String getMessageId() { return messageId; } @Override public LocalDateTime getSentDate() { return sentDate; } @Override public MailContact getSender() { return sender; } @Override public List<MailContact> getReceivers() { return receivers; } @Override public List<MailContact> getCarbonCopies() { return carbonCopies; } @Override public List<MailContact> getBlindCarbonCopies() { return blindCarbonCopies; } @Override public String getSubject() { return subject; } @Override public String getTag() { return tag; } @Override public String getHtmlBody() { return htmlBody; } @Override public String getTextBody() { return textBody; } @Override public JSONObject getJSONObject() { JSONObject obj = new JSONObject(); obj.put("From", sender.getName()+" <"+sender.getAddress()+">"); addReceivers(obj, receivers, "To"); addReceivers(obj, carbonCopies, "Cc"); addReceivers(obj, blindCarbonCopies, "Bcc"); obj.put("Subject", subject); if(tag.length()>0) { obj.put("Tag", tag); } if(htmlBody.length()>0) { obj.put("HtmlBody", htmlBody); } else { obj.put("HtmlBody", textBody); } if(textBody.length()>0) { obj.put("TextBody", textBody); } return obj; } private void addReceivers(JSONObject obj, List<MailContact> sendList, String jsonType) { boolean first = true; StringBuilder sb = new StringBuilder(); for(MailContact contact: sendList) { if(first) { first = false; } else { sb.append(", "); } sb.append(contact.getName()); sb.append(" <"); sb.append(contact.getAddress()); sb.append(">"); } if(sendList.size()>0) { obj.put(jsonType, sb.toString()); } } }
Java
/* * Copyright (C) 2014 Hector Espert Pardo * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package es.blackleg.libdam.geometry; import es.blackleg.libdam.utilities.Calculadora; /** * * @author Hector Espert Pardo */ public class Circulo extends Figura { private double radio; public Circulo() { } public Circulo(double radio) { this.radio = radio; } public void setRadio(double radio) { this.radio = radio; } public double getRadio() { return radio; } public double getDiametro() { return 2 * radio; } @Override public double calculaArea() { return Calculadora.areaCirculo(radio); } @Override public double calculaPerimetro() { return Calculadora.perimetroCirculo(radio); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Circulo other = (Circulo) obj; return Double.doubleToLongBits(this.radio) == Double.doubleToLongBits(other.radio); } @Override public int hashCode() { int hash = 5; hash = 67 * hash + (int) (Double.doubleToLongBits(this.radio) ^ (Double.doubleToLongBits(this.radio) >>> 32)); return hash; } @Override public String toString() { return String.format("Circulo: x=%d, y=%d, R=%.2f.", super.getCentro().getX(), super.getCentro().getY(), radio); } }
Java
<?php return [ 'facebook' => [ 'appId' => '', //application api id for facebook 'appSecret' => '', //application api secret for facebook 'scope' => 'email, user_birthday, publish_actions' //facebook scopes ], 'twitter' => [ 'appId' => '', //twitter application consumer key 'appSecret' => '' //twitter application consumer secret //Twitter scopes must be defined in dev.twitter.com ] ];
Java
/** * Cerberus Copyright (C) 2013 - 2017 cerberustesting * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This file is part of Cerberus. * * Cerberus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Cerberus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cerberus. If not, see <http://www.gnu.org/licenses/>. */ package org.cerberus.service.groovy.impl; import groovy.lang.GroovyShell; import java.util.Collections; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.cerberus.service.groovy.IGroovyService; import org.codehaus.groovy.control.CompilerConfiguration; import org.kohsuke.groovy.sandbox.SandboxTransformer; import org.springframework.stereotype.Service; /** * {@link IGroovyService} default implementation * * @author Aurelien Bourdon */ @Service public class GroovyService implements IGroovyService { /** * Groovy specific compilation customizer in order to avoid code injection */ private static final CompilerConfiguration GROOVY_COMPILER_CONFIGURATION = new CompilerConfiguration().addCompilationCustomizers(new SandboxTransformer()); /** * Each Groovy execution is ran inside a dedicated {@link Thread}, * especially to register our Groovy interceptor */ private ExecutorService executorService; @PostConstruct private void init() { executorService = Executors.newCachedThreadPool(); } @PreDestroy private void shutdown() { if (executorService != null && !executorService.isShutdown()) { executorService.shutdownNow(); } } @Override public String eval(final String script) throws IGroovyServiceException { try { Future<String> expression = executorService.submit(() -> { RestrictiveGroovyInterceptor interceptor = new RestrictiveGroovyInterceptor( Collections.<Class<?>>emptySet(), Collections.<Class<?>>emptySet(), Collections.<RestrictiveGroovyInterceptor.AllowedPrefix>emptyList() ); try { interceptor.register(); GroovyShell shell = new GroovyShell(GROOVY_COMPILER_CONFIGURATION); return shell.evaluate(script).toString(); } finally { interceptor.unregister(); } }); String eval = expression.get(); if (eval == null) { throw new IGroovyServiceException("Groovy evaluation returns null result"); } return eval; } catch (Exception e) { throw new IGroovyServiceException(e); } } }
Java
using System; using System.Collections.Generic; using System.Text; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Engine; using Micropolis.Common; using Microsoft.ApplicationInsights; namespace Micropolis.ViewModels { public class EvaluationPaneViewModel : BindableBase, Engine.IListener { private Engine.Micropolis _engine; private MainGamePageViewModel _mainPageViewModel; /// <summary> /// Sets the engine. /// </summary> /// <param name="newEngine">The new engine.</param> public void SetEngine(Engine.Micropolis newEngine) { if (_engine != null) { //old engine _engine.RemoveListener(this); } _engine = newEngine; if (_engine != null) { //new engine _engine.AddListener(this); LoadEvaluation(); } } public EvaluationPaneViewModel() { DismissCommand = new DelegateCommand(OnDismissClicked); try { _telemetry = new TelemetryClient(); } catch (Exception) { } } /// <summary> /// Called when user clicked the dismiss button to close the window. /// </summary> private void OnDismissClicked() { try { _telemetry.TrackEvent("EvaluationPaneDismissClicked"); } catch (Exception) { } _mainPageViewModel.HideEvaluationPane(); } private string _headerPublicOpinionTextBlockText; public string HeaderPublicOpinionTextBlockText { get { return this._headerPublicOpinionTextBlockText; } set { this.SetProperty(ref this._headerPublicOpinionTextBlockText, value); } } private string _pubOpTextBlockText; public string PubOpTextBlockText { get { return this._pubOpTextBlockText; } set { this.SetProperty(ref this._pubOpTextBlockText, value); } } private string _pubOp2TextBlockText; public string PubOp2TextBlockText { get { return this._pubOp2TextBlockText; } set { this.SetProperty(ref this._pubOp2TextBlockText, value); } } private string _pubOp3TextBlockText; public string PubOp3TextBlockText { get { return this._pubOp3TextBlockText; } set { this.SetProperty(ref this._pubOp3TextBlockText, value); } } private string _pubOp4TextBlockText; public string PubOp4TextBlockText { get { return this._pubOp4TextBlockText; } set { this.SetProperty(ref this._pubOp4TextBlockText, value); } } /// <summary> /// Makes the public opinion pane. /// </summary> /// <returns></returns> private void MakePublicOpinionPane() { HeaderPublicOpinionTextBlockText = Strings.GetString("public-opinion"); PubOpTextBlockText = Strings.GetString("public-opinion-1"); PubOp2TextBlockText = Strings.GetString("public-opinion-2"); PubOp3TextBlockText = Strings.GetString("public-opinion-yes"); PubOp4TextBlockText = Strings.GetString("public-opinion-no"); VoterProblem1TextBlockText = ""; VoterCount1TextBlockText = ""; VoterProblem2TextBlockText = ""; VoterCount2TextBlockText = ""; VoterProblem3TextBlockText = ""; VoterCount3TextBlockText = ""; VoterProblem4TextBlockText = ""; VoterCount4TextBlockText = ""; } private string _voterProblem4TextBlockText; public string VoterProblem4TextBlockText { get { return this._voterProblem4TextBlockText; } set { this.SetProperty(ref this._voterProblem4TextBlockText, value); } } private string _voterProblem3TextBlockText; public string VoterProblem3TextBlockText { get { return this._voterProblem3TextBlockText; } set { this.SetProperty(ref this._voterProblem3TextBlockText, value); } } private string _voterProblem2TextBlockText; public string VoterProblem2TextBlockText { get { return this._voterProblem2TextBlockText; } set { this.SetProperty(ref this._voterProblem2TextBlockText, value); } } private string _voterProblem1TextBlockText; public string VoterProblem1TextBlockText { get { return this._voterProblem1TextBlockText; } set { this.SetProperty(ref this._voterProblem1TextBlockText, value); } } private string _voterCount1TextBlockText; public string VoterCount1TextBlockText { get { return this._voterCount1TextBlockText; } set { this.SetProperty(ref this._voterCount1TextBlockText, value); } } private string _voterCount2TextBlockText; public string VoterCount2TextBlockText { get { return this._voterCount2TextBlockText; } set { this.SetProperty(ref this._voterCount2TextBlockText, value); } } private string _voterCount3TextBlockText; public string VoterCount3TextBlockText { get { return this._voterCount3TextBlockText; } set { this.SetProperty(ref this._voterCount3TextBlockText, value); } } private string _voterCount4TextBlockText; public string VoterCount4TextBlockText { get { return this._voterCount4TextBlockText; } set { this.SetProperty(ref this._voterCount4TextBlockText, value); } } /// <summary> /// Makes the statistics pane. /// </summary> /// <returns></returns> private void MakeStatisticsPane() { HeaderStatisticsTextBlockText = Strings.GetString("statistics-head"); CityScoreHeaderTextBlockText = Strings.GetString("city-score-head"); StatPopTextBlockText = Strings.GetString("stats-population"); StatMigTextBlockText = Strings.GetString("stats-net-migration"); StatsLastYearTextBlockText = Strings.GetString("stats-last-year"); StatsAssessedValueTextBlockText = Strings.GetString("stats-assessed-value"); StatsCategoryTextBlockText = Strings.GetString("stats-category"); StatsGameLevelTextBlockText = Strings.GetString("stats-game-level"); CityScoreCurrentTextBlockText = Strings.GetString("city-score-current"); CityScoreChangeTextBlockText = Strings.GetString("city-score-change"); } private string _headerStatisticsTextBlockText; public string HeaderStatisticsTextBlockText { get { return this._headerStatisticsTextBlockText; } set { this.SetProperty(ref this._headerStatisticsTextBlockText, value); } } private string _cityScoreHeaderTextBlockText; public string CityScoreHeaderTextBlockText { get { return this._cityScoreHeaderTextBlockText; } set { this.SetProperty(ref this._cityScoreHeaderTextBlockText, value); } } private string _statPopTextBlockText; public string StatPopTextBlockText { get { return this._statPopTextBlockText; } set { this.SetProperty(ref this._statPopTextBlockText, value); } } private string _statMigTextBlockText; public string StatMigTextBlockText { get { return this._statMigTextBlockText; } set { this.SetProperty(ref this._statMigTextBlockText, value); } } private string _statsLastYearTextBlockText; public string StatsLastYearTextBlockText { get { return this._statsLastYearTextBlockText; } set { this.SetProperty(ref this._statsLastYearTextBlockText, value); } } private string _statsAssessedValueTextBlockText; public string StatsAssessedValueTextBlockText { get { return this._statsAssessedValueTextBlockText; } set { this.SetProperty(ref this._statsAssessedValueTextBlockText, value); } } private string _statsCategoryTextBlockText; public string StatsCategoryTextBlockText { get { return this._statsCategoryTextBlockText; } set { this.SetProperty(ref this._statsCategoryTextBlockText, value); } } private string _statsGameLevelTextBlockText; public string StatsGameLevelTextBlockText { get { return this._statsGameLevelTextBlockText; } set { this.SetProperty(ref this._statsGameLevelTextBlockText, value); } } private string _cityScoreCurrentTextBlockText; public string CityScoreCurrentTextBlockText { get { return this._cityScoreCurrentTextBlockText; } set { this.SetProperty(ref this._cityScoreCurrentTextBlockText, value); } } private string _cityScoreChangeTextBlockText; public string CityScoreChangeTextBlockText { get { return this._cityScoreChangeTextBlockText; } set { this.SetProperty(ref this._cityScoreChangeTextBlockText, value); } } private string _yesTextBlockText; public string YesTextBlockText { get { return this._yesTextBlockText; } set { this.SetProperty(ref this._yesTextBlockText, value); } } private string _noTextBlockText; public string NoTextBlockText { get { return this._noTextBlockText; } set { this.SetProperty(ref this._noTextBlockText, value); } } /// <summary> /// Loads the evaluation. /// </summary> private void LoadEvaluation() { YesTextBlockText = ((_engine.Evaluation.CityYes).ToString()+"%"); NoTextBlockText = ((_engine.Evaluation.CityNo).ToString()+"%"); CityProblem p; int numVotes; p = 0 < _engine.Evaluation.ProblemOrder.Length ? _engine.Evaluation.ProblemOrder[0] : default(CityProblem); numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0; if (numVotes != 0) { VoterProblem1TextBlockText = ("problem." + p); //name VoterCount1TextBlockText = (0.01*numVotes).ToString(); VoterProblem1IsVisible = true; VoterCount1IsVisible = true; } else { VoterProblem1IsVisible = false; VoterCount1IsVisible = false; } p = 1 < _engine.Evaluation.ProblemOrder.Length ? _engine.Evaluation.ProblemOrder[1] : default(CityProblem); numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0; if (numVotes != 0) { VoterProblem2TextBlockText = ("problem." + p); //name VoterCount2TextBlockText = (0.01 * numVotes).ToString(); VoterProblem2IsVisible = true; VoterCount2IsVisible = true; } else { VoterProblem2IsVisible = false; VoterCount2IsVisible = false; } p = 2 < _engine.Evaluation.ProblemOrder.Length ? _engine.Evaluation.ProblemOrder[2] : default(CityProblem); numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0; if (numVotes != 0) { VoterProblem3TextBlockText = ("problem." + p); //name VoterCount3TextBlockText = (0.01 * numVotes).ToString(); VoterProblem3IsVisible = true; VoterCount3IsVisible = true; } else { VoterProblem3IsVisible = false; VoterCount3IsVisible = false; } p = 3 < _engine.Evaluation.ProblemOrder.Length ? _engine.Evaluation.ProblemOrder[3] : default(CityProblem); numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0; if (numVotes != 0) { VoterProblem4TextBlockText = ("problem." + p); //name VoterCount4TextBlockText = (0.01 * numVotes).ToString(); VoterProblem4IsVisible = true; VoterCount4IsVisible = true; } else { VoterProblem4IsVisible = false; VoterCount4IsVisible = false; } PopTextBlockText = (_engine.Evaluation.CityPop).ToString(); DeltaTextBlockText = (_engine.Evaluation.DeltaCityPop).ToString(); AssessTextBlockText = (_engine.Evaluation.CityAssValue).ToString(); CityClassTextBlockText = (GetCityClassName(_engine.Evaluation.CityClass)); GameLevelTextBlockText = (GetGameLevelName(_engine.GameLevel)); ScoreTextBlockText = (_engine.Evaluation.CityScore).ToString(); ScoreDeltaTextBlockText = (_engine.Evaluation.DeltaCityScore).ToString(); } private bool _voterCount4IsVisible; public bool VoterCount4IsVisible { get { return this._voterCount4IsVisible; } set { this.SetProperty(ref this._voterCount4IsVisible, value); } } private bool _voterCount3IsVisible; public bool VoterCount3IsVisible { get { return this._voterCount3IsVisible; } set { this.SetProperty(ref this._voterCount3IsVisible, value); } } private bool _voterCount2IsVisible; public bool VoterCount2IsVisible { get { return this._voterCount2IsVisible; } set { this.SetProperty(ref this._voterCount2IsVisible, value); } } private bool _voterCount1IsVisible; public bool VoterCount1IsVisible { get { return this._voterCount1IsVisible; } set { this.SetProperty(ref this._voterCount1IsVisible, value); } } private bool _voterProblem4IsVisible; public bool VoterProblem4IsVisible { get { return this._voterProblem4IsVisible; } set { this.SetProperty(ref this._voterProblem4IsVisible, value); } } private bool _voterProblem3IsVisible; public bool VoterProblem3IsVisible { get { return this._voterProblem3IsVisible; } set { this.SetProperty(ref this._voterProblem3IsVisible, value); } } private bool _voterProblem2IsVisible; public bool VoterProblem2IsVisible { get { return this._voterProblem2IsVisible; } set { this.SetProperty(ref this._voterProblem2IsVisible, value); } } private bool _voterProblem1IsVisible; public bool VoterProblem1IsVisible { get { return this._voterProblem1IsVisible; } set { this.SetProperty(ref this._voterProblem1IsVisible, value); } } private string _scoreDeltaTextBlockText; public string ScoreDeltaTextBlockText { get { return this._scoreDeltaTextBlockText; } set { this.SetProperty(ref this._scoreDeltaTextBlockText, value); } } private string _scoreTextBlockText; public string ScoreTextBlockText { get { return this._scoreTextBlockText; } set { this.SetProperty(ref this._scoreTextBlockText, value); } } private string _gameLevelTextBlockText; public string GameLevelTextBlockText { get { return this._gameLevelTextBlockText; } set { this.SetProperty(ref this._gameLevelTextBlockText, value); } } private string _cityClassTextBlockText; public string CityClassTextBlockText { get { return this._cityClassTextBlockText; } set { this.SetProperty(ref this._cityClassTextBlockText, value); } } private string _assessTextBlockText; public string AssessTextBlockText { get { return this._assessTextBlockText; } set { this.SetProperty(ref this._assessTextBlockText, value); } } private string _deltaTextBlockText; public string DeltaTextBlockText { get { return this._deltaTextBlockText; } set { this.SetProperty(ref this._deltaTextBlockText, value); } } private string _popTextBlockText; public string PopTextBlockText { get { return this._popTextBlockText; } set { this.SetProperty(ref this._popTextBlockText, value); } } /// <summary> /// Gets the name of the city class. /// </summary> /// <param name="cityClass">The city class.</param> /// <returns></returns> private static String GetCityClassName(int cityClass) { return Strings.GetString("class." + cityClass); } /// <summary> /// Gets the name of the game level. /// </summary> /// <param name="gameLevel">The game level.</param> /// <returns></returns> private static String GetGameLevelName(int gameLevel) { return Strings.GetString("level." + gameLevel); } public DelegateCommand DismissCommand { get; private set; } private string _dismissButtonText; private TelemetryClient _telemetry; public string DismissButtonText { get { return this._dismissButtonText; } set { this.SetProperty(ref this._dismissButtonText, value); } } internal void SetupAfterBasicInit(MainGamePageViewModel mainPageViewModel, Engine.Micropolis engine) { _mainPageViewModel = mainPageViewModel; DismissButtonText = Strings.GetString("dismiss-evaluation"); MakePublicOpinionPane(); MakeStatisticsPane(); SetEngine(engine); LoadEvaluation(); } #region implements Micropolis.IListener /// <summary> /// Cities the message. /// </summary> /// <param name="message">The message.</param> /// <param name="loc">The loc.</param> public void CityMessage(MicropolisMessage message, CityLocation loc) { } /// <summary> /// Cities the sound. /// </summary> /// <param name="sound">The sound.</param> /// <param name="loc">The loc.</param> public void CitySound(Sound sound, CityLocation loc) { } /// <summary> /// Fired whenever the "census" is taken, and the various historical counters have been updated. (Once a month in /// game.) /// </summary> public void CensusChanged() { } /// <summary> /// Fired whenever resValve, comValve, or indValve changes. (Twice a month in game.) /// </summary> public void DemandChanged() { } /// <summary> /// Fired whenever the mayor's money changes. /// </summary> public void FundsChanged() { } /// <summary> /// Fired whenever autoBulldoze, autoBudget, noDisasters, or simSpeed change. /// </summary> public void OptionsChanged() { } #endregion #region implements Engine.IListener /// <summary> /// Fired whenever the city evaluation is recalculated. (Once a year.) /// </summary> public void EvaluationChanged() { LoadEvaluation(); } #endregion } }
Java
<?php /** * KR_Custom_Posts */ class KR_Custom_Posts extends Odin_Post_Type { private $_labels = array(); private $_arguments = array(); private $_dashicon = 'dashicons-'; private $_supports = array( 'title', 'editor', 'thumbnail' ); private $_slug; private $_singular; private $_plural; private $_rewrite; private $_exclude_search; public function __construct( $post_slug = null, $singular = null, $plural = null, $supports = array(), $dashicon = 'admin-post', $rewrite = null, $exclude_search = false ) { if(empty($post_slug)) { echo '<pre>' . print_r( __('The Parameter <code>$post_slug</code> is required!!'), true ) . '</pre>'; die(); } $this->_slug = $post_slug; $this->_dashicon = $this->_dashicon . $dashicon; $this->_singular = (!empty($singular)) ? $singular : $this->_slug; $this->_plural = (!empty($plural)) ? $plural : $this->_slug; $this->_supports = (count($supports) > 0) ? $supports : $this->_supports; $this->_rewrite = (!empty($rewrite)) ? array('slug' => $rewrite) : array('slug' => $this->_slug); $this->_exclude_search = $exclude_search; $this->kr_init(); } private function kr_init() { parent::__construct( $this->_slug, $this->_slug ); $this->kr_set_labels(); $this->kr_set_arguments(); $this->set_labels($this->_labels); # odin method set_labels $this->set_arguments($this->_arguments); # odin method set_arguments $this->kr_cleaner(); } private function kr_set_labels() { $this->_labels = array( 'name' => $this->_plural, 'singular_name' => $this->_singular, 'menu_name' => $this->_plural, 'all_items' => $this->_plural, 'add_new' => 'Adicionar Novo', 'add_new_item' => 'Adicionar Novo', 'search_items' => 'Buscar', 'not_found' => 'Nada encontrado', 'not_found_in_trash' => 'Nada encontrado na lixeira', ); } private function kr_set_arguments() { $this->_arguments = array( 'supports' => $this->_supports, 'menu_icon' => $this->_dashicon, 'rewrite' => $this->_rewrite, 'exclude_from_search' => $this->_exclude_search, // 'menu_position' => '1.36', 'capability_type' => 'page', ); } private function kr_cleaner() { unset($this->_slug); unset($this->_dashicon); unset($this->_singular); unset($this->_plural); unset($this->_supports); unset($this->_exclude_search); unset($this->_rewrite); unset($this->_labels); unset($this->_arguments); } } # End Class KR_Custom_Posts
Java
<?php /* core/modules/system/templates/block--system-branding-block.html.twig */ class __TwigTemplate_f1b301a70237e4e176f4b41c2721030700b3dd2e5c3f618f2513416e3a699971 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("block.html.twig", "core/modules/system/templates/block--system-branding-block.html.twig", 1); $this->blocks = array( 'content' => array($this, 'block_content'), ); } protected function doGetParent(array $context) { return "block.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $tags = array("if" => 19); $filters = array("t" => 20); $functions = array("path" => 20); try { $this->env->getExtension('sandbox')->checkSecurity( array('if'), array('t'), array('path') ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 18 public function block_content($context, array $blocks = array()) { // line 19 echo " "; if ((isset($context["site_logo"]) ? $context["site_logo"] : null)) { // line 20 echo " <a href=\""; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar($this->env->getExtension('drupal_core')->getPath("<front>"))); echo "\" title=\""; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Home"))); echo "\" rel=\"home\"> <img src=\""; // line 21 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["site_logo"]) ? $context["site_logo"] : null), "html", null, true)); echo "\" alt=\""; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Home"))); echo "\" /> </a> "; } // line 24 echo " "; if ((isset($context["site_name"]) ? $context["site_name"] : null)) { // line 25 echo " <a href=\""; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar($this->env->getExtension('drupal_core')->getPath("<front>"))); echo "\" title=\""; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Home"))); echo "\" rel=\"home\">"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["site_name"]) ? $context["site_name"] : null), "html", null, true)); echo "</a> "; } // line 27 echo " "; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["site_slogan"]) ? $context["site_slogan"] : null), "html", null, true)); echo " "; } public function getTemplateName() { return "core/modules/system/templates/block--system-branding-block.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 86 => 27, 76 => 25, 73 => 24, 65 => 21, 58 => 20, 55 => 19, 52 => 18, 11 => 1,); } } /* {% extends "block.html.twig" %}*/ /* {#*/ /* /***/ /* * @file*/ /* * Default theme implementation for a branding block.*/ /* **/ /* * Each branding element variable (logo, name, slogan) is only available if*/ /* * enabled in the block configuration.*/ /* **/ /* * Available variables:*/ /* * - site_logo: Logo for site as defined in Appearance or theme settings.*/ /* * - site_name: Name for site as defined in Site information settings.*/ /* * - site_slogan: Slogan for site as defined in Site information settings.*/ /* **/ /* * @ingroup themeable*/ /* *//* */ /* #}*/ /* {% block content %}*/ /* {% if site_logo %}*/ /* <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">*/ /* <img src="{{ site_logo }}" alt="{{ 'Home'|t }}" />*/ /* </a>*/ /* {% endif %}*/ /* {% if site_name %}*/ /* <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}</a>*/ /* {% endif %}*/ /* {{ site_slogan }}*/ /* {% endblock %}*/ /* */
Java
#region using directives using System; using PoGo.PokeMobBot.Logic.Event; using PoGo.PokeMobBot.Logic.Event.Egg; using PoGo.PokeMobBot.Logic.Event.Fort; using PoGo.PokeMobBot.Logic.Event.Global; using PoGo.PokeMobBot.Logic.Event.GUI; using PoGo.PokeMobBot.Logic.Event.Item; using PoGo.PokeMobBot.Logic.Event.Logic; using PoGo.PokeMobBot.Logic.Event.Obsolete; using PoGo.PokeMobBot.Logic.Event.Player; using PoGo.PokeMobBot.Logic.Event.Pokemon; using PoGo.PokeMobBot.Logic.State; using PoGo.PokeMobBot.Logic.Utils; using POGOProtos.Networking.Responses; #endregion namespace PoGo.PokeMobBot.Logic { public class StatisticsAggregator { public void HandleEvent(ProfileEvent evt, ISession session) { session.Stats.SetUsername(evt.Profile); session.Stats.RefreshStatAndCheckLevelup(session); } public void HandleEvent(ErrorEvent evt, ISession session) { } public void HandleEvent(NoticeEvent evt, ISession session) { } public void HandleEvent(FortLureStartedEvent evt, ISession session) { } public void HandleEvent(ItemUsedEvent evt, ISession session) { } public void HandleEvent(WarnEvent evt, ISession session) { } public void HandleEvent(UseLuckyEggEvent evt, ISession session) { } public void HandleEvent(PokemonEvolveEvent evt, ISession session) { session.Stats.TotalExperience += evt.Exp; session.Stats.RefreshStatAndCheckLevelup(session); } public void HandleEvent(TransferPokemonEvent evt, ISession session) { session.Stats.TotalPokemonsTransfered++; session.Stats.RefreshStatAndCheckLevelup(session); } public void HandleEvent(EggHatchedEvent evt, ISession session) { session.Stats.TotalPokemons++; session.Stats.HatchedNow++; session.Stats.RefreshStatAndCheckLevelup(session); session.Stats.RefreshPokeDex(session); } public void HandleEvent(VerifyChallengeEvent evt, ISession session) { } public void HandleEvent(CheckChallengeEvent evt, ISession session) { } public void HandleEvent(BuddySetEvent evt, ISession session) { } public void HandleEvent(BuddyWalkedEvent evt, ISession session) { } public void HandleEvent(ItemRecycledEvent evt, ISession session) { session.Stats.TotalItemsRemoved += evt.Count; session.Stats.RefreshStatAndCheckLevelup(session); } public void HandleEvent(FortUsedEvent evt, ISession session) { session.Stats.TotalExperience += evt.Exp; session.Stats.TotalPokestops++; session.Stats.RefreshStatAndCheckLevelup(session); } public void HandleEvent(FortTargetEvent evt, ISession session) { } public void HandleEvent(PokemonActionDoneEvent evt, ISession session) { } public void HandleEvent(PokemonCaptureEvent evt, ISession session) { if (evt.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess) { session.Stats.TotalExperience += evt.Exp; session.Stats.TotalPokemons++; session.Stats.TotalStardust = evt.Stardust; session.Stats.RefreshStatAndCheckLevelup(session); session.Stats.RefreshPokeDex(session); } session.Stats.PokeBalls++; } public void HandleEvent(NoPokeballEvent evt, ISession session) { } public void HandleEvent(UseBerryEvent evt, ISession session) { } public void HandleEvent(DisplayHighestsPokemonEvent evt, ISession session) { } public void HandleEvent(UpdatePositionEvent evt, ISession session) { } public void HandleEvent(NewVersionEvent evt, ISession session) { } public void HandleEvent(UpdateEvent evt, ISession session) { } public void HandleEvent(BotCompleteFailureEvent evt, ISession session) { } public void HandleEvent(DebugEvent evt, ISession session) { } public void HandleEvent(EggIncubatorStatusEvent evt, ISession session) { } public void HandleEvent(EggsListEvent evt, ISession session) { } public void HandleEvent(ForceMoveDoneEvent evt, ISession session) { } public void HandleEvent(FortFailedEvent evt, ISession session) { } public void HandleEvent(InvalidKeepAmountEvent evt, ISession session) { } public void HandleEvent(InventoryListEvent evt, ISession session) { } public void HandleEvent(InventoryNewItemsEvent evt, ISession session) { } public void HandleEvent(EggFoundEvent evt, ISession session) { } public void HandleEvent(NextRouteEvent evt, ISession session) { } public void HandleEvent(PlayerLevelUpEvent evt, ISession session) { } public void HandleEvent(PlayerStatsEvent evt, ISession session) { } public void HandleEvent(PokemonDisappearEvent evt, ISession session) { session.Stats.EncountersNow++; } public void HandleEvent(PokemonEvolveDoneEvent evt, ISession session) { session.Stats.TotalEvolves++; session.Stats.RefreshPokeDex(session); } public void HandleEvent(PokemonFavoriteEvent evt, ISession session) { } public void HandleEvent(PokemonSettingsEvent evt, ISession session) { } public void HandleEvent(PokemonsFoundEvent evt, ISession session) { } public void HandleEvent(PokemonsWildFoundEvent evt, ISession session) { } public void HandleEvent(PokemonStatsChangedEvent evt, ISession session) { } public void HandleEvent(PokeStopListEvent evt, ISession session) { } public void HandleEvent(SnipeEvent evt, ISession session) { } public void HandleEvent(SnipeModeEvent evt, ISession session) { } public void HandleEvent(UseLuckyEggMinPokemonEvent evt, ISession session) { } public void HandleEvent(PokemonListEvent evt, ISession session) { } public void HandleEvent(GymPokeEvent evt, ISession session) { } public void HandleEvent(PokestopsOptimalPathEvent evt, ISession session) { } public void HandleEvent(TeamSetEvent evt, ISession session) { } public void HandleEvent(ItemLostEvent evt, ISession session) { } public void Listen(IEvent evt, ISession session) { try { dynamic eve = evt; HandleEvent(eve, session); } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } } } }
Java
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member (no intention to document this file) namespace RobinHood70.WallE.Base { public class AllCategoriesItem { #region Constructors internal AllCategoriesItem(string category, int files, bool hidden, int pages, int size, int subcats) { this.Category = category; this.Files = files; this.Hidden = hidden; this.Pages = pages; this.Size = size; this.Subcategories = subcats; } #endregion #region Public Properties public string Category { get; } public int Files { get; } public bool Hidden { get; } public int Pages { get; } public int Size { get; } public int Subcategories { get; } #endregion #region Public Override Methods public override string ToString() => this.Category; #endregion } }
Java
module libxc_funcs_m implicit none public integer, parameter :: XC_LDA_X = 1 ! Exchange integer, parameter :: XC_LDA_C_WIGNER = 2 ! Wigner parametrization integer, parameter :: XC_LDA_C_RPA = 3 ! Random Phase Approximation integer, parameter :: XC_LDA_C_HL = 4 ! Hedin & Lundqvist integer, parameter :: XC_LDA_C_GL = 5 ! Gunnarson & Lundqvist integer, parameter :: XC_LDA_C_XALPHA = 6 ! Slater's Xalpha integer, parameter :: XC_LDA_C_VWN = 7 ! Vosko, Wilk, & Nussair integer, parameter :: XC_LDA_C_VWN_RPA = 8 ! Vosko, Wilk, & Nussair (RPA) integer, parameter :: XC_LDA_C_PZ = 9 ! Perdew & Zunger integer, parameter :: XC_LDA_C_PZ_MOD = 10 ! Perdew & Zunger (Modified) integer, parameter :: XC_LDA_C_OB_PZ = 11 ! Ortiz & Ballone (PZ) integer, parameter :: XC_LDA_C_PW = 12 ! Perdew & Wang integer, parameter :: XC_LDA_C_PW_MOD = 13 ! Perdew & Wang (Modified) integer, parameter :: XC_LDA_C_OB_PW = 14 ! Ortiz & Ballone (PW) integer, parameter :: XC_LDA_C_AMGB = 15 ! Attacalite et al integer, parameter :: XC_LDA_XC_TETER93 = 20 ! Teter 93 parametrization integer, parameter :: XC_GGA_X_PBE = 101 ! Perdew, Burke & Ernzerhof exchange integer, parameter :: XC_GGA_X_PBE_R = 102 ! Perdew, Burke & Ernzerhof exchange (revised) integer, parameter :: XC_GGA_X_B86 = 103 ! Becke 86 Xalfa,beta,gamma integer, parameter :: XC_GGA_X_B86_R = 104 ! Becke 86 Xalfa,beta,gamma (reoptimized) integer, parameter :: XC_GGA_X_B86_MGC = 105 ! Becke 86 Xalfa,beta,gamma (with mod. grad. correction) integer, parameter :: XC_GGA_X_B88 = 106 ! Becke 88 integer, parameter :: XC_GGA_X_G96 = 107 ! Gill 96 integer, parameter :: XC_GGA_X_PW86 = 108 ! Perdew & Wang 86 integer, parameter :: XC_GGA_X_PW91 = 109 ! Perdew & Wang 91 integer, parameter :: XC_GGA_X_OPTX = 110 ! Handy & Cohen OPTX 01 integer, parameter :: XC_GGA_X_DK87_R1 = 111 ! dePristo & Kress 87 (version R1) integer, parameter :: XC_GGA_X_DK87_R2 = 112 ! dePristo & Kress 87 (version R2) integer, parameter :: XC_GGA_X_LG93 = 113 ! Lacks & Gordon 93 integer, parameter :: XC_GGA_X_FT97_A = 114 ! Filatov & Thiel 97 (version A) integer, parameter :: XC_GGA_X_FT97_B = 115 ! Filatov & Thiel 97 (version B) integer, parameter :: XC_GGA_X_PBE_SOL = 116 ! Perdew, Burke & Ernzerhof exchange (solids) integer, parameter :: XC_GGA_X_RPBE = 117 ! Hammer, Hansen & Norskov (PBE-like) integer, parameter :: XC_GGA_X_WC = 118 ! Wu & Cohen integer, parameter :: XC_GGA_X_mPW91 = 119 ! Modified form of PW91 by Adamo & Barone integer, parameter :: XC_GGA_X_AM05 = 120 ! Armiento & Mattsson 05 exchange integer, parameter :: XC_GGA_X_PBEA = 121 ! Madsen (PBE-like) integer, parameter :: XC_GGA_X_MPBE = 122 ! Adamo & Barone modification to PBE integer, parameter :: XC_GGA_X_XPBE = 123 ! xPBE reparametrization by Xu & Goddard integer, parameter :: XC_GGA_X_OPTPBE = 124 ! optPBE reparametrization for optPBE-vdW integer, parameter :: XC_GGA_X_OPTB88 = 125 ! optB88 reparametrization for optB88-vdW integer, parameter :: XC_GGA_X_C09 = 126 ! Cooper exchange for C09-vdW integer, parameter :: XC_GGA_C_PBE = 130 ! Perdew, Burke & Ernzerhof correlation integer, parameter :: XC_GGA_C_LYP = 131 ! Lee, Yang & Parr integer, parameter :: XC_GGA_C_P86 = 132 ! Perdew 86 integer, parameter :: XC_GGA_C_PBE_SOL = 133 ! Perdew, Burke & Ernzerhof correlation SOL integer, parameter :: XC_GGA_C_PW91 = 134 ! Perdew & Wang 91 integer, parameter :: XC_GGA_C_AM05 = 135 ! Armiento & Mattsson 05 correlation integer, parameter :: XC_GGA_C_XPBE = 136 ! xPBE reparametrization by Xu & Goddard integer, parameter :: XC_GGA_C_PBE_REVTPSS = 137 ! PBE correlation for TPSS integer, parameter :: XC_GGA_XC_LB = 160 ! van Leeuwen & Baerends integer, parameter :: XC_GGA_XC_HCTH_93 = 161 ! HCTH functional fitted to 93 molecules integer, parameter :: XC_GGA_XC_HCTH_120 = 162 ! HCTH functional fitted to 120 molecules integer, parameter :: XC_GGA_XC_HCTH_147 = 163 ! HCTH functional fitted to 147 molecules integer, parameter :: XC_GGA_XC_HCTH_407 = 164 ! HCTH functional fitted to 147 molecules integer, parameter :: XC_GGA_XC_EDF1 = 165 ! Empirical functionals from Adamson, Gill, and Pople integer, parameter :: XC_GGA_XC_XLYP = 166 ! XLYP functional integer, parameter :: XC_HYB_GGA_XC_B3PW91 = 401 ! The original hybrid proposed by Becke integer, parameter :: XC_HYB_GGA_XC_B3LYP = 402 ! The (in)famous B3LYP integer, parameter :: XC_HYB_GGA_XC_B3P86 = 403 ! Perdew 86 hybrid similar to B3PW91 integer, parameter :: XC_HYB_GGA_XC_O3LYP = 404 ! hybrid using the optx functional integer, parameter :: XC_HYB_GGA_XC_PBEH = 406 ! aka PBE0 or PBE1PBE integer, parameter :: XC_HYB_GGA_XC_X3LYP = 411 ! maybe the best hybrid integer, parameter :: XC_HYB_GGA_XC_B1WC = 412 ! Becke 1-parameter mixture of WC and EXX integer, parameter :: XC_MGGA_X_TPSS = 201 ! Perdew, Tao, Staroverov & Scuseria exchange integer, parameter :: XC_MGGA_C_TPSS = 202 ! Perdew, Tao, Staroverov & Scuseria correlation integer, parameter :: XC_MGGA_X_M06L = 203 ! Zhao, Truhlar exchange integer, parameter :: XC_MGGA_C_M06L = 204 ! Zhao, Truhlar correlation integer, parameter :: XC_MGGA_X_REVTPSS = 205 ! Perdew, Ruzsinszky, Csonka, Constantin and Sun Exchange integer, parameter :: XC_MGGA_C_REVTPSS = 206 ! Perdew, Ruzsinszky, Csonka, Constantin and Sun Correlation integer, parameter :: XC_LCA_OMC = 301 ! Orestes, Marcasso & Capelle integer, parameter :: XC_LCA_LCH = 302 ! Lee, Colwell & Handy end module libxc_funcs_m
Java
# brasillivre ![alt text](readme.png "") Segundo o [Ministério do Trabalho](http://www.mtps.gov.br/fiscalizacao-combate-trabalho-escravo) >Considera-se trabalho realizado em condição análoga à de escravo a que resulte das seguintes situações, quer em conjunto, quer isoladamente: a submissão de trabalhador a trabalhos forçados; a submissão de trabalhador a jornada exaustiva; a sujeição de trabalhador a condições degradantes de trabalho; a restrição da locomoção do trabalhador, seja em razão de dívida contraída, seja por meio do cerceamento do uso de qualquer meio de transporte por parte do trabalhador, ou por qualquer outro meio com o fim de retê-lo no local de trabalho; a vigilância ostensiva no local de trabalho por parte do empregador ou seu preposto, com o fim de retê-lo no local de trabalho; a posse de documentos ou objetos pessoais do trabalhador, por parte do empregador ou seu preposto, com o fim de retê-lo no local de trabalho. ### Fontes A Lista de Transparência sobre Trabalho Escravo Contemporâneo no Brasil pode ser obtida através do seguinte link [http://reporterbrasil.org.br/wp-content/uploads/2016/06/listadetransparencia4.pdf](http://reporterbrasil.org.br/wp-content/uploads/2016/06/listadetransparencia4.pdf) ### Objetivos do Projeto ... ### O porquê [STF proíbe Ministério do Trabalho de divulgar lista suja do trabalho escravo](http://oglobo.globo.com/economia/negocios/stf-proibe-ministerio-do-trabalho-de-divulgar-lista-suja-do-trabalho-escravo-14944492) [STF libera divulgação de lista suja do trabalho escravo] (http://exame.abril.com.br/brasil/noticias/stf-libera-divulgacao-de-lista-de-empresas-autuadas-por-trabalho-escravo) ...não consigo compreender o judiciário [http://www.bbc.com/portuguese/noticias/2014/11/141117_escravidao_brasil_mundo_pai](http://www.bbc.com/portuguese/noticias/2014/11/141117_escravidao_brasil_mundo_pai) ### [Roadmap](https://github.com/devmessias/brasillivre/labels/roadmap) Se você deseja contribuir para o projeto eu coloquei em [brasillivre/labels/roadmap](https://github.com/devmessias/brasillivre/labels/roadmap) todos os issues que considero mais importantes no momento, pull requests são sempre bem-vindos, assim como novas sugestões de features.
Java
'''WARCAT: Web ARChive (WARC) Archiving Tool Tool and library for handling Web ARChive (WARC) files. ''' from .version import *
Java
#ifndef __TARGET_CORE_USER_H #define __TARGET_CORE_USER_H /* This header will be used by application too */ #include <linux/types.h> #include <linux/uio.h> #define TCMU_VERSION "2.0" /* * Ring Design * ----------- * * The mmaped area is divided into three parts: * 1) The mailbox (struct tcmu_mailbox, below) * 2) The command ring * 3) Everything beyond the command ring (data) * * The mailbox tells userspace the offset of the command ring from the * start of the shared memory region, and how big the command ring is. * * The kernel passes SCSI commands to userspace by putting a struct * tcmu_cmd_entry in the ring, updating mailbox->cmd_head, and poking * userspace via uio's interrupt mechanism. * * tcmu_cmd_entry contains a header. If the header type is PAD, * userspace should skip hdr->length bytes (mod cmdr_size) to find the * next cmd_entry. * * Otherwise, the entry will contain offsets into the mmaped area that * contain the cdb and data buffers -- the latter accessible via the * iov array. iov addresses are also offsets into the shared area. * * When userspace is completed handling the command, set * entry->rsp.scsi_status, fill in rsp.sense_buffer if appropriate, * and also set mailbox->cmd_tail equal to the old cmd_tail plus * hdr->length, mod cmdr_size. If cmd_tail doesn't equal cmd_head, it * should process the next packet the same way, and so on. */ #define TCMU_MAILBOX_VERSION 2 #define ALIGN_SIZE 64 /* Should be enough for most CPUs */ #define TCMU_MAILBOX_FLAG_CAP_OOOC (1 << 0) /* Out-of-order completions */ struct tcmu_mailbox { __u16 version; __u16 flags; __u32 cmdr_off; __u32 cmdr_size; __u32 cmd_head; /* Updated by user. On its own cacheline */ __u32 cmd_tail __attribute__((__aligned__(ALIGN_SIZE))); } __packed; enum tcmu_opcode { TCMU_OP_PAD = 0, TCMU_OP_CMD, }; /* * Only a few opcodes, and length is 8-byte aligned, so use low bits for opcode. */ struct tcmu_cmd_entry_hdr { __u32 len_op; __u16 cmd_id; __u8 kflags; #define TCMU_UFLAG_UNKNOWN_OP 0x1 __u8 uflags; } __packed; #define TCMU_OP_MASK 0x7 static inline enum tcmu_opcode tcmu_hdr_get_op(__u32 len_op) { return len_op & TCMU_OP_MASK; } static inline void tcmu_hdr_set_op(__u32 *len_op, enum tcmu_opcode op) { *len_op &= ~TCMU_OP_MASK; *len_op |= (op & TCMU_OP_MASK); } static inline __u32 tcmu_hdr_get_len(__u32 len_op) { return len_op & ~TCMU_OP_MASK; } static inline void tcmu_hdr_set_len(__u32 *len_op, __u32 len) { *len_op &= TCMU_OP_MASK; *len_op |= len; } /* Currently the same as SCSI_SENSE_BUFFERSIZE */ #define TCMU_SENSE_BUFFERSIZE 96 struct tcmu_cmd_entry { struct tcmu_cmd_entry_hdr hdr; union { struct { uint32_t iov_cnt; uint32_t iov_bidi_cnt; uint32_t iov_dif_cnt; uint64_t cdb_off; uint64_t __pad1; uint64_t __pad2; struct iovec iov[0]; } req; struct { uint8_t scsi_status; uint8_t __pad1; uint16_t __pad2; uint32_t __pad3; char sense_buffer[TCMU_SENSE_BUFFERSIZE]; } rsp; }; } __packed; #define TCMU_OP_ALIGN_SIZE sizeof(uint64_t) enum tcmu_genl_cmd { TCMU_CMD_UNSPEC, TCMU_CMD_ADDED_DEVICE, TCMU_CMD_REMOVED_DEVICE, __TCMU_CMD_MAX, }; #define TCMU_CMD_MAX (__TCMU_CMD_MAX - 1) enum tcmu_genl_attr { TCMU_ATTR_UNSPEC, TCMU_ATTR_DEVICE, TCMU_ATTR_MINOR, __TCMU_ATTR_MAX, }; #define TCMU_ATTR_MAX (__TCMU_ATTR_MAX - 1) #endif
Java
/* * Symphony - A modern community (forum/SNS/blog) platform written in Java. * Copyright (C) 2012-2017, b3log.org & hacpai.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.b3log.symphony.processor; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.b3log.latke.Keys; import org.b3log.latke.Latkes; import org.b3log.latke.ioc.inject.Inject; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.model.Pagination; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.servlet.HTTPRequestContext; import org.b3log.latke.servlet.HTTPRequestMethod; import org.b3log.latke.servlet.annotation.After; import org.b3log.latke.servlet.annotation.Before; import org.b3log.latke.servlet.annotation.RequestProcessing; import org.b3log.latke.servlet.annotation.RequestProcessor; import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer; import org.b3log.latke.util.Locales; import org.b3log.latke.util.Stopwatchs; import org.b3log.latke.util.Strings; import org.b3log.symphony.model.Article; import org.b3log.symphony.model.Common; import org.b3log.symphony.model.UserExt; import org.b3log.symphony.processor.advice.AnonymousViewCheck; import org.b3log.symphony.processor.advice.PermissionGrant; import org.b3log.symphony.processor.advice.stopwatch.StopwatchEndAdvice; import org.b3log.symphony.processor.advice.stopwatch.StopwatchStartAdvice; import org.b3log.symphony.service.*; import org.b3log.symphony.util.Emotions; import org.b3log.symphony.util.Markdowns; import org.b3log.symphony.util.Symphonys; import org.json.JSONObject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.util.*; /** * Index processor. * <p> * <ul> * <li>Shows index (/), GET</li> * <li>Shows recent articles (/recent), GET</li> * <li>Shows hot articles (/hot), GET</li> * <li>Shows perfect articles (/perfect), GET</li> * <li>Shows about (/about), GET</li> * <li>Shows b3log (/b3log), GET</li> * <li>Shows SymHub (/symhub), GET</li> * <li>Shows kill browser (/kill-browser), GET</li> * </ul> * </p> * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://vanessa.b3log.org">Liyuan Li</a> * @version 1.12.3.24, Dec 26, 2016 * @since 0.2.0 */ @RequestProcessor public class IndexProcessor { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(IndexProcessor.class.getName()); /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * User management service. */ @Inject private UserMgmtService userMgmtService; /** * Data model service. */ @Inject private DataModelService dataModelService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Timeline management service. */ @Inject private TimelineMgmtService timelineMgmtService; /** * Shows md guide. * * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/guide/markdown", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showMDGuide(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("other/md-guide.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); InputStream inputStream = null; try { inputStream = IndexProcessor.class.getResourceAsStream("/md_guide.md"); final String md = IOUtils.toString(inputStream, "UTF-8"); String html = Emotions.convert(md); html = Markdowns.toHTML(html); dataModel.put("md", md); dataModel.put("html", html); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Loads markdown guide failed", e); } finally { IOUtils.closeQuietly(inputStream); } dataModelService.fillHeaderAndFooter(request, response, dataModel); } /** * Shows index. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = {"", "/"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showIndex(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("index.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final List<JSONObject> recentArticles = articleQueryService.getIndexRecentArticles(avatarViewMode); dataModel.put(Common.RECENT_ARTICLES, recentArticles); JSONObject currentUser = userQueryService.getCurrentUser(request); if (null == currentUser) { userMgmtService.tryLogInWithCookie(request, context.getResponse()); } currentUser = userQueryService.getCurrentUser(request); if (null != currentUser) { if (!UserExt.finshedGuide(currentUser)) { response.sendRedirect(Latkes.getServePath() + "/guide"); return; } final String userId = currentUser.optString(Keys.OBJECT_ID); final int pageSize = Symphonys.getInt("indexArticlesCnt"); final List<JSONObject> followingTagArticles = articleQueryService.getFollowingTagArticles( avatarViewMode, userId, 1, pageSize); dataModel.put(Common.FOLLOWING_TAG_ARTICLES, followingTagArticles); final List<JSONObject> followingUserArticles = articleQueryService.getFollowingUserArticles( avatarViewMode, userId, 1, pageSize); dataModel.put(Common.FOLLOWING_USER_ARTICLES, followingUserArticles); } else { dataModel.put(Common.FOLLOWING_TAG_ARTICLES, Collections.emptyList()); dataModel.put(Common.FOLLOWING_USER_ARTICLES, Collections.emptyList()); } final List<JSONObject> perfectArticles = articleQueryService.getIndexPerfectArticles(avatarViewMode); dataModel.put(Common.PERFECT_ARTICLES, perfectArticles); final List<JSONObject> timelines = timelineMgmtService.getTimelines(); dataModel.put(Common.TIMELINES, timelines); dataModel.put(Common.SELECTED, Common.INDEX); dataModelService.fillHeaderAndFooter(request, response, dataModel); dataModelService.fillIndexTags(dataModel); } /** * Shows recent articles. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = {"/recent", "/recent/hot", "/recent/good", "/recent/reply"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showRecent(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("recent.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); String pageNumStr = request.getParameter("p"); if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) { pageNumStr = "1"; } final int pageNum = Integer.valueOf(pageNumStr); int pageSize = Symphonys.getInt("indexArticlesCnt"); final JSONObject user = userQueryService.getCurrentUser(request); if (null != user) { pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE); if (!UserExt.finshedGuide(user)) { response.sendRedirect(Latkes.getServePath() + "/guide"); return; } } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); String sortModeStr = StringUtils.substringAfter(request.getRequestURI(), "/recent"); int sortMode; switch (sortModeStr) { case "": sortMode = 0; break; case "/hot": sortMode = 1; break; case "/good": sortMode = 2; break; case "/reply": sortMode = 3; break; default: sortMode = 0; } final JSONObject result = articleQueryService.getRecentArticles(avatarViewMode, sortMode, pageNum, pageSize); final List<JSONObject> allArticles = (List<JSONObject>) result.get(Article.ARTICLES); dataModel.put(Common.SELECTED, Common.RECENT); final List<JSONObject> stickArticles = new ArrayList<>(); final Iterator<JSONObject> iterator = allArticles.iterator(); while (iterator.hasNext()) { final JSONObject article = iterator.next(); final boolean stick = article.optInt(Article.ARTICLE_T_STICK_REMAINS) > 0; article.put(Article.ARTICLE_T_IS_STICK, stick); if (stick) { stickArticles.add(article); iterator.remove(); } } dataModel.put(Common.STICK_ARTICLES, stickArticles); dataModel.put(Common.LATEST_ARTICLES, allArticles); final JSONObject pagination = result.getJSONObject(Pagination.PAGINATION); final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT); final List<Integer> pageNums = (List<Integer>) pagination.get(Pagination.PAGINATION_PAGE_NUMS); if (!pageNums.isEmpty()) { dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0)); dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1)); } dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum); dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); dataModelService.fillHeaderAndFooter(request, response, dataModel); dataModelService.fillRandomArticles(avatarViewMode, dataModel); dataModelService.fillSideHotArticles(avatarViewMode, dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); dataModel.put(Common.CURRENT, StringUtils.substringAfter(request.getRequestURI(), "/recent")); } /** * Shows hot articles. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/hot", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showHotArticles(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("hot.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); int pageSize = Symphonys.getInt("indexArticlesCnt"); final JSONObject user = userQueryService.getCurrentUser(request); if (null != user) { pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE); } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final List<JSONObject> indexArticles = articleQueryService.getHotArticles(avatarViewMode, pageSize); dataModel.put(Common.INDEX_ARTICLES, indexArticles); dataModel.put(Common.SELECTED, Common.HOT); Stopwatchs.start("Fills"); try { dataModelService.fillHeaderAndFooter(request, response, dataModel); if (!(Boolean) dataModel.get(Common.IS_MOBILE)) { dataModelService.fillRandomArticles(avatarViewMode, dataModel); } dataModelService.fillSideHotArticles(avatarViewMode, dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } finally { Stopwatchs.end(); } } /** * Shows SymHub page. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/symhub", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showSymHub(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("other/symhub.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final List<JSONObject> syms = Symphonys.getSyms(); dataModel.put("syms", (Object) syms); Stopwatchs.start("Fills"); try { final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); dataModelService.fillHeaderAndFooter(request, response, dataModel); if (!(Boolean) dataModel.get(Common.IS_MOBILE)) { dataModelService.fillRandomArticles(avatarViewMode, dataModel); } dataModelService.fillSideHotArticles(avatarViewMode, dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } finally { Stopwatchs.end(); } } /** * Shows perfect articles. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/perfect", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showPerfectArticles(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("perfect.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); String pageNumStr = request.getParameter("p"); if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) { pageNumStr = "1"; } final int pageNum = Integer.valueOf(pageNumStr); int pageSize = Symphonys.getInt("indexArticlesCnt"); final JSONObject user = userQueryService.getCurrentUser(request); if (null != user) { pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE); if (!UserExt.finshedGuide(user)) { response.sendRedirect(Latkes.getServePath() + "/guide"); return; } } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject result = articleQueryService.getPerfectArticles(avatarViewMode, pageNum, pageSize); final List<JSONObject> perfectArticles = (List<JSONObject>) result.get(Article.ARTICLES); dataModel.put(Common.PERFECT_ARTICLES, perfectArticles); dataModel.put(Common.SELECTED, Common.PERFECT); final JSONObject pagination = result.getJSONObject(Pagination.PAGINATION); final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT); final List<Integer> pageNums = (List<Integer>) pagination.get(Pagination.PAGINATION_PAGE_NUMS); if (!pageNums.isEmpty()) { dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0)); dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1)); } dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum); dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); dataModelService.fillHeaderAndFooter(request, response, dataModel); dataModelService.fillRandomArticles(avatarViewMode, dataModel); dataModelService.fillSideHotArticles(avatarViewMode, dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } /** * Shows about. * * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/about", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = StopwatchEndAdvice.class) public void showAbout(final HttpServletResponse response) throws Exception { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", "https://hacpai.com/article/1440573175609"); response.flushBuffer(); } /** * Shows b3log. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/b3log", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showB3log(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("other/b3log.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); dataModelService.fillHeaderAndFooter(request, response, dataModel); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); dataModelService.fillRandomArticles(avatarViewMode, dataModel); dataModelService.fillSideHotArticles(avatarViewMode, dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } /** * Shows kill browser page with the specified context. * * @param context the specified context * @param request the specified HTTP servlet request * @param response the specified HTTP servlet response */ @RequestProcessing(value = "/kill-browser", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = StopwatchEndAdvice.class) public void showKillBrowser(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); renderer.setTemplateName("other/kill-browser.ftl"); context.setRenderer(renderer); final Map<String, Object> dataModel = renderer.getDataModel(); final Map<String, String> langs = langPropsService.getAll(Locales.getLocale()); dataModel.putAll(langs); Keys.fillRuntime(dataModel); dataModelService.fillMinified(dataModel); } }
Java
/* Copyright 2011 MCForge Dual-licensed under the Educational Community License, Version 2.0 and the GNU General Public License, Version 3 (the "Licenses"); you may not use this file except in compliance with the Licenses. You may obtain a copy of the Licenses at http://www.osedu.org/licenses/ECL-2.0 http://www.gnu.org/licenses/gpl-3.0.html Unless required by applicable law or agreed to in writing, software distributed under the Licenses are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licenses for the specific language governing permissions and limitations under the Licenses. */ using System; using System.IO; namespace MCForge { public class CmdMap : Command { public override string name { get { return "map"; } } public override string shortcut { get { return ""; } } public override string type { get { return "mod"; } } public override bool museumUsable { get { return true; } } public override LevelPermission defaultRank { get { return LevelPermission.Guest; } } public CmdMap() { } public override void Use(Player p, string message) { if (message == "") message = p.level.name; Level foundLevel; if (message.IndexOf(' ') == -1) { foundLevel = Level.Find(message); if (foundLevel == null) { if (p != null) { foundLevel = p.level; } } else { Player.SendMessage(p, "MOTD: &b" + foundLevel.motd); Player.SendMessage(p, "Finite mode: " + FoundCheck(foundLevel.finite)); Player.SendMessage(p, "Animal AI: " + FoundCheck(foundLevel.ai)); Player.SendMessage(p, "Edge water: " + FoundCheck(foundLevel.edgeWater)); Player.SendMessage(p, "Grass growing: " + FoundCheck(foundLevel.GrassGrow)); Player.SendMessage(p, "Physics speed: &b" + foundLevel.speedPhysics); Player.SendMessage(p, "Physics overload: &b" + foundLevel.overload); Player.SendMessage(p, "Survival death: " + FoundCheck(foundLevel.Death) + "(Fall: " + foundLevel.fall + ", Drown: " + foundLevel.drown + ")"); Player.SendMessage(p, "Killer blocks: " + FoundCheck(foundLevel.Killer)); Player.SendMessage(p, "Unload: " + FoundCheck(foundLevel.unload)); Player.SendMessage(p, "Auto physics: " + FoundCheck(foundLevel.rp)); Player.SendMessage(p, "Instant building: " + FoundCheck(foundLevel.Instant)); Player.SendMessage(p, "RP chat: " + FoundCheck(!foundLevel.worldChat)); return; } } else { foundLevel = Level.Find(message.Split(' ')[0]); if (foundLevel == null || message.Split(' ')[0].ToLower() == "ps" || message.Split(' ')[0].ToLower() == "rp") foundLevel = p.level; else message = message.Substring(message.IndexOf(' ') + 1); } if (p != null) if (p.group.Permission < LevelPermission.Operator) { Player.SendMessage(p, "Setting map options is reserved to OP+"); return; } string foundStart; if (message.IndexOf(' ') == -1) foundStart = message.ToLower(); else foundStart = message.Split(' ')[0].ToLower(); try { switch (foundStart) { case "theme": foundLevel.theme = message.Substring(message.IndexOf(' ') + 1); foundLevel.ChatLevel("Map theme: &b" + foundLevel.theme); break; case "finite": foundLevel.finite = !foundLevel.finite; foundLevel.ChatLevel("Finite mode: " + FoundCheck(foundLevel.finite)); break; case "ai": foundLevel.ai = !foundLevel.ai; foundLevel.ChatLevel("Animal AI: " + FoundCheck(foundLevel.ai)); break; case "edge": foundLevel.edgeWater = !foundLevel.edgeWater; foundLevel.ChatLevel("Edge water: " + FoundCheck(foundLevel.edgeWater)); break; case "grass": foundLevel.GrassGrow = !foundLevel.GrassGrow; foundLevel.ChatLevel("Growing grass: " + FoundCheck(foundLevel.GrassGrow)); break; case "ps": case "physicspeed": if (int.Parse(message.Split(' ')[1]) < 10) { Player.SendMessage(p, "Cannot go below 10"); return; } foundLevel.speedPhysics = int.Parse(message.Split(' ')[1]); foundLevel.ChatLevel("Physics speed: &b" + foundLevel.speedPhysics); break; case "overload": if (int.Parse(message.Split(' ')[1]) < 500) { Player.SendMessage(p, "Cannot go below 500 (default is 1500)"); return; } if (p.group.Permission < LevelPermission.Admin && int.Parse(message.Split(' ')[1]) > 2500) { Player.SendMessage(p, "Only SuperOPs may set higher than 2500"); return; } foundLevel.overload = int.Parse(message.Split(' ')[1]); foundLevel.ChatLevel("Physics overload: &b" + foundLevel.overload); break; case "motd": if (message.Split(' ').Length == 1) foundLevel.motd = "ignore"; else foundLevel.motd = message.Substring(message.IndexOf(' ') + 1); foundLevel.ChatLevel("Map MOTD: &b" + foundLevel.motd); break; case "death": foundLevel.Death = !foundLevel.Death; foundLevel.ChatLevel("Survival death: " + FoundCheck(foundLevel.Death)); break; case "killer": foundLevel.Killer = !foundLevel.Killer; foundLevel.ChatLevel("Killer blocks: " + FoundCheck(foundLevel.Killer)); break; case "fall": foundLevel.fall = int.Parse(message.Split(' ')[1]); foundLevel.ChatLevel("Fall distance: &b" + foundLevel.fall); break; case "drown": foundLevel.drown = int.Parse(message.Split(' ')[1]) * 10; foundLevel.ChatLevel("Drown time: &b" + (foundLevel.drown / 10)); break; case "unload": foundLevel.unload = !foundLevel.unload; foundLevel.ChatLevel("Auto unload: " + FoundCheck(foundLevel.unload)); break; case "rp": case "restartphysics": foundLevel.rp = !foundLevel.rp; foundLevel.ChatLevel("Auto physics: " + FoundCheck(foundLevel.rp)); break; case "instant": if (p.group.Permission < LevelPermission.Admin) { Player.SendMessage(p, "This is reserved for Super+"); return; } foundLevel.Instant = !foundLevel.Instant; foundLevel.ChatLevel("Instant building: " + FoundCheck(foundLevel.Instant)); break; case "chat": foundLevel.worldChat = !foundLevel.worldChat; foundLevel.ChatLevel("RP chat: " + FoundCheck(!foundLevel.worldChat)); break; default: Player.SendMessage(p, "Could not find option entered."); return; } foundLevel.changed = true; if (p.level != foundLevel) Player.SendMessage(p, "/map finished!"); } catch { Player.SendMessage(p, "INVALID INPUT"); } } public string FoundCheck(bool check) { if (check) return "&aON"; else return "&cOFF"; } public override void Help(Player p) { Player.SendMessage(p, "/map [level] [toggle] - Sets [toggle] on [map]"); Player.SendMessage(p, "Possible toggles: theme, finite, ai, edge, ps, overload, motd, death, fall, drown, unload, rp, instant, killer, chat"); Player.SendMessage(p, "Edge will cause edge water to flow."); Player.SendMessage(p, "Grass will make grass not grow without physics"); Player.SendMessage(p, "Finite will cause all liquids to be finite."); Player.SendMessage(p, "AI will make animals hunt or flee."); Player.SendMessage(p, "PS will set the map's physics speed."); Player.SendMessage(p, "Overload will change how easy/hard it is to kill physics."); Player.SendMessage(p, "MOTD will set a custom motd for the map. (leave blank to reset)"); Player.SendMessage(p, "Death will allow survival-style dying (falling, drowning)"); Player.SendMessage(p, "Fall/drown set the distance/time before dying from each."); Player.SendMessage(p, "Killer turns killer blocks on and off."); Player.SendMessage(p, "Unload sets whether the map unloads when no one's there."); Player.SendMessage(p, "RP sets whether the physics auto-start for the map"); Player.SendMessage(p, "Instant mode works by not updating everyone's screens"); Player.SendMessage(p, "Chat sets the map to recieve no messages from other maps"); } } }
Java
require 'test/unit' class FizzbuzzTest < Test::Unit::TestCase # Called before every test method runs. Can be used # to set up fixture information. def setup # Do nothing end # Called after every test method runs. Can be used to tear # down fixture information. def teardown # Do nothing end # Fake test def test_fail expected = 1 actual =1 assert_same expected, actual # fail('Not implemented') end def test_fizzbuzz require './fizzbuzz.d/rb-fizzbuzz' res=[] 1.upto(100).each {|e| next if fizbuz e, res next if fiz e, res next if buz e, res res << e } assert_same 100, res.length end end
Java
/* Copyright 2013 Statoil ASA. This file is part of the Open Porous Media project (OPM). OPM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OPM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OPM. If not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_MODULE ParserIntegrationTests #include <boost/test/unit_test.hpp> #include <boost/test/test_tools.hpp> #include <boost/filesystem.hpp> #include <ostream> #include <fstream> #include <opm/parser/eclipse/Deck/Deck.hpp> #include <opm/parser/eclipse/Parser/Parser.hpp> #include <opm/parser/eclipse/Parser/ParserRecord.hpp> #include <opm/parser/eclipse/Parser/ParserEnums.hpp> using namespace Opm; using namespace boost::filesystem; static void createDeckWithInclude(path& datafile, std::string addEndKeyword) { path tmpdir = temp_directory_path(); path root = tmpdir / unique_path("%%%%-%%%%"); path absoluteInclude = root / "absolute.include"; path includePath1 = root / "include"; path includePath2 = root / "include2"; path pathIncludeFile = "path.file"; create_directories(root); create_directories(includePath1); create_directories(includePath2); { datafile = root / "TEST.DATA"; std::ofstream of(datafile.string().c_str()); of << "PATHS" << std::endl; of << "PATH1 '" << includePath1.string() << "' /" << std::endl; of << "PATH2 '" << includePath2.string() << "' /" << std::endl; of << "/" << std::endl; of << "INCLUDE" << std::endl; of << " \'relative.include\' /" << std::endl; of << std::endl; of << "INCLUDE" << std::endl; of << " \'" << absoluteInclude.string() << "\' /" << std::endl; of << std::endl; of << "INCLUDE" << std::endl; of << " \'include/nested.include\' /" << std::endl; of << std::endl; of << std::endl; of << "INCLUDE" << std::endl; of << " \'$PATH1/" << pathIncludeFile.string() << "\' /" << std::endl; of << std::endl; of << "INCLUDE" << std::endl; of << " \'$PATH2/" << pathIncludeFile.string() << "\' /" << std::endl; of.close(); } { path relativeInclude = root / "relative.include"; std::ofstream of(relativeInclude.string().c_str()); of << "START" << std::endl; of << " 10 'FEB' 2012 /" << std::endl; of.close(); } { std::ofstream of(absoluteInclude.string().c_str()); if (addEndKeyword.length() > 0) { of << addEndKeyword << std::endl; } of << "DIMENS" << std::endl; of << " 10 20 30 /" << std::endl; of.close(); } { path nestedInclude = includePath1 / "nested.include"; path gridInclude = includePath1 / "grid.include"; std::ofstream of(nestedInclude.string().c_str()); of << "INCLUDE" << std::endl; of << " \'$PATH1/grid.include\' /" << std::endl; of.close(); std::ofstream of2(gridInclude.string().c_str()); of2 << "GRIDUNIT" << std::endl; of2 << "/" << std::endl; of2.close(); } { path fullPathToPathIncludeFile1 = includePath1 / pathIncludeFile; std::ofstream of1(fullPathToPathIncludeFile1.string().c_str()); of1 << "TITLE" << std::endl; of1 << "This is the title /" << std::endl; of1.close(); path fullPathToPathIncludeFile2 = includePath2 / pathIncludeFile; std::ofstream of2(fullPathToPathIncludeFile2.string().c_str()); of2 << "BOX" << std::endl; of2 << " 1 2 3 4 5 6 /" << std::endl; of2.close(); } std::cout << datafile << std::endl; } BOOST_AUTO_TEST_CASE(parse_fileWithWWCTKeyword_deckReturned) { path datafile; Parser parser; createDeckWithInclude (datafile, ""); auto deck = parser.parseFile(datafile.string()); BOOST_CHECK( deck.hasKeyword("START")); BOOST_CHECK( deck.hasKeyword("DIMENS")); BOOST_CHECK( deck.hasKeyword("GRIDUNIT")); } BOOST_AUTO_TEST_CASE(parse_fileWithENDINCKeyword_deckReturned) { path datafile; Parser parser; createDeckWithInclude (datafile, "ENDINC"); auto deck = parser.parseFile(datafile.string()); BOOST_CHECK( deck.hasKeyword("START")); BOOST_CHECK( !deck.hasKeyword("DIMENS")); BOOST_CHECK( deck.hasKeyword("GRIDUNIT")); } BOOST_AUTO_TEST_CASE(parse_fileWithENDKeyword_deckReturned) { path datafile; Parser parser; createDeckWithInclude (datafile, "END"); auto deck = parser.parseFile(datafile.string()); BOOST_CHECK( deck.hasKeyword("START")); BOOST_CHECK( !deck.hasKeyword("DIMENS")); BOOST_CHECK( !deck.hasKeyword("GRIDUNIT")); } BOOST_AUTO_TEST_CASE(parse_fileWithPathsKeyword_IncludeExtendsPath) { path datafile; Parser parser; createDeckWithInclude (datafile, ""); auto deck = parser.parseFile(datafile.string()); BOOST_CHECK( deck.hasKeyword("TITLE")); BOOST_CHECK( deck.hasKeyword("BOX")); }
Java
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Newegg.Oversea.Silverlight.ControlPanel.Core.Base; using ECCentral.BizEntity.Enum; using ECCentral.BizEntity.MKT; using Newegg.Oversea.Silverlight.Utilities.Validation; using ECCentral.BizEntity; namespace ECCentral.Portal.UI.MKT.Models { public class AmbassadorNewsVM : ModelBase { public string CompanyCode { get; set; } public int? SysNo { get; set; } private int? _ReferenceSysNo; public int? ReferenceSysNo { get { return _ReferenceSysNo; } set { base.SetValue("ReferenceSysNo", ref _ReferenceSysNo, value); } } private string _Title; [Validate(ValidateType.Required)] [Validate(ValidateType.MaxLength,100)] public string Title { get { return _Title; } set { base.SetValue("Title", ref _Title, value); } } private string _Content; [Validate(ValidateType.Required)] public string Content { get { return _Content; } set { base.SetValue("Content", ref _Content, value); } } private AmbassadorNewsStatus? status; [Validate(ValidateType.Required)] public AmbassadorNewsStatus? Status { get { return status; } set { base.SetValue("Status", ref status, value); } } } }
Java
using ServiceStack.OrmLite; using System; using System.Configuration; using System.Data; namespace Bm2s.Data.Utils { /// <summary> /// Data access point /// </summary> public class Datas { /// <summary> /// Database provider /// </summary> private IOrmLiteDialectProvider _dbProvider; /// <summary> /// Gets the database provider /// </summary> public IOrmLiteDialectProvider DbProvider { get { if (this._dbProvider == null) { switch (ConfigurationManager.AppSettings["DbProvider"].ToLower()) { case "oracle": this._dbProvider = OracleDialect.Provider; break; case "mysql" : this._dbProvider = MySqlDialect.Provider; break; case "postgresql": this._dbProvider = PostgreSqlDialect.Provider; break; case "mssqlserver": this._dbProvider = SqlServerDialect.Provider; break; default: this._dbProvider = null; break; } } return this._dbProvider; } } /// <summary> /// Database connection /// </summary> private IDbConnection _dbConnection; /// <summary> /// Gets the database connection /// </summary> public IDbConnection DbConnection { get { if (this._dbConnection == null) { this._dbConnection = this.DbConnectionFactory.OpenDbConnection(); } return this._dbConnection; } } /// <summary> /// Database connection factory /// </summary> private IDbConnectionFactory _dbConnectionFactory; /// <summary> /// Gets the database connection factory /// </summary> public IDbConnectionFactory DbConnectionFactory { get { if (this._dbConnectionFactory == null) { this._dbConnectionFactory = new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["bm2s"].ConnectionString, this.DbProvider); } return this._dbConnectionFactory; } } /// <summary> /// Constructor for the singleton /// </summary> protected Datas() { this.CheckDatabaseSchema(); } /// <summary> /// Creation of the schemas /// </summary> public virtual void CheckDatabaseSchema() { } /// <summary> /// Create datas for the first use /// </summary> public virtual void CheckFirstUseDatas() { } } }
Java
/** * Created by caimiao on 15-6-14. */ define(function(require, exports, module) { exports.hello= function (echo) { alert(echo); }; })
Java