answer
stringlengths
15
1.25M
from django.conf.urls import url from ..views import collections as views urlpatterns = [ url('^create/$', views.Create.as_view(), name='create'), url('^c:(?P<slug>[-\w]+)/$', views.Detail.as_view(), name='detail'), url('^$', views.List.as_view(), name='list'), ]
package net.fortuna.ical4j.model.property; import net.fortuna.ical4j.model.ParameterList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyFactoryImpl; import net.fortuna.ical4j.model.UtcOffset; import net.fortuna.ical4j.model.ValidationException; /** * $Id$ * * Created: [Apr 6, 2004] * * Defines a TZOFFSETTO iCalendar component property. * @author benf */ public class TzOffsetTo extends Property { private static final long serialVersionUID = <API key>; private UtcOffset offset; /** * Default constructor. */ public TzOffsetTo() { super(TZOFFSETTO, PropertyFactoryImpl.getInstance()); } /** * @param value an offset value */ public TzOffsetTo(String value) { super(TZOFFSETTO, PropertyFactoryImpl.getInstance()); setValue(value); } /** * @param aList a list of parameters for this component * @param aValue a value string for this component */ public TzOffsetTo(final ParameterList aList, final String aValue) { super(TZOFFSETTO, aList, PropertyFactoryImpl.getInstance()); setValue(aValue); } /** * @param anOffset a timezone offset in milliseconds */ public TzOffsetTo(final UtcOffset anOffset) { super(TZOFFSETTO, PropertyFactoryImpl.getInstance()); offset = anOffset; } /** * @param aList a list of parameters for this component * @param anOffset a timezone offset in milliseconds */ public TzOffsetTo(final ParameterList aList, final UtcOffset anOffset) { super(TZOFFSETTO, aList, PropertyFactoryImpl.getInstance()); offset = anOffset; } /** * @return Returns the offset. */ public final UtcOffset getOffset() { return offset; } /** * {@inheritDoc} */ public final void setValue(final String aValue) { offset = new UtcOffset(aValue); } /** * {@inheritDoc} */ public final String getValue() { if (offset != null) { return offset.toString(); } return ""; } /** * @param offset The offset to set. */ public final void setOffset(final UtcOffset offset) { this.offset = offset; } /** * {@inheritDoc} */ public final void validate() throws ValidationException { // TODO: Auto-generated method stub } }
#pragma once #include <ABI38_0_0React/components/view/ViewShadowNode.h> #include <ABI38_0_0React/core/<API key>.h> namespace ABI38_0_0facebook { namespace ABI38_0_0React { using <API key> = <API key><ViewShadowNode>; } // namespace ABI38_0_0React } // namespace ABI38_0_0facebook
id: view-style-props title: View Style Props Example js import React from "react"; import { View, StyleSheet } from "react-native"; const ViewStyleProps = () => { return ( <View style={styles.container}> <View style={styles.top} /> <View style={styles.middle} /> <View style={styles.bottom} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "space-between", backgroundColor: "#fff", padding: 20, margin: 10, }, top: { flex: 0.3, backgroundColor: "grey", borderWidth: 5, borderTopLeftRadius: 20, <API key>: 20, }, middle: { flex: 0.3, backgroundColor: "beige", borderWidth: 5, }, bottom: { flex: 0.3, backgroundColor: "pink", borderWidth: 5, <API key>: 20, <API key>: 20, }, }); export default ViewStyleProps; # Reference ## Props `borderRightColor` | Type | Required | | | [color](https://reactnative.dev/docs/colors) | No | `backfaceVisibility` | Type | Required | | | enum('visible', 'hidden') | No | `borderBottomColor` | Type | Required | | | [color](https://reactnative.dev/docs/colors) | No | `<API key>` | Type | Required | | | number | No | `<API key>` | Type | Required | | | number | No | `<API key>` | Type | Required | | | number | No | `<API key>` | Type | Required | | | number | No | `borderBottomWidth` | Type | Required | | | number | No | `borderColor` | Type | Required | | | [color](https://reactnative.dev/docs/colors) | No | `borderEndColor` | Type | Required | | | [color](https://reactnative.dev/docs/colors) | No | `borderLeftColor` | Type | Required | | | [color](https://reactnative.dev/docs/colors) | No | `borderLeftWidth` | Type | Required | | | number | No | `borderRadius` If the rounded border is not visible, try applying `overflow: 'hidden'` as well. | Type | Required | | | number | No | `backgroundColor` | Type | Required | | | [color](https://reactnative.dev/docs/colors) | No | `borderRightWidth` | Type | Required | | | number | No | `borderStartColor` | Type | Required | | | [color](https://reactnative.dev/docs/colors) | No | `borderStyle` | Type | Required | | | enum('solid', 'dotted', 'dashed') | No | `borderTopColor` | Type | Required | | | [color](https://reactnative.dev/docs/colors) | No | `borderTopEndRadius` | Type | Required | | | number | No | `borderTopLeftRadius` | Type | Required | | | number | No | `<API key>` | Type | Required | | | number | No | `<API key>` | Type | Required | | | number | No | `borderTopWidth` | Type | Required | | | number | No | `borderWidth` | Type | Required | | | number | No | `opacity` | Type | Required | | | number | No | `elevation` (Android-only) Sets the elevation of a view, using Android's underlying [elevation API](https://developer.android.com/training/material/shadows-clipping.html#Elevation). This adds a drop shadow to the item and affects z-order for overlapping views. Only supported on Android 5.0+, has no effect on earlier versions. | Type | Required | Platform | | | number | No | Android |
<!DOCTYPE html PUBLIC "- window.onload = function () {pageLoad();}; </script></head><body><div id="package-header"><ul class="links" id="page-menu"><li><a href="index.html">Contents</a></li><li><a href="doc-index.html">Index</a></li></ul><p class="caption"><API key>.1.2.0: A class for types with a default value</p></div><div id="content"><div id="index"><p class="caption">Index</p><table><tr><td class="src">def</td><td class="module"><a href="Data-Default-Class.html
<?php return [ 'components' => [ 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=yii2advanced', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => '@common/layouts/mail', // send all mails to a file by default. You have to set // 'useFileTransport' to false and configure a transport // for the mailer to send real emails. 'useFileTransport' => true, ], 'reCaptcha' => [ 'name' => 'reCaptcha', 'class' => 'himiklab\yii2\recaptcha\ReCaptcha', //todo @HJ needs to be set every template 'siteKey' => '<API key>', //todo @HJ needs to be set every template 'secret' => '<API key>', ], ], ];
{-| Module : <API key> Description : Bottom-up typed numeric expressions Copyright : (c) Michal Konecny, Pieter Collins License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable @<API key>@ provides a version of @Prelude@ where unary and binary operations such as @not@, @+@, @==@ have their result type derived from the parameter type(s). This module facilitates a single-line import for the package mixed-types-num. See the re-exported modules for further details. -} module <API key> ( -- * Re-exporting Prelude, hiding the operators we are changing module Numeric.MixedTypes.PreludeHiding, -- * Error-collecting wrapper type CN, cn, unCN, <API key>, -- * A part of package ``convertible'' module Data.Convertible.Base, -- * Modules with Prelude alternatives module Numeric.MixedTypes.Literals, module Numeric.MixedTypes.Bool, module Numeric.MixedTypes.Eq, module Numeric.MixedTypes.Ord, module Numeric.MixedTypes.MinMaxAbs, module Numeric.MixedTypes.AddSub, module Numeric.MixedTypes.Round, module Numeric.MixedTypes.Reduce, module Numeric.MixedTypes.Mul, module Numeric.MixedTypes.Ring, module Numeric.MixedTypes.Div, module Numeric.MixedTypes.Power, module Numeric.MixedTypes.Field, module Numeric.MixedTypes.Elementary, module Numeric.MixedTypes.Complex, -- module Numeric.CollectErrors, module Utils.TH.DeclForTypes, module Utils.Test.EnforceRange, -- * Re-export for convenient Rational literals (%) ) where import Data.Ratio ((%)) import Numeric.CollectErrors (CN, cn, unCN, <API key>) import Data.Convertible.Instances.Num() import Data.Convertible.Base import Utils.TH.DeclForTypes import Utils.Test.EnforceRange import Numeric.MixedTypes.PreludeHiding import Numeric.MixedTypes.Literals import Numeric.MixedTypes.Bool import Numeric.MixedTypes.Eq import Numeric.MixedTypes.Ord import Numeric.MixedTypes.MinMaxAbs import Numeric.MixedTypes.AddSub import Numeric.MixedTypes.Round import Numeric.MixedTypes.Reduce import Numeric.MixedTypes.Mul import Numeric.MixedTypes.Ring import Numeric.MixedTypes.Div import Numeric.MixedTypes.Power import Numeric.MixedTypes.Field import Numeric.MixedTypes.Elementary import Numeric.MixedTypes.Complex
#!/bin/env python # Automatically translated python version of # OpenSceneGraph example program "osgwidgetprogress" # !!! This program will need manual tuning before it will work. !!! import sys from osgpypp import osgDB from osgpypp import osgWidget # Translated from file 'osgwidgetprogress.cpp' # -*-c++-*- osgWidget - Code by: Jeremy Moles (cubicool) 2007-2008 #include <osgDB/ReadFile> #include <osgWidget/Util> #include <osgWidget/WindowManager> #include <osgWidget/Canvas> MASK_2D = 0xF0000000 class UpdateProgressNode (osg.NodeCallback) : start = float() done = float() UpdateProgressNode(): start (0.0), done (5.0) virtual void operator()(osg.Node* node, osg.NodeVisitor* nv) fs = nv.getFrameStamp() t = fs.getSimulationTime() if start == 0.0 : start = t width = ((t - start) / done) * 512.0 percent = (width / 512.0) * 100.0 if width < 1.0 or width > 512.0 : return window = dynamic_cast<osgWidget.Window*>(node) if not window : return w = window.getByName("pMeter") l = dynamic_cast<osgWidget.Label*>(window.getByName("pLabel")) if not w or not l : return w.setWidth(width) w.setTexCoordRegion(0.0, 0.0, width, 64.0) ss = std.ostringstream() ss, osg.round(percent), "% Done" l.setLabel(ss.str()) def main(argv): viewer = osgViewer.Viewer() wm = osgWidget.WindowManager( viewer, 1280.0, 1024.0, MASK_2D, osgWidget.WindowManager.WM_PICK_DEBUG ) canvas = osgWidget.Canvas("canvas") pOutline = osgWidget.Widget("pOutline", 512.0, 64.0) pMeter = osgWidget.Widget("pMeter", 0.0, 64.0) pLabel = osgWidget.Label("pLabel", "0% Done") pOutline.setImage("osgWidget/progress-outline.png", True) pOutline.setLayer(osgWidget.Widget.LAYER_MIDDLE, 2) pMeter.setImage("osgWidget/progress-meter.png") pMeter.setColor(0.7, 0.1, 0.1, 0.7) pMeter.setLayer(osgWidget.Widget.LAYER_MIDDLE, 1) pLabel.setFont("fonts/VeraMono.ttf") pLabel.setFontSize(20) pLabel.setFontColor(1.0, 1.0, 1.0, 1.0) pLabel.setSize(512.0, 64.0) pLabel.setLayer(osgWidget.Widget.LAYER_MIDDLE, 3) canvas.setOrigin(300.0, 300.0) canvas.addWidget(pMeter, 0.0, 0.0) canvas.addWidget(pOutline, 0.0, 0.0) canvas.addWidget(pLabel, 0.0, 0.0) canvas.getBackground().setColor(0.0, 0.0, 0.0, 0.0) canvas.setUpdateCallback(UpdateProgressNode()) wm.addChild(canvas) return osgWidget.createExample(viewer, wm, osgDB.readNodeFile("cow.osgt")) if __name__ == "__main__": main(sys.argv)
title: Hello World (again) kind: article created_at: 2011-08-10 tags: ['general'] Welcome to my new homepage where I will blog a lot more than I did on my old page, I promise. My blog posts will be about computers, programming, software, computer graphics and to some extent life in general :) My first tip is the software that has actually created this page: <a href="http://nanoc.stoneship.org" rel="external">nanoc</a>. nanoc (yes, it must be written with the first letter lower case) is a static site compiler. It works much like a compiler for a traditional programming - you give it a file of rules and it compiles your source code into a result. But now, why would you want a static site in the 21st century? The answer is efficiency. Since what you see here is only static pages, there is no code executed on the web server. This also gives better security - try to hack a static page ;). It also gives you more control since you have all the code for your web page, your articles are not laying around in some database at some third party web host. nanoc is also very flexible and can be extended in a number of ways. For dynamic content, javascript can be used. I use Disqus for the ability to have comments and it is really nice! So, for a small to medium sized website it can be very suitable. Other static site generators are for example <a href="http://jekyllrb.com" rel="external">Jekyll</a> (written in Ruby as nanoc) and <a href="http://ringce.com/hyde" rel="external">Hyde (written in Python).
package org.basex.gui.text; import static org.basex.gui.GUIConstants.*; import java.awt.*; import org.basex.data.*; public final class SyntaxXML extends Syntax { /** Last quote. */ private int quote; /** Element name flag. */ private boolean name; /** Flag for printing element name. */ private boolean elem; /** Current state of comment. */ private int comment; /** Current state of processing instruction. */ private int pi; @Override public void init(final Color color) { super.init(color); quote = 0; name = false; elem = false; comment = 0; pi = 0; } @Override public Color getColor(final TextIterator iter) { final int ch = iter.curr(); if(comment > 0) return comment(ch); if(pi > 0) return pi(ch); // last token was an opening angle bracket (<) if(name) { if(quote != 0) { if(quote == ch) quote = 0; return VALUE; } if(ch == '"' || ch == '\'') { quote = ch; return VALUE; } if(ch == '>') { name = false; return KEYWORD; } if(ch == '=' || ch == '/') { return KEYWORD; } if(ch == '!') { comment = 1; name = false; return COMMENT; } if(ch == '?') { pi = 1; name = false; return VARIABLE; } if(elem) { if(ch <= ' ') elem = false; return KEYWORD; } return VARIABLE; } // start of a new element, comment or processing instruction if(ch == '<') { name = true; elem = true; return KEYWORD; } return plain; } /** * Processes a comment or doctype declaration. * @param ch current character * @return color */ private Color comment(final int ch) { switch(comment) { case 1: case 2: comment = ch == '-' ? comment + 1 : 6; break; case 3: if(ch == '-') comment = 4; break; case 4: comment = ch == '-' ? comment + 1 : 3; break; case 5: comment = ch == '>' ? 0 : 3; break; case 6: if(ch == '>') comment = 0; break; } return comment > 0 ? COMMENT : KEYWORD; } /** * Processes a processing instruction. * @param ch current character * @return color */ private Color pi(final int ch) { switch(pi) { case 1: if(ch == '?') pi = 2; break; case 2: pi = ch == '>' ? 0 : 1; break; } return pi > 0 ? VARIABLE : KEYWORD; } @Override public byte[] commentOpen() { return DataText.COMM_O; } @Override public byte[] commentEnd() { return DataText.COMM_C; } }
#include "<API key>.h" #include "PathOpsTestCommon.h" #include "SkIntersections.h" #include "SkPathOpsRect.h" #include "SkReduceOrder.h" #include "Test.h" const int <API key> = 9; static void standardTestCases(skiatest::Reporter* reporter) { for (size_t index = <API key>; index < tests_count; ++index) { int iIndex = static_cast<int>(index); const SkDCubic& cubic1 = tests[index][0]; const SkDCubic& cubic2 = tests[index][1]; SkReduceOrder reduce1, reduce2; int order1 = reduce1.reduce(cubic1, SkReduceOrder::kNo_Quadratics, SkReduceOrder::kFill_Style); int order2 = reduce2.reduce(cubic2, SkReduceOrder::kNo_Quadratics, SkReduceOrder::kFill_Style); const bool showSkipped = false; if (order1 < 4) { if (showSkipped) { SkDebugf("%s [%d] cubic1 order=%d\n", __FUNCTION__, iIndex, order1); } continue; } if (order2 < 4) { if (showSkipped) { SkDebugf("%s [%d] cubic2 order=%d\n", __FUNCTION__, iIndex, order2); } continue; } SkIntersections tIntersections; tIntersections.intersect(cubic1, cubic2); if (!tIntersections.used()) { if (showSkipped) { SkDebugf("%s [%d] no intersection\n", __FUNCTION__, iIndex); } continue; } if (tIntersections.isCoincident(0)) { if (showSkipped) { SkDebugf("%s [%d] coincident\n", __FUNCTION__, iIndex); } continue; } for (int pt = 0; pt < tIntersections.used(); ++pt) { double tt1 = tIntersections[0][pt]; SkDPoint xy1 = cubic1.xyAtT(tt1); double tt2 = tIntersections[1][pt]; SkDPoint xy2 = cubic2.xyAtT(tt2); if (!xy1.approximatelyEqual(xy2)) { SkDebugf("%s [%d,%d] x!= t1=%g (%g,%g) t2=%g (%g,%g)\n", __FUNCTION__, (int)index, pt, tt1, xy1.fX, xy1.fY, tt2, xy2.fX, xy2.fY); } REPORTER_ASSERT(reporter, xy1.approximatelyEqual(xy2)); } } } static const SkDCubic testSet[] = { // FIXME: uncommenting these two will cause this to fail // this results in two curves very nearly but not exactly coincident #if 0 {{{67.426548091427676, 37.993772624988935}, {23.483695892376684, 90.476863174921306}, {35.597065061143162, 79.872482633158796}, {75.38634169631932, 18.244890038969412}}}, {{{67.4265481, 37.9937726}, {23.4836959, 90.4768632}, {35.5970651, 79.8724826}, {75.3863417, 18.24489}}}, #endif {{{0, 0}, {0, 1}, {1, 1}, {1, 0}}}, {{{1, 0}, {0, 0}, {0, 1}, {1, 1}}}, {{{0, 1}, {4, 5}, {1, 0}, {5, 3}}}, {{{0, 1}, {3, 5}, {1, 0}, {5, 4}}}, {{{0, 1}, {1, 6}, {1, 0}, {1, 0}}}, {{{0, 1}, {0, 1}, {1, 0}, {6, 1}}}, {{{0, 1}, {3, 4}, {1, 0}, {5, 1}}}, {{{0, 1}, {1, 5}, {1, 0}, {4, 3}}}, {{{0, 1}, {1, 2}, {1, 0}, {6, 1}}}, {{{0, 1}, {1, 6}, {1, 0}, {2, 1}}}, {{{0, 1}, {0, 5}, {1, 0}, {4, 0}}}, {{{0, 1}, {0, 4}, {1, 0}, {5, 0}}}, {{{0, 1}, {3, 4}, {1, 0}, {3, 0}}}, {{{0, 1}, {0, 3}, {1, 0}, {4, 3}}}, {{{0, 0}, {1, 2}, {3, 4}, {4, 4}}}, {{{0, 0}, {1, 2}, {3, 4}, {4, 4}}}, {{{4, 4}, {3, 4}, {1, 2}, {0, 0}}}, {{{0, 1}, {2, 3}, {1, 0}, {1, 0}}}, {{{0, 1}, {0, 1}, {1, 0}, {3, 2}}}, {{{0, 2}, {0, 1}, {1, 0}, {1, 0}}}, {{{0, 1}, {0, 1}, {2, 0}, {1, 0}}}, {{{0, 1}, {0, 2}, {1, 0}, {1, 0}}}, {{{0, 1}, {0, 1}, {1, 0}, {2, 0}}}, {{{0, 1}, {1, 6}, {1, 0}, {2, 0}}}, {{{0, 1}, {0, 2}, {1, 0}, {6, 1}}}, {{{0, 1}, {5, 6}, {1, 0}, {1, 0}}}, {{{0, 1}, {0, 1}, {1, 0}, {6, 5}}}, {{{95.837747722788592, 45.025976907939643}, {16.564570095652982, 0.72959763963222402}, {63.209855865319199, 68.047528419665767}, {57.640240647662544, 59.524565264361243}}}, {{{51.593891741518817, 38.53849970667553}, {62.34752929878772, 74.924924725166022}, {74.810149322641152, 34.17966562983564}, {29.368398119401373, 94.66719277886078}}}, {{{39.765160968417838, 33.060396198677083}, {5.1922921581157908, 66.854301452103215}, {31.619281802149157, 25.269248720849514}, {81.541621071073038, 70.025341524754353}}}, {{{46.078911165743556, 48.259962651999651}, {20.24450549867214, 49.403916182650214}, {0.26325131778756683, 24.46489805563581}, {15.915006546264051, 83.515023059917155}}}, {{{65.454505973241524, 93.881892270353575}, {45.867360264932437, 92.723972719499827}, {2.1464054482739447, 74.636369140183717}, {33.774068594804994, 40.770872887582925}}}, {{{72.963387832494163, 95.659300729473728}, {11.809496633619768, 82.209921247423594}, {13.456139067865974, 57.329313623406605}, {36.060621606214262, 70.867335643091849}}}, {{{32.484981432782945, 75.082940782924624}, {42.467313093350882, 48.131159948246157}, {3.5963115764764657, 43.208665839959245}, {79.442476890721579, 89.709102357602262}}}, {{{18.98573861410177, 93.308887208490106}, {40.405250173250792, 91.039661826118675}, {8.0467721950480584, 42.100282172719147}, {40.883324221187891, 26.030185504830527}}}, {{{7.5374809128872498, 82.441702896003477}, {22.444346930107265, 22.138854312775123}, {66.76091829629658, 50.753805856571446}, {78.193478508942519, 97.7932997968948}}}, {{{97.700573130371311, 53.53260215070685}, {87.72443481149358, 84.575876772671876}, {19.215031396232092, 47.032676472809484}, {11.989686410869325, 10.659507480757082}}}, {{{26.192053931854691, 9.8504326817814416}, {10.174241480498686, 98.476562741434464}, {21.177712558385782, 33.814968789841501}, {75.329030899018534, 55.02231980442177}}}, {{{56.222082700683771, 24.54395039218662}, {95.589995289030483, 81.050822735322086}, {28.180450866082897, 28.837706255185282}, {60.128952916771617, 87.311672180570511}}}, {{{42.449716172390481, 52.379709366885805}, {27.896043159019225, 48.797373636065686}, {92.770268299044233, 89.899302036454571}, {12.102066544863426, 99.43241951960718}}}, {{{45.77532924980639, 45.958701495993274}, {37.458701356062065, 68.393691335056758}, {37.569326692060258, 27.673713456687381}, {60.674866037757539, 62.47349659096146}}}, {{{67.426548091427676, 37.993772624988935}, {23.483695892376684, 90.476863174921306}, {35.597065061143162, 79.872482633158796}, {75.38634169631932, 18.244890038969412}}}, {{{61.336508189019057, 82.693132843213675}, {44.639380902349664, 54.074825790745592}, {16.815615499771951, 20.049704667203923}, {41.866884958868326, 56.735503699973002}}}, {{{18.1312339, 31.6473732}, {95.5711034, 63.5350219}, {92.3283165, 62.0158945}, {18.5656052, 32.1268808}}}, {{{97.402018, 35.7169972}, {33.1127443, 25.8935163}, {1.13970027, 54.9424981}, {56.4860195, 60.529264}}}, }; const size_t testSetCount = SK_ARRAY_COUNT(testSet); static const SkDCubic newTestSet[] = { {{{3, 5}, {1, 6}, {5, 0}, {3, 1}}}, {{{0, 5}, {1, 3}, {5, 3}, {6, 1}}}, {{{0, 1}, {1, 5}, {1, 0}, {1, 0}}}, {{{0, 1}, {0, 1}, {1, 0}, {5, 1}}}, {{{1, 3}, {5, 6}, {5, 3}, {5, 4}}}, {{{3, 5}, {4, 5}, {3, 1}, {6, 5}}}, {{{0, 5}, {0, 5}, {5, 4}, {6, 4}}}, {{{4, 5}, {4, 6}, {5, 0}, {5, 0}}}, {{{0, 4}, {1, 3}, {5, 4}, {4, 2}}}, {{{4, 5}, {2, 4}, {4, 0}, {3, 1}}}, {{{0, 2}, {1, 5}, {3, 2}, {4, 1}}}, {{{2, 3}, {1, 4}, {2, 0}, {5, 1}}}, {{{0, 2}, {2, 3}, {5, 1}, {3, 2}}}, {{{1, 5}, {2, 3}, {2, 0}, {3, 2}}}, {{{2, 6}, {4, 5}, {1, 0}, {6, 1}}}, {{{0, 1}, {1, 6}, {6, 2}, {5, 4}}}, {{{0, 1}, {1, 2}, {6, 5}, {5, 4}}}, {{{5, 6}, {4, 5}, {1, 0}, {2, 1}}}, {{{2.5119999999999996, 1.5710000000000002}, {2.6399999999999983, 1.6599999999999997}, {2.8000000000000007, 1.8000000000000003}, {3, 2}}}, {{{2.4181876227114887, 1.9849772580462195}, {2.8269904869227211, 2.009330650246834}, {3.2004679292461624, 1.9942047174679169}, {3.4986199496818058, 2.0035994597094731}}}, {{{2, 3}, {1, 4}, {1, 0}, {6, 0}}}, {{{0, 1}, {0, 6}, {3, 2}, {4, 1}}}, {{{0, 2}, {1, 5}, {1, 0}, {6, 1}}}, {{{0, 1}, {1, 6}, {2, 0}, {5, 1}}}, {{{0, 1}, {1, 5}, {2, 1}, {4, 0}}}, {{{1, 2}, {0, 4}, {1, 0}, {5, 1}}}, {{{0, 1}, {3, 5}, {2, 1}, {3, 1}}}, {{{1, 2}, {1, 3}, {1, 0}, {5, 3}}}, {{{0, 1}, {2, 5}, {6, 0}, {5, 3}}}, {{{0, 6}, {3, 5}, {1, 0}, {5, 2}}}, {{{0, 1}, {3, 6}, {1, 0}, {5, 2}}}, {{{0, 1}, {2, 5}, {1, 0}, {6, 3}}}, {{{1, 2}, {5, 6}, {1, 0}, {1, 0}}}, {{{0, 1}, {0, 1}, {2, 1}, {6, 5}}}, {{{0, 6}, {1, 2}, {1, 0}, {1, 0}}}, {{{0, 1}, {0, 1}, {6, 0}, {2, 1}}}, {{{0, 2}, {0, 1}, {3, 0}, {1, 0}}}, {{{0, 3}, {0, 1}, {2, 0}, {1, 0}}}, }; const size_t newTestSetCount = SK_ARRAY_COUNT(newTestSet); static void oneOff(skiatest::Reporter* reporter, const SkDCubic& cubic1, const SkDCubic& cubic2) { #if ONE_OFF_DEBUG SkDebugf("computed quadratics given\n"); SkDebugf(" {{{%1.9g,%1.9g}, {%1.9g,%1.9g}, {%1.9g,%1.9g}, {%1.9g,%1.9g}}},\n", cubic1[0].fX, cubic1[0].fY, cubic1[1].fX, cubic1[1].fY, cubic1[2].fX, cubic1[2].fY, cubic1[3].fX, cubic1[3].fY); SkDebugf(" {{{%1.9g,%1.9g}, {%1.9g,%1.9g}, {%1.9g,%1.9g}, {%1.9g,%1.9g}}},\n", cubic2[0].fX, cubic2[0].fY, cubic2[1].fX, cubic2[1].fY, cubic2[2].fX, cubic2[2].fY, cubic2[3].fX, cubic2[3].fY); #endif SkTDArray<SkDQuad> quads1; CubicToQuads(cubic1, cubic1.calcPrecision(), quads1); #if ONE_OFF_DEBUG SkDebugf("computed quadratics set 1\n"); for (int index = 0; index < quads1.count(); ++index) { const SkDQuad& q = quads1[index]; SkDebugf(" {{{%1.9g,%1.9g}, {%1.9g,%1.9g}, {%1.9g,%1.9g}}},\n", q[0].fX, q[0].fY, q[1].fX, q[1].fY, q[2].fX, q[2].fY); } #endif SkTDArray<SkDQuad> quads2; CubicToQuads(cubic2, cubic2.calcPrecision(), quads2); #if ONE_OFF_DEBUG SkDebugf("computed quadratics set 2\n"); for (int index = 0; index < quads2.count(); ++index) { const SkDQuad& q = quads2[index]; SkDebugf(" {{{%1.9g,%1.9g}, {%1.9g,%1.9g}, {%1.9g,%1.9g}}},\n", q[0].fX, q[0].fY, q[1].fX, q[1].fY, q[2].fX, q[2].fY); } #endif SkIntersections intersections; intersections.intersect(cubic1, cubic2); double tt1, tt2; SkDPoint xy1, xy2; for (int pt3 = 0; pt3 < intersections.used(); ++pt3) { tt1 = intersections[0][pt3]; xy1 = cubic1.xyAtT(tt1); tt2 = intersections[1][pt3]; xy2 = cubic2.xyAtT(tt2); #if ONE_OFF_DEBUG SkDebugf("%s t1=%1.9g (%1.9g, %1.9g) (%1.9g, %1.9g) (%1.9g, %1.9g) t2=%1.9g\n", __FUNCTION__, tt1, xy1.fX, xy1.fY, intersections.pt(pt3).fX, intersections.pt(pt3).fY, xy2.fX, xy2.fY, tt2); #endif REPORTER_ASSERT(reporter, xy1.approximatelyEqual(xy2)); } } static void oneOff(skiatest::Reporter* reporter, int outer, int inner) { const SkDCubic& cubic1 = testSet[outer]; const SkDCubic& cubic2 = testSet[inner]; oneOff(reporter, cubic1, cubic2); } static void newOneOff(skiatest::Reporter* reporter, int outer, int inner) { const SkDCubic& cubic1 = newTestSet[outer]; const SkDCubic& cubic2 = newTestSet[inner]; oneOff(reporter, cubic1, cubic2); } static void oneOffTest(skiatest::Reporter* reporter) { oneOff(reporter, 14, 16); newOneOff(reporter, 0, 1); } static void oneOffTests(skiatest::Reporter* reporter) { for (size_t outer = 0; outer < testSetCount - 1; ++outer) { for (size_t inner = outer + 1; inner < testSetCount; ++inner) { oneOff(reporter, outer, inner); } } for (size_t outer = 0; outer < newTestSetCount - 1; ++outer) { for (size_t inner = outer + 1; inner < newTestSetCount; ++inner) { oneOff(reporter, outer, inner); } } } #define DEBUG_CRASH 0 static void <API key>(skiatest::Reporter* reporter) { srand(0); const int tests = 10000000; #if !defined(SK_BUILD_FOR_WIN) && !defined(<API key>) unsigned seed = 0; #endif for (int test = 0; test < tests; ++test) { SkDCubic cubic1, cubic2; for (int i = 0; i < 4; ++i) { cubic1[i].fX = static_cast<double>(SK_RAND(seed)) / RAND_MAX * 100; cubic1[i].fY = static_cast<double>(SK_RAND(seed)) / RAND_MAX * 100; cubic2[i].fX = static_cast<double>(SK_RAND(seed)) / RAND_MAX * 100; cubic2[i].fY = static_cast<double>(SK_RAND(seed)) / RAND_MAX * 100; } #if DEBUG_CRASH char str[1024]; snprintf(str, sizeof(str), "{{{%1.9g, %1.9g}, {%1.9g, %1.9g}, {%1.9g, %1.9g}, {%1.9g, %1.9g}}},\n" "{{{%1.9g, %1.9g}, {%1.9g, %1.9g}, {%1.9g, %1.9g}, {%1.9g, %1.9g}}},\n", cubic1[0].fX, cubic1[0].fY, cubic1[1].fX, cubic1[1].fY, cubic1[2].fX, cubic1[2].fY, cubic1[3].fX, cubic1[3].fY, cubic2[0].fX, cubic2[0].fY, cubic2[1].fX, cubic2[1].fY, cubic2[2].fX, cubic2[2].fY, cubic2[3].fX, cubic2[3].fY); #endif SkDRect rect1, rect2; rect1.setBounds(cubic1); rect2.setBounds(cubic2); bool boundsIntersect = rect1.fLeft <= rect2.fRight && rect2.fLeft <= rect2.fRight && rect1.fTop <= rect2.fBottom && rect2.fTop <= rect1.fBottom; if (test == -1) { SkDebugf("ready...\n"); } SkIntersections intersections2; int newIntersects = intersections2.intersect(cubic1, cubic2); if (!boundsIntersect && newIntersects) { #if DEBUG_CRASH SkDebugf("%s %d unexpected intersection boundsIntersect=%d " " newIntersects=%d\n%s %s\n", __FUNCTION__, test, boundsIntersect, newIntersects, __FUNCTION__, str); #endif REPORTER_ASSERT(reporter, 0); } for (int pt = 0; pt < intersections2.used(); ++pt) { double tt1 = intersections2[0][pt]; SkDPoint xy1 = cubic1.xyAtT(tt1); double tt2 = intersections2[1][pt]; SkDPoint xy2 = cubic2.xyAtT(tt2); REPORTER_ASSERT(reporter, xy1.approximatelyEqual(xy2)); } } } static void intersectionFinder(int index0, int index1, double t1Seed, double t2Seed, double t1Step, double t2Step) { const SkDCubic& cubic1 = newTestSet[index0]; const SkDCubic& cubic2 = newTestSet[index1]; SkDPoint t1[3], t2[3]; bool toggle = true; do { t1[0] = cubic1.xyAtT(t1Seed - t1Step); t1[1] = cubic1.xyAtT(t1Seed); t1[2] = cubic1.xyAtT(t1Seed + t1Step); t2[0] = cubic2.xyAtT(t2Seed - t2Step); t2[1] = cubic2.xyAtT(t2Seed); t2[2] = cubic2.xyAtT(t2Seed + t2Step); double dist[3][3]; dist[1][1] = t1[1].distance(t2[1]); int best_i = 1, best_j = 1; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (i == 1 && j == 1) { continue; } dist[i][j] = t1[i].distance(t2[j]); if (dist[best_i][best_j] > dist[i][j]) { best_i = i; best_j = j; } } } if (best_i == 0) { t1Seed -= t1Step; } else if (best_i == 2) { t1Seed += t1Step; } if (best_j == 0) { t2Seed -= t2Step; } else if (best_j == 2) { t2Seed += t2Step; } if (best_i == 1 && best_j == 1) { if ((toggle ^= true)) { t1Step /= 2; } else { t2Step /= 2; } } } while (!t1[1].approximatelyEqual(t2[1])); t1Step = t2Step = 0.1; double t10 = t1Seed - t1Step * 2; double t12 = t1Seed + t1Step * 2; double t20 = t2Seed - t2Step * 2; double t22 = t2Seed + t2Step * 2; SkDPoint test; while (!approximately_zero(t1Step)) { test = cubic1.xyAtT(t10); t10 += t1[1].approximatelyEqual(test) ? -t1Step : t1Step; t1Step /= 2; } t1Step = 0.1; while (!approximately_zero(t1Step)) { test = cubic1.xyAtT(t12); t12 -= t1[1].approximatelyEqual(test) ? -t1Step : t1Step; t1Step /= 2; } while (!approximately_zero(t2Step)) { test = cubic2.xyAtT(t20); t20 += t2[1].approximatelyEqual(test) ? -t2Step : t2Step; t2Step /= 2; } t2Step = 0.1; while (!approximately_zero(t2Step)) { test = cubic2.xyAtT(t22); t22 -= t2[1].approximatelyEqual(test) ? -t2Step : t2Step; t2Step /= 2; } #if ONE_OFF_DEBUG SkDebugf("%s t1=(%1.9g<%1.9g<%1.9g) t2=(%1.9g<%1.9g<%1.9g)\n", __FUNCTION__, t10, t1Seed, t12, t20, t2Seed, t22); SkDPoint p10 = cubic1.xyAtT(t10); SkDPoint p1Seed = cubic1.xyAtT(t1Seed); SkDPoint p12 = cubic1.xyAtT(t12); SkDebugf("%s p1=(%1.9g,%1.9g)<(%1.9g,%1.9g)<(%1.9g,%1.9g)\n", __FUNCTION__, p10.fX, p10.fY, p1Seed.fX, p1Seed.fY, p12.fX, p12.fY); SkDPoint p20 = cubic2.xyAtT(t20); SkDPoint p2Seed = cubic2.xyAtT(t2Seed); SkDPoint p22 = cubic2.xyAtT(t22); SkDebugf("%s p2=(%1.9g,%1.9g)<(%1.9g,%1.9g)<(%1.9g,%1.9g)\n", __FUNCTION__, p20.fX, p20.fY, p2Seed.fX, p2Seed.fY, p22.fX, p22.fY); #endif } static void <API key>() { // double t1Seed = 0.87; // double t2Seed = 0.87; double t1Step = 0.000001; double t2Step = 0.000001; intersectionFinder(0, 1, 0.855895664, 0.864850875, t1Step, t2Step); intersectionFinder(0, 1, 0.865207906, 0.865207887, t1Step, t2Step); intersectionFinder(0, 1, 0.865213351, 0.865208087, t1Step, t2Step); } static void <API key>(skiatest::Reporter* reporter) { const SkDCubic selfSet[] = { {{{0, 2}, {2, 3}, {5, 1}, {3, 2}}}, {{{0, 2}, {3, 5}, {5, 0}, {4, 2}}}, {{{3.34, 8.98}, {1.95, 10.27}, {3.76, 7.65}, {4.96, 10.64}}}, {{{3.13, 2.74}, {1.08, 4.62}, {3.71, 0.94}, {2.01, 3.81}}}, {{{6.71, 3.14}, {7.99, 2.75}, {8.27, 1.96}, {6.35, 3.57}}}, {{{12.81, 7.27}, {7.22, 6.98}, {12.49, 8.97}, {11.42, 6.18}}}, }; size_t selfSetCount = SK_ARRAY_COUNT(selfSet); size_t firstFail = 1; for (size_t index = firstFail; index < selfSetCount; ++index) { const SkDCubic& cubic = selfSet[index]; #if ONE_OFF_DEBUG int idx2; double max[3]; int ts = cubic.findMaxCurvature(max); for (idx2 = 0; idx2 < ts; ++idx2) { SkDebugf("%s max[%d]=%1.9g (%1.9g, %1.9g)\n", __FUNCTION__, idx2, max[idx2], cubic.xyAtT(max[idx2]).fX, cubic.xyAtT(max[idx2]).fY); } SkTDArray<double> ts1; SkTDArray<SkDQuad> quads1; cubic.toQuadraticTs(cubic.calcPrecision(), &ts1); for (idx2 = 0; idx2 < ts1.count(); ++idx2) { SkDebugf("%s t[%d]=%1.9g\n", __FUNCTION__, idx2, ts1[idx2]); } CubicToQuads(cubic, cubic.calcPrecision(), quads1); for (idx2 = 0; idx2 < quads1.count(); ++idx2) { const SkDQuad& q = quads1[idx2]; SkDebugf(" {{{%1.9g,%1.9g}, {%1.9g,%1.9g}, {%1.9g,%1.9g}}},\n", q[0].fX, q[0].fY, q[1].fX, q[1].fY, q[2].fX, q[2].fY); } SkDebugf("\n"); #endif SkIntersections i; int result = i.intersect(cubic); REPORTER_ASSERT(reporter, result == 1); REPORTER_ASSERT(reporter, i.used() == 1); REPORTER_ASSERT(reporter, !approximately_equal(i[0][0], i[1][0])); SkDPoint pt1 = cubic.xyAtT(i[0][0]); SkDPoint pt2 = cubic.xyAtT(i[1][0]); REPORTER_ASSERT(reporter, pt1.approximatelyEqual(pt2)); } } static void <API key>(skiatest::Reporter* reporter) { oneOffTest(reporter); oneOffTests(reporter); <API key>(reporter); standardTestCases(reporter); if (false) <API key>(); if (false) <API key>(reporter); } #include "TestClassDef.h" <API key>(<API key>)
#include <errno.h> #include <inttypes.h> #include <pthread.h> #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> #include <sys/time.h> #include <ck_pr.h> #include <ck_barrier.h> #include "../../common.h" #ifndef ITERATE #define ITERATE 5000000 #endif #ifndef ENTRIES #define ENTRIES 512 #endif static struct affinity a; static int nthr; static int counters[ENTRIES]; static <API key> barrier = <API key>; static int barrier_wait; static void * thread(void *null CK_CC_UNUSED) { <API key> state = <API key>; int j, counter; int i = 0; aff_iterate(&a); ck_pr_inc_int(&barrier_wait); while (ck_pr_load_int(&barrier_wait) != nthr) ck_pr_stall(); for (j = 0; j < ITERATE; j++) { i = j++ & (ENTRIES - 1); ck_pr_inc_int(&counters[i]); <API key>(&barrier, &state, nthr); counter = ck_pr_load_int(&counters[i]); if (counter != nthr * (j / ENTRIES + 1)) { ck_error("FAILED [%d:%d]: %d != %d\n", i, j - 1, counter, nthr); } } return (NULL); } int main(int argc, char *argv[]) { pthread_t *threads; int i; if (argc < 3) { ck_error("Usage: correct <number of threads> <affinity delta>\n"); } nthr = atoi(argv[1]); if (nthr <= 0) { ck_error("ERROR: Number of threads must be greater than 0\n"); } threads = malloc(sizeof(pthread_t) * nthr); if (threads == NULL) { ck_error("ERROR: Could not allocate thread structures\n"); } a.delta = atoi(argv[2]); fprintf(stderr, "Creating threads (barrier)..."); for (i = 0; i < nthr; i++) { if (pthread_create(&threads[i], NULL, thread, NULL)) { ck_error("ERROR: Could not create thread %d\n", i); } } fprintf(stderr, "done\n"); fprintf(stderr, "Waiting for threads to finish correctness regression..."); for (i = 0; i < nthr; i++) pthread_join(threads[i], NULL); fprintf(stderr, "done (passed)\n"); return (0); }
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use app\models\MOffice; use app\models\MStaff; $this->title = $model->isNewRecord ? '' : ''.''; $this->params['breadcrumbs'][] = ['label' => '', 'url' => ['officelist']]; $this->params['breadcrumbs'][] = $model->isNewRecord ? '' : ''; ?> <div class="muser-update"> <div class="muser-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'title')->textInput(['maxlength' => 64]) ?> <?= $form->field($model, 'address')->textInput(['maxlength' => 128]) ?> <?= $form->field($model, 'manager')->textInput(['maxlength' => 16]) ?> <?= $form->field($model, 'mobile')->textInput(['maxlength' => 24]) ?> <?= $form->field($model, 'lon')->textInput(['maxlength' => 24]) ?> <?= $form->field($model, 'lat')->textInput(['maxlength' => 24]) ?> <?= $form->field($model, 'visable')->dropDownList(['1'=>'', '0'=>'']) ?> <?= $form->field($model, 'pswd')->textInput(['maxlength' => 24]) ?> <?php if ($model->isNewRecord): ?> <?= $form->field($model, 'need_scene_id')->dropDownList(['0'=>'', '1'=>''])->label('') ?> <?php endif; ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? '' : '', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div> </div> <?php /* <?= $form->field($model, 'office_id')->textInput(['maxlength' => 10]) ?> <?= $form->field($model, 'office_id')->dropDownList(MOffice::<API key>(Yii::$app->user->identity->gh_id, false, false)) ?> <?= $form->field($model, 'status')->dropDownList(MOrder::<API key>()) ?> <h1><?= Html::encode($this->title) ?></h1> */
-- Variable arguments local function p(...) print(...) end local function values(...) return ... end local function add(...) local a, b = ... return a+b end p(values(1, 2)) p("sum=", add(values(1, 2)))
#pragma once // ensure the MCU series is correct #ifndef STM32PLUS_F0 #error This class can only be used with the STM32F0 series #endif /* * Forward declare the IRQ handler name. There is a single IRQ handler for ADC 1 on the F0 */ extern "C" void <API key>(); namespace stm32plus { /** * Feature class to allow allow handling of ADC interrupts. Declare this feature * with your AdcN<> declaration, register an event handler with the AdvEventSource * base class and then use enableInterrupts() to start. */ class AdcInterruptFeature : public AdcEventSource, public AdcFeatureBase { private: typedef void (*FPTR)(); // this trick will force the linker to include the ISR static FPTR _forceLinkage; protected: uint16_t _interruptMask; public: enum { END_OF_CONVERSION = 0x01, OVERFLOW = 0x02, END_OF_SEQUENCE = 0x04, ANALOG_WATCHDOG = 0x08, END_OF_SAMPLING = 0x10, ADC_READY = 0x20 }; static AdcEventSource *_adcInstance; public: AdcInterruptFeature(Adc& adc); ~AdcInterruptFeature(); void initialise() {} void enableInterrupts(uint16_t interruptMask); void disableInterrupts(uint16_t interruptMask); }; /** * Typedefs for the sole ADC for compatibility */ typedef AdcInterruptFeature <API key>; /** * Constructor, initialises the interrupt mask for this class to zero. */ inline AdcInterruptFeature::AdcInterruptFeature(Adc& adc) : AdcFeatureBase(adc) { _interruptMask=0; _adcInstance=this; } /** * Destructor, if any interrupts are configured for this class then * disable them so that ISR calls don't disappear off into nothing */ inline AdcInterruptFeature::~AdcInterruptFeature() { if(_interruptMask!=0) disableInterrupts(_interruptMask); } /** * Enable the interrupts specified in the mask * @param interruptMask The bitmask of interrupts, e.g. END_OF_CONVERSION | OVERFLOW */ inline void AdcInterruptFeature::enableInterrupts(uint16_t interruptMask) { _interruptMask|=interruptMask; _forceLinkage=&<API key>; Nvic::configureIrq(ADC1_COMP_IRQn); if((interruptMask & END_OF_CONVERSION)!=0) ADC_ITConfig(_adc,ADC_IT_EOC,ENABLE); if((interruptMask & END_OF_SEQUENCE)!=0) ADC_ITConfig(_adc,ADC_IT_EOSEQ,ENABLE); if((interruptMask & END_OF_SAMPLING)!=0) ADC_ITConfig(_adc,ADC_IT_EOSMP,ENABLE); if((interruptMask & ANALOG_WATCHDOG)!=0) ADC_ITConfig(_adc,ADC_IT_AWD,ENABLE); if((interruptMask & OVERFLOW)!=0) ADC_ITConfig(_adc,ADC_IT_OVR,ENABLE); if((interruptMask & ADC_READY)!=0) ADC_ITConfig(_adc,ADC_IT_ADRDY,ENABLE); } /** * Disable the interrupts specified in the mask * @param interruptMask The bitmask of interrupts, e.g. END_OF_CONVERSION | OVERFLOW */ inline void AdcInterruptFeature::disableInterrupts(uint16_t interruptMask) { _interruptMask&=~interruptMask; if((interruptMask & END_OF_CONVERSION)!=0) ADC_ITConfig(_adc,ADC_IT_EOC,DISABLE); if((interruptMask & END_OF_SEQUENCE)!=0) ADC_ITConfig(_adc,ADC_IT_EOSEQ,DISABLE); if((interruptMask & END_OF_SAMPLING)!=0) ADC_ITConfig(_adc,ADC_IT_EOSMP,DISABLE); if((interruptMask & ANALOG_WATCHDOG)!=0) ADC_ITConfig(_adc,ADC_IT_AWD,DISABLE); if((interruptMask & OVERFLOW)!=0) ADC_ITConfig(_adc,ADC_IT_OVR,DISABLE); if((interruptMask & ADC_READY)!=0) ADC_ITConfig(_adc,ADC_IT_ADRDY,DISABLE); } }
<footer class="footer"> <div class="content content--footer"> <small class="small">&copy; {{ site.time | date: '%Y' }} — {{ site.title }}</small> </div> </footer>
require_relative 'group_presenter' module Carto module Api class UserPresenter include AccountTypeHelper def initialize(user, fetch_groups: false, current_viewer: nil, fetch_db_size: true, fetch_basemaps: false, fetch_profile: true) @user = user @fetch_groups = fetch_groups @current_viewer = current_viewer @fetch_db_size = fetch_db_size @fetch_basemaps = fetch_basemaps @fetch_profile = fetch_profile end def to_poro return {} if @user.nil? return to_public_poro unless current_viewer && @user.viewable_by?(current_viewer) poro = { id: @user.id, name: @user.name, last_name: @user.last_name, username: @user.username, email: @user.email, avatar_url: @user.avatar_url, website: @user.website, description: @user.description, location: @user.location, twitter_username: @user.twitter_username, disqus_shortname: @user.disqus_shortname, available_for_hire: @user.available_for_hire, base_url: @user.public_url, <API key>: @user.<API key>, quota_in_bytes: @user.quota_in_bytes, table_count: @user.table_count, viewer: @user.viewer?, role_display: @user.role_display, org_admin: @user.organization_admin?, <API key>: @user.<API key>, <API key>: @user.<API key>, org_user: @user.organization_id.present?, remove_logo: @user.remove_logo?, } if fetch_groups poro[:groups] = @user.groups ? @user.groups.map { |g| Carto::Api::GroupPresenter.new(g).to_poro } : [] end poro[:basemaps] = @user.basemaps if fetch_basemaps poro[:db_size_in_bytes] = @user.db_size_in_bytes if fetch_db_size if fetch_profile poro[:industry] = @user.industry poro[:company_employees] = @user.company_employees poro[:use_case] = @user.use_case poro[:company] = @user.company poro[:phone] = @user.phone poro[:job_role] = @user.job_role end poro end def to_eumapi_poro presentation = to_poro presentation.delete(:id) presentation[:<API key>] = @user.<API key> presentation[:api_key] = @user.api_key presentation end def to_public_poro return {} if @user.nil? poro = { id: @user.id, username: @user.username, name: @user.name, last_name: @user.last_name, avatar_url: @user.avatar_url, base_url: @user.public_url, <API key>: @user.<API key>, disqus_shortname: @user.disqus_shortname, viewer: @user.viewer?, org_admin: @user.organization_admin?, org_user: @user.organization_id.present?, remove_logo: @user.remove_logo? } if fetch_groups poro[:groups] = @user.groups ? @user.groups.map { |g| Carto::Api::GroupPresenter.new(g).to_poro } : [] end poro end def data(options = {}) return {} if @user.nil? db_size_in_bytes = @user.db_size_in_bytes data = { id: @user.id, email: @user.email, name: @user.name, last_name: @user.last_name, created_at: @user.created_at, username: @user.username, state: @user.state, account_type: @user.account_type, <API key>: plan_name(@user.account_type), table_quota: @user.table_quota, public_map_quota: @user.public_map_quota, <API key>: @user.<API key>, private_map_quota: @user.private_map_quota, <API key>: @user.<API key>, table_count: @user.table_count, viewer: @user.viewer?, role_display: @user.role_display, industry: @user.industry, company_employees: @user.company_employees, use_case: @user.use_case, company: @user.company, phone: @user.phone, job_role: @user.job_role, org_admin: @user.organization_admin?, <API key>: @user.<API key>, <API key>: @user.<API key>, <API key>: @user.<API key>, <API key>: @user.<API key>, <API key>: @user.<API key>, <API key>: @user.<API key>, <API key>: @user.<API key>, visualization_count: @user.visualization_count, failed_import_count: failed_import_count, <API key>: <API key>, import_count: import_count, <API key>: <API key>, quota_in_bytes: @user.quota_in_bytes, # TODO: To be deprecated in favor of memory -> quota_in_bytes db_size_in_bytes: db_size_in_bytes, # TODO: To be deprecated in favor of memory -> db_size_in_bytes <API key>: db_size_in_bytes.present? ? (db_size_in_bytes / (1024.0 * 1024.0)).round(2) : nil, <API key>: @user.<API key>, <API key>: @user.remaining_quota(db_size_in_bytes).to_f, storage: { # Total quota, including premium subscriptions addons: quota_in_bytes: @user.quota_in_bytes, # Total DB storage used, including premium and public synchronized datasets: db_size_in_bytes: db_size_in_bytes, # DB storage used by public subscriptions: <API key>: @user.<API key>, # DB storage used by premium subscriptions: <API key>: @user.<API key>, # Estimated premium datasets size: <API key>: @user.<API key> }, map_views: @user.organization_user? ? @user.organization.map_views_count : @user.map_views_count, map_views_quota: @user.organization_user? ? @user.organization.map_views_quota : @user.map_views_quota, unverified: @user.unverified?, geocoding: { quota: @user.organization_user? ? @user.organization.geocoding_quota : @user.geocoding_quota, block_price: @user.organization_user? ? @user.organization.<API key> : @user.<API key>, monthly_use: @user.organization_user? ? @user.organization.get_geocoding_calls : @user.get_geocoding_calls, hard_limit: @user.<API key>? }, here_isolines: { quota: @user.organization_user? ? @user.organization.here_isolines_quota : @user.here_isolines_quota, block_price: @user.organization_user? ? @user.organization.<API key> : @user.<API key>, monthly_use: @user.organization_user? ? @user.organization.<API key> : @user.<API key>, hard_limit: @user.<API key>? }, mapzen_routing: { quota: @user.organization_user? ? @user.organization.<API key> : @user.<API key>, block_price: @user.organization_user? ? @user.organization.<API key> : @user.<API key>, monthly_use: @user.organization_user? ? @user.organization.<API key> : @user.<API key>, hard_limit: @user.<API key>? }, geocoder_provider: @user.geocoder_provider, isolines_provider: @user.isolines_provider, routing_provider: @user.routing_provider, twitter: { enabled: @user.<TwitterConsumerkey>, quota: @user.organization_user? ? @user.organization.<TwitterConsumerkey> : @user.<TwitterConsumerkey>, block_price: @user.organization_user? ? @user.organization.<TwitterConsumerkey> : @user.<TwitterConsumerkey>, block_size: @user.organization_user? ? @user.organization.<TwitterConsumerkey> : @user.<TwitterConsumerkey>, monthly_use: @user.organization_user? ? @user.organization.<TwitterConsumerkey> : @user.<TwitterConsumerkey>, hard_limit: @user.hard_<TwitterConsumerkey>, customized_config: CartoDB::Datasources::DatasourcesFactory.customized_config?(CartoDB::Datasources::Search::<TwitterConsumerkey>, @user) }, salesforce: { enabled: @user.organization_user? ? @user.organization.<API key> : @user.<API key> }, mailchimp: { enabled: Carto::AccountType.new.mailchimp?(@user) }, billing_period: @user.last_billing_cycle, next_billing_period: @user.next_billing_cycle, api_key: @user.api_key, layers: @user.layers.map { |layer| Carto::Api::LayerPresenter.new(layer).to_poro }, trial_ends_at: @user.trial_ends_at, upgraded_at: @user.upgraded_at, show_trial_reminder: @user.show_trial_reminder?, <API key>: (@user.account_type.downcase != 'free' && @user.upgraded_at && @user.upgraded_at + 15.days > Date.today ? true : false), actions: { private_tables: @user.<API key>, private_maps: @user.<API key>?, remove_logo: @user.remove_logo?, sync_tables: @user.sync_tables_enabled, <API key>: @user.<API key>?, google_maps_enabled: @user.google_maps_enabled?, engine_enabled: @user.engine_enabled?, builder_enabled: @user.builder_enabled?, mobile_sdk_enabled: @user.mobile_sdk_enabled? }, limits: { concurrent_syncs: CartoDB::PlatformLimits::Importer::<API key>::MAX_SYNCS_PER_USER, concurrent_imports: @user.<API key>, import_file_size: @user.<API key>, import_table_rows: @user.<API key>, max_layers: @user.max_layers }, notification: @user.notification, email_notifications: @user.<API key>, avatar_url: @user.avatar, feature_flags: @user.feature_flags_names, base_url: @user.public_url, <API key>: @user.<API key>?, description: @user.description, website: @user.website, twitter_username: @user.twitter_username, disqus_shortname: @user.disqus_shortname, available_for_hire: @user.available_for_hire, location: @user.location, mfa_configured: @user.multifactor_<API key>?, is_enterprise: @user.enterprise?, do_enabled: @user.do_enabled?, do_bq_project: @user&.gcloud_settings&.[](:bq_project), do_bq_dataset: @user&.gcloud_settings&.[](:bq_dataset), } if @user.<API key>? && (!@user.organization.present? || @user.organization_owner?) data[:<API key>] = @user.<API key> end if @user.organization.present? data[:organization] = Carto::Api::<API key>.new(@user.organization).to_poro data[:organization][:<API key>] = @user.organization.unassigned_quota + @user.quota_in_bytes end if !@user.groups.nil? data[:groups] = @user.groups.map { |g| Carto::Api::GroupPresenter.new(g).to_poro } end if @user.mobile_sdk_enabled? data[:mobile_apps] = { mobile_xamarin: @user.mobile_xamarin, <API key>: @user.<API key>, mobile_offline_maps: @user.mobile_offline_maps, <API key>: @user.<API key>, <API key>: @user.<API key>, <API key>: @user.<API key> } end if options[:extended] # TODO: This fields are pending migration data.merge({ :real_table_count => @user.real_tables.size, :last_active_time => @user.<API key> }) else data end end private attr_reader :current_viewer, :current_user, :fetch_groups, :fetch_db_size, :fetch_basemaps, :fetch_profile def failed_import_count Carto::DataImport.where(user_id: @user.id, state: 'failure').count end def <API key> Carto::DataImport.where(user_id: @user.id, state: 'complete').count end def import_count DataImport.where(user_id: @user.id).count end def <API key> row_data = Carto::<API key>.new .with_user_id(@user.id) .with_order(:created_at, :desc) .build_paged(1, 1) .pluck(:created_at) row_data.nil? ? nil : row_data[0] end end end end
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\GuruSearch */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="guru-search"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <?= $form->field($model, 'id') ?> <?= $form->field($model, 'id_guru') ?> <?= $form->field($model, 'nama_guru') ?> <div class="form-group"> <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?> <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div>
<?php namespace RcmUser\Controller; class <API key> extends <API key> { /** * indexAction - list * * @return array */ public function indexAction() { // ACCESS CHECK if (!$this->isAllowed( <API key>::RESOURCE_ID_USER, 'read' ) ) { return $this-><API key>(); } $viewArr = []; return $this->buildView($viewArr); } }
layout: organization category: local title: Mountain Bible Church impact_area: Human Rights keywords: location_services: location_offices: website: http://fundly.com/<API key> description: mission: | We were once again tragically reminded of the frailty of our existence as Hurricane Sandy shattered lives and devastated property across the Northeast. No area was hit worse than our hometown of Staten Island. Normally resilient people were brought to their knees, left shocked, without shelter and life sustaining necessities, but also, seemingly without hope. Needs were at critical, life threatening levels and deteriorating rapidly. Without any hesitation, people stopped what they were doing and sprung into action, digging in and doing whatever it took, not the least of which was writing checks and tapping other valuable resources. Without a doubt, your willingness to contribute at such a dire time has already saved lives and will forever be the difference in restoring normalcy for so many families. From the depths of despair, humility is stirred. cash_grants: grants: service_opp: services: learn: cont_relationship: salutation: first_name: last_name: <API key>: city: Staten Island state: NY address: | 163 Ridgecrest Avenue Staten Island NY 10312 lat: 40.538055 lng: -74.157806 phone: 917-302-0306 ext: fax: email: preferred_contact: <API key>:
#include <string.h> #include <openssl/aead.h> #include <openssl/aes.h> #include <openssl/cipher.h> #include <openssl/cpu.h> #include <openssl/err.h> #include <openssl/mem.h> #include <openssl/modes.h> #include <openssl/obj.h> #include <openssl/rand.h> #include <openssl/sha.h> #include "internal.h" #include "../internal.h" #include "../modes/internal.h" #if defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) #include "../arm_arch.h" #endif typedef struct { union { double align; AES_KEY ks; } ks; block128_f block; union { cbc128_f cbc; ctr128_f ctr; } stream; } EVP_AES_KEY; typedef struct { union { double align; AES_KEY ks; } ks; /* AES key schedule to use */ int key_set; /* Set if key initialised */ int iv_set; /* Set if an iv is set */ GCM128_CONTEXT gcm; uint8_t *iv; /* Temporary IV store */ int ivlen; /* IV length */ int taglen; int iv_gen; /* It is OK to generate IVs */ ctr128_f ctr; } EVP_AES_GCM_CTX; #if !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_X86_64) || defined(OPENSSL_X86)) #define VPAES extern unsigned int OPENSSL_ia32cap_P[]; static char vpaes_capable(void) { return (OPENSSL_ia32cap_P[1] & (1 << (41 - 32))) != 0; } #if defined(OPENSSL_X86_64) #define BSAES static char bsaes_capable(void) { return vpaes_capable(); } #endif #elif !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) #include "../arm_arch.h" #if defined(OPENSSL_ARM) && __ARM_ARCH__ >= 7 #define BSAES static char bsaes_capable(void) { return <API key>(); } #endif #define HWAES static char hwaes_capable(void) { return (OPENSSL_armcap_P & ARMV8_AES) != 0; } int <API key>(const uint8_t *user_key, const int bits, AES_KEY *key); int <API key>(const uint8_t *user_key, const int bits, AES_KEY *key); void aes_v8_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key); void aes_v8_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key); void aes_v8_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t *ivec, const int enc); void <API key>(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, const uint8_t ivec[16]); #endif /* OPENSSL_ARM */ #if defined(BSAES) /* On platforms where BSAES gets defined (just above), then these functions are * provided by asm. */ void bsaes_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t ivec[16], int enc); void <API key>(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, const uint8_t ivec[16]); #else static char bsaes_capable(void) { return 0; } /* On other platforms, bsaes_capable() will always return false and so the * following will never be called. */ void bsaes_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t ivec[16], int enc) { abort(); } void <API key>(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, const uint8_t ivec[16]) { abort(); } #endif #if defined(VPAES) /* On platforms where VPAES gets defined (just above), then these functions are * provided by asm. */ int <API key>(const uint8_t *userKey, int bits, AES_KEY *key); int <API key>(const uint8_t *userKey, int bits, AES_KEY *key); void vpaes_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key); void vpaes_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key); void vpaes_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t *ivec, int enc); #else static char vpaes_capable(void) { return 0; } /* On other platforms, vpaes_capable() will always return false and so the * following will never be called. */ int <API key>(const uint8_t *userKey, int bits, AES_KEY *key) { abort(); } int <API key>(const uint8_t *userKey, int bits, AES_KEY *key) { abort(); } void vpaes_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { abort(); } void vpaes_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { abort(); } void vpaes_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t *ivec, int enc) { abort(); } #endif #if !defined(HWAES) /* If HWAES isn't defined then we provide dummy functions for each of the hwaes * functions. */ int hwaes_capable(void) { return 0; } int <API key>(const uint8_t *user_key, int bits, AES_KEY *key) { abort(); } int <API key>(const uint8_t *user_key, int bits, AES_KEY *key) { abort(); } void aes_v8_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { abort(); } void aes_v8_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { abort(); } void aes_v8_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t *ivec, int enc) { abort(); } void <API key>(const uint8_t *in, uint8_t *out, size_t len, const AES_KEY *key, const uint8_t ivec[16]) { abort(); } #endif #if !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_X86_64) || defined(OPENSSL_X86)) int <API key>(const uint8_t *userKey, int bits, AES_KEY *key); int <API key>(const uint8_t *userKey, int bits, AES_KEY *key); void aesni_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key); void aesni_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key); void aesni_ecb_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, int enc); void aesni_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t length, const AES_KEY *key, uint8_t *ivec, int enc); void <API key>(const uint8_t *in, uint8_t *out, size_t blocks, const void *key, const uint8_t *ivec); #if defined(OPENSSL_X86_64) size_t aesni_gcm_encrypt(const uint8_t *in, uint8_t *out, size_t len, const void *key, uint8_t ivec[16], uint64_t *Xi); #define AES_gcm_encrypt aesni_gcm_encrypt size_t aesni_gcm_decrypt(const uint8_t *in, uint8_t *out, size_t len, const void *key, uint8_t ivec[16], uint64_t *Xi); #define AES_gcm_decrypt aesni_gcm_decrypt void gcm_ghash_avx(uint64_t Xi[2], const u128 Htable[16], const uint8_t *in, size_t len); #define AES_GCM_ASM(gctx) \ (gctx->ctr == <API key> && gctx->gcm.ghash == gcm_ghash_avx) #endif /* OPENSSL_X86_64 */ #else /* On other platforms, aesni_capable() will always return false and so the * following will never be called. */ void aesni_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) { abort(); } int <API key>(const uint8_t *userKey, int bits, AES_KEY *key) { abort(); } void <API key>(const uint8_t *in, uint8_t *out, size_t blocks, const void *key, const uint8_t *ivec) { abort(); } #endif static int aes_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, const uint8_t *iv, int enc) { int ret, mode; EVP_AES_KEY *dat = (EVP_AES_KEY *)ctx->cipher_data; mode = ctx->cipher->flags & EVP_CIPH_MODE_MASK; if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { if (hwaes_capable()) { ret = <API key>(key, ctx->key_len * 8, &dat->ks.ks); dat->block = (block128_f)aes_v8_decrypt; dat->stream.cbc = NULL; if (mode == EVP_CIPH_CBC_MODE) { dat->stream.cbc = (cbc128_f)aes_v8_cbc_encrypt; } } else if (bsaes_capable() && mode == EVP_CIPH_CBC_MODE) { ret = AES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = (block128_f)AES_decrypt; dat->stream.cbc = (cbc128_f)bsaes_cbc_encrypt; } else if (vpaes_capable()) { ret = <API key>(key, ctx->key_len * 8, &dat->ks.ks); dat->block = (block128_f)vpaes_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f)vpaes_cbc_encrypt : NULL; } else { ret = AES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = (block128_f)AES_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f)AES_cbc_encrypt : NULL; } } else if (hwaes_capable()) { ret = <API key>(key, ctx->key_len * 8, &dat->ks.ks); dat->block = (block128_f)aes_v8_encrypt; dat->stream.cbc = NULL; if (mode == EVP_CIPH_CBC_MODE) { dat->stream.cbc = (cbc128_f)aes_v8_cbc_encrypt; } else if (mode == EVP_CIPH_CTR_MODE) { dat->stream.ctr = (ctr128_f)<API key>; } } else if (bsaes_capable() && mode == EVP_CIPH_CTR_MODE) { ret = AES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = (block128_f)AES_encrypt; dat->stream.ctr = (ctr128_f)<API key>; } else if (vpaes_capable()) { ret = <API key>(key, ctx->key_len * 8, &dat->ks.ks); dat->block = (block128_f)vpaes_encrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f)vpaes_cbc_encrypt : NULL; } else { ret = AES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks); dat->block = (block128_f)AES_encrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f)AES_cbc_encrypt : NULL; } if (ret < 0) { OPENSSL_PUT_ERROR(CIPHER, aes_init_key, <API key>); return 0; } return 1; } static int aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = (EVP_AES_KEY *)ctx->cipher_data; if (dat->stream.cbc) { (*dat->stream.cbc)(in, out, len, &dat->ks, ctx->iv, ctx->encrypt); } else if (ctx->encrypt) { <API key>(in, out, len, &dat->ks, ctx->iv, dat->block); } else { <API key>(in, out, len, &dat->ks, ctx->iv, dat->block); } return 1; } static int aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { size_t bl = ctx->cipher->block_size; size_t i; EVP_AES_KEY *dat = (EVP_AES_KEY *)ctx->cipher_data; if (len < bl) { return 1; } for (i = 0, len -= bl; i <= len; i += bl) { (*dat->block)(in + i, out + i, &dat->ks); } return 1; } static int aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { unsigned int num = ctx->num; EVP_AES_KEY *dat = (EVP_AES_KEY *)ctx->cipher_data; if (dat->stream.ctr) { <API key>(in, out, len, &dat->ks, ctx->iv, ctx->buf, &num, dat->stream.ctr); } else { <API key>(in, out, len, &dat->ks, ctx->iv, ctx->buf, &num, dat->block); } ctx->num = (size_t)num; return 1; } static char aesni_capable(void); static ctr128_f aes_ctr_set_key(AES_KEY *aes_key, GCM128_CONTEXT *gcm_ctx, block128_f *out_block, const uint8_t *key, size_t key_len) { if (aesni_capable()) { <API key>(key, key_len * 8, aes_key); if (gcm_ctx != NULL) { CRYPTO_gcm128_init(gcm_ctx, aes_key, (block128_f)aesni_encrypt); } if (out_block) { *out_block = (block128_f) aesni_encrypt; } return (ctr128_f)<API key>; } if (hwaes_capable()) { <API key>(key, key_len * 8, aes_key); if (gcm_ctx != NULL) { CRYPTO_gcm128_init(gcm_ctx, aes_key, (block128_f)aes_v8_encrypt); } if (out_block) { *out_block = (block128_f) aes_v8_encrypt; } return (ctr128_f)<API key>; } if (bsaes_capable()) { AES_set_encrypt_key(key, key_len * 8, aes_key); if (gcm_ctx != NULL) { CRYPTO_gcm128_init(gcm_ctx, aes_key, (block128_f)AES_encrypt); } if (out_block) { *out_block = (block128_f) AES_encrypt; } return (ctr128_f)<API key>; } if (vpaes_capable()) { <API key>(key, key_len * 8, aes_key); if (out_block) { *out_block = (block128_f) vpaes_encrypt; } if (gcm_ctx != NULL) { CRYPTO_gcm128_init(gcm_ctx, aes_key, (block128_f)vpaes_encrypt); } return NULL; } AES_set_encrypt_key(key, key_len * 8, aes_key); if (gcm_ctx != NULL) { CRYPTO_gcm128_init(gcm_ctx, aes_key, (block128_f)AES_encrypt); } if (out_block) { *out_block = (block128_f) AES_encrypt; } return NULL; } static int aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, const uint8_t *iv, int enc) { EVP_AES_GCM_CTX *gctx = ctx->cipher_data; if (!iv && !key) { return 1; } if (key) { gctx->ctr = aes_ctr_set_key(&gctx->ks.ks, &gctx->gcm, NULL, key, ctx->key_len); /* If we have an iv can set it directly, otherwise use saved IV. */ if (iv == NULL && gctx->iv_set) { iv = gctx->iv; } if (iv) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); gctx->iv_set = 1; } gctx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (gctx->key_set) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); } else { memcpy(gctx->iv, iv, gctx->ivlen); } gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } static void aes_gcm_cleanup(EVP_CIPHER_CTX *c) { EVP_AES_GCM_CTX *gctx = c->cipher_data; OPENSSL_cleanse(&gctx->gcm, sizeof(gctx->gcm)); if (gctx->iv != c->iv) { OPENSSL_free(gctx->iv); } } /* increment counter (64-bit int) by 1 */ static void ctr64_inc(uint8_t *counter) { int n = 8; uint8_t c; do { --n; c = counter[n]; ++c; counter[n] = c; if (c) { return; } } while (n); } static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_GCM_CTX *gctx = c->cipher_data; switch (type) { case EVP_CTRL_INIT: gctx->key_set = 0; gctx->iv_set = 0; gctx->ivlen = c->cipher->iv_len; gctx->iv = c->iv; gctx->taglen = -1; gctx->iv_gen = 0; return 1; case <API key>: if (arg <= 0) { return 0; } /* Allocate memory for IV if needed */ if (arg > EVP_MAX_IV_LENGTH && arg > gctx->ivlen) { if (gctx->iv != c->iv) { OPENSSL_free(gctx->iv); } gctx->iv = OPENSSL_malloc(arg); if (!gctx->iv) { return 0; } } gctx->ivlen = arg; return 1; case <API key>: if (arg <= 0 || arg > 16 || c->encrypt) { return 0; } memcpy(c->buf, ptr, arg); gctx->taglen = arg; return 1; case <API key>: if (arg <= 0 || arg > 16 || !c->encrypt || gctx->taglen < 0) { return 0; } memcpy(ptr, c->buf, arg); return 1; case <API key>: /* Special case: -1 length restores whole IV */ if (arg == -1) { memcpy(gctx->iv, ptr, gctx->ivlen); gctx->iv_gen = 1; return 1; } /* Fixed field must be at least 4 bytes and invocation field * at least 8. */ if (arg < 4 || (gctx->ivlen - arg) < 8) { return 0; } if (arg) { memcpy(gctx->iv, ptr, arg); } if (c->encrypt && !RAND_bytes(gctx->iv + arg, gctx->ivlen - arg)) { return 0; } gctx->iv_gen = 1; return 1; case EVP_CTRL_GCM_IV_GEN: if (gctx->iv_gen == 0 || gctx->key_set == 0) { return 0; } CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); if (arg <= 0 || arg > gctx->ivlen) { arg = gctx->ivlen; } memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg); /* Invocation field will be at least 8 bytes in size and * so no need to check wrap around or increment more than * last 8 bytes. */ ctr64_inc(gctx->iv + gctx->ivlen - 8); gctx->iv_set = 1; return 1; case <API key>: if (gctx->iv_gen == 0 || gctx->key_set == 0 || c->encrypt) { return 0; } memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); gctx->iv_set = 1; return 1; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_GCM_CTX *gctx_out = out->cipher_data; if (gctx->gcm.key) { if (gctx->gcm.key != &gctx->ks) { return 0; } gctx_out->gcm.key = &gctx_out->ks; } if (gctx->iv == c->iv) { gctx_out->iv = out->iv; } else { gctx_out->iv = OPENSSL_malloc(gctx->ivlen); if (!gctx_out->iv) { return 0; } memcpy(gctx_out->iv, gctx->iv, gctx->ivlen); } return 1; } default: return -1; } } static int aes_gcm_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, size_t len) { EVP_AES_GCM_CTX *gctx = ctx->cipher_data; /* If not set up, return error */ if (!gctx->key_set) { return -1; } if (!gctx->iv_set) { return -1; } if (in) { if (out == NULL) { if (!CRYPTO_gcm128_aad(&gctx->gcm, in, len)) { return -1; } } else if (ctx->encrypt) { if (gctx->ctr) { size_t bulk = 0; #if defined(AES_GCM_ASM) if (len >= 32 && AES_GCM_ASM(gctx)) { size_t res = (16 - gctx->gcm.mres) % 16; if (!<API key>(&gctx->gcm, in, out, res)) { return -1; } bulk = AES_gcm_encrypt(in + res, out + res, len - res, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; bulk += res; } #endif if (!<API key>(&gctx->gcm, in + bulk, out + bulk, len - bulk, gctx->ctr)) { return -1; } } else { size_t bulk = 0; if (!<API key>(&gctx->gcm, in + bulk, out + bulk, len - bulk)) { return -1; } } } else { if (gctx->ctr) { size_t bulk = 0; #if defined(AES_GCM_ASM) if (len >= 16 && AES_GCM_ASM(gctx)) { size_t res = (16 - gctx->gcm.mres) % 16; if (!<API key>(&gctx->gcm, in, out, res)) { return -1; } bulk = AES_gcm_decrypt(in + res, out + res, len - res, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; bulk += res; } #endif if (!<API key>(&gctx->gcm, in + bulk, out + bulk, len - bulk, gctx->ctr)) { return -1; } } else { size_t bulk = 0; if (!<API key>(&gctx->gcm, in + bulk, out + bulk, len - bulk)) { return -1; } } } return len; } else { if (!ctx->encrypt) { if (gctx->taglen < 0 || !<API key>(&gctx->gcm, ctx->buf, gctx->taglen) != 0) { return -1; } gctx->iv_set = 0; return 0; } CRYPTO_gcm128_tag(&gctx->gcm, ctx->buf, 16); gctx->taglen = 16; /* Don't reuse the IV */ gctx->iv_set = 0; return 0; } } static const EVP_CIPHER aes_128_cbc = { NID_aes_128_cbc, 16 /* block_size */, 16 /* key_size */, 16 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_CBC_MODE, NULL /* app_data */, aes_init_key, aes_cbc_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aes_128_ctr = { NID_aes_128_ctr, 1 /* block_size */, 16 /* key_size */, 16 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_CTR_MODE, NULL /* app_data */, aes_init_key, aes_ctr_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aes_128_ecb = { NID_aes_128_ecb, 16 /* block_size */, 16 /* key_size */, 0 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_ECB_MODE, NULL /* app_data */, aes_init_key, aes_ecb_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aes_128_gcm = { NID_aes_128_gcm, 1 /* block_size */, 16 /* key_size */, 12 /* iv_len */, sizeof(EVP_AES_GCM_CTX), EVP_CIPH_GCM_MODE | EVP_CIPH_CUSTOM_IV | <API key> | <API key> | EVP_CIPH_CTRL_INIT | <API key>, NULL /* app_data */, aes_gcm_init_key, aes_gcm_cipher, aes_gcm_cleanup, aes_gcm_ctrl}; static const EVP_CIPHER aes_256_cbc = { NID_aes_256_cbc, 16 /* block_size */, 32 /* key_size */, 16 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_CBC_MODE, NULL /* app_data */, aes_init_key, aes_cbc_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aes_256_ctr = { NID_aes_256_ctr, 1 /* block_size */, 32 /* key_size */, 16 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_CTR_MODE, NULL /* app_data */, aes_init_key, aes_ctr_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aes_256_ecb = { NID_aes_256_ecb, 16 /* block_size */, 32 /* key_size */, 0 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_ECB_MODE, NULL /* app_data */, aes_init_key, aes_ecb_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aes_256_gcm = { NID_aes_256_gcm, 1 /* block_size */, 32 /* key_size */, 12 /* iv_len */, sizeof(EVP_AES_GCM_CTX), EVP_CIPH_GCM_MODE | EVP_CIPH_CUSTOM_IV | <API key> | <API key> | EVP_CIPH_CTRL_INIT | <API key>, NULL /* app_data */, aes_gcm_init_key, aes_gcm_cipher, aes_gcm_cleanup, aes_gcm_ctrl}; #if !defined(OPENSSL_NO_ASM) && \ (defined(OPENSSL_X86_64) || defined(OPENSSL_X86)) /* AES-NI section. */ static char aesni_capable(void) { return (OPENSSL_ia32cap_P[1] & (1 << (57 - 32))) != 0; } static int aesni_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, const uint8_t *iv, int enc) { int ret, mode; EVP_AES_KEY *dat = (EVP_AES_KEY *)ctx->cipher_data; mode = ctx->cipher->flags & EVP_CIPH_MODE_MASK; if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { ret = <API key>(key, ctx->key_len * 8, ctx->cipher_data); dat->block = (block128_f)aesni_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f)aesni_cbc_encrypt : NULL; } else { ret = <API key>(key, ctx->key_len * 8, ctx->cipher_data); dat->block = (block128_f)aesni_encrypt; if (mode == EVP_CIPH_CBC_MODE) { dat->stream.cbc = (cbc128_f)aesni_cbc_encrypt; } else if (mode == EVP_CIPH_CTR_MODE) { dat->stream.ctr = (ctr128_f)<API key>; } else { dat->stream.cbc = NULL; } } if (ret < 0) { OPENSSL_PUT_ERROR(CIPHER, aesni_init_key, <API key>); return 0; } return 1; } static int aesni_cbc_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, size_t len) { aesni_cbc_encrypt(in, out, len, ctx->cipher_data, ctx->iv, ctx->encrypt); return 1; } static int aesni_ecb_cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, size_t len) { size_t bl = ctx->cipher->block_size; if (len < bl) { return 1; } aesni_ecb_encrypt(in, out, len, ctx->cipher_data, ctx->encrypt); return 1; } static int aesni_gcm_init_key(EVP_CIPHER_CTX *ctx, const uint8_t *key, const uint8_t *iv, int enc) { EVP_AES_GCM_CTX *gctx = ctx->cipher_data; if (!iv && !key) { return 1; } if (key) { <API key>(key, ctx->key_len * 8, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f)aesni_encrypt); gctx->ctr = (ctr128_f)<API key>; /* If we have an iv can set it directly, otherwise use * saved IV. */ if (iv == NULL && gctx->iv_set) { iv = gctx->iv; } if (iv) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); gctx->iv_set = 1; } gctx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (gctx->key_set) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); } else { memcpy(gctx->iv, iv, gctx->ivlen); } gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } static const EVP_CIPHER aesni_128_cbc = { NID_aes_128_cbc, 16 /* block_size */, 16 /* key_size */, 16 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_CBC_MODE, NULL /* app_data */, aesni_init_key, aesni_cbc_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aesni_128_ctr = { NID_aes_128_ctr, 1 /* block_size */, 16 /* key_size */, 16 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_CTR_MODE, NULL /* app_data */, aesni_init_key, aes_ctr_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aesni_128_ecb = { NID_aes_128_ecb, 16 /* block_size */, 16 /* key_size */, 0 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_ECB_MODE, NULL /* app_data */, aesni_init_key, aesni_ecb_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aesni_128_gcm = { NID_aes_128_gcm, 1 /* block_size */, 16 /* key_size */, 12 /* iv_len */, sizeof(EVP_AES_GCM_CTX), EVP_CIPH_GCM_MODE | EVP_CIPH_CUSTOM_IV | <API key> | <API key> | EVP_CIPH_CTRL_INIT | <API key>, NULL /* app_data */, aesni_gcm_init_key, aes_gcm_cipher, aes_gcm_cleanup, aes_gcm_ctrl}; static const EVP_CIPHER aesni_256_cbc = { NID_aes_256_cbc, 16 /* block_size */, 32 /* key_size */, 16 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_CBC_MODE, NULL /* app_data */, aesni_init_key, aesni_cbc_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aesni_256_ctr = { NID_aes_256_ctr, 1 /* block_size */, 32 /* key_size */, 16 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_CTR_MODE, NULL /* app_data */, aesni_init_key, aes_ctr_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aesni_256_ecb = { NID_aes_256_ecb, 16 /* block_size */, 32 /* key_size */, 0 /* iv_len */, sizeof(EVP_AES_KEY), EVP_CIPH_ECB_MODE, NULL /* app_data */, aesni_init_key, aesni_ecb_cipher, NULL /* cleanup */, NULL /* ctrl */}; static const EVP_CIPHER aesni_256_gcm = { NID_aes_256_gcm, 1 /* block_size */, 32 /* key_size */, 12 /* iv_len */, sizeof(EVP_AES_GCM_CTX), EVP_CIPH_GCM_MODE | EVP_CIPH_CUSTOM_IV | <API key> | <API key> | EVP_CIPH_CTRL_INIT | <API key> | <API key>, NULL /* app_data */, aesni_gcm_init_key, aes_gcm_cipher, aes_gcm_cleanup, aes_gcm_ctrl}; #define EVP_CIPHER_FUNCTION(keybits, mode) \ const EVP_CIPHER *EVP_aes_##keybits##_##mode(void) { \ if (aesni_capable()) { \ return &aesni_##keybits##_##mode; \ } else { \ return &aes_##keybits##_##mode; \ } \ } #else /* ^^^ OPENSSL_X86_64 || OPENSSL_X86 */ static char aesni_capable(void) { return 0; } #define EVP_CIPHER_FUNCTION(keybits, mode) \ const EVP_CIPHER *EVP_aes_##keybits##_##mode(void) { \ return &aes_##keybits##_##mode; \ } #endif EVP_CIPHER_FUNCTION(128, cbc) EVP_CIPHER_FUNCTION(128, ctr) EVP_CIPHER_FUNCTION(128, ecb) EVP_CIPHER_FUNCTION(128, gcm) EVP_CIPHER_FUNCTION(256, cbc) EVP_CIPHER_FUNCTION(256, ctr) EVP_CIPHER_FUNCTION(256, ecb) EVP_CIPHER_FUNCTION(256, gcm) #define <API key> 16 struct aead_aes_gcm_ctx { union { double align; AES_KEY ks; } ks; GCM128_CONTEXT gcm; ctr128_f ctr; uint8_t tag_len; }; static int aead_aes_gcm_init(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len, size_t tag_len) { struct aead_aes_gcm_ctx *gcm_ctx; const size_t key_bits = key_len * 8; if (key_bits != 128 && key_bits != 256) { OPENSSL_PUT_ERROR(CIPHER, aead_aes_gcm_init, <API key>); return 0; /* EVP_AEAD_CTX_init should catch this. */ } if (tag_len == <API key>) { tag_len = <API key>; } if (tag_len > <API key>) { OPENSSL_PUT_ERROR(CIPHER, aead_aes_gcm_init, <API key>); return 0; } gcm_ctx = OPENSSL_malloc(sizeof(struct aead_aes_gcm_ctx)); if (gcm_ctx == NULL) { return 0; } gcm_ctx->ctr = aes_ctr_set_key(&gcm_ctx->ks.ks, &gcm_ctx->gcm, NULL, key, key_len); gcm_ctx->tag_len = tag_len; ctx->aead_state = gcm_ctx; return 1; } static void <API key>(EVP_AEAD_CTX *ctx) { struct aead_aes_gcm_ctx *gcm_ctx = ctx->aead_state; OPENSSL_cleanse(gcm_ctx, sizeof(struct aead_aes_gcm_ctx)); OPENSSL_free(gcm_ctx); } static int aead_aes_gcm_seal(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len, const uint8_t *nonce, size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *ad, size_t ad_len) { size_t bulk = 0; const struct aead_aes_gcm_ctx *gcm_ctx = ctx->aead_state; GCM128_CONTEXT gcm; if (in_len + gcm_ctx->tag_len < in_len) { OPENSSL_PUT_ERROR(CIPHER, aead_aes_gcm_seal, CIPHER_R_TOO_LARGE); return 0; } if (max_out_len < in_len + gcm_ctx->tag_len) { OPENSSL_PUT_ERROR(CIPHER, aead_aes_gcm_seal, <API key>); return 0; } memcpy(&gcm, &gcm_ctx->gcm, sizeof(gcm)); CRYPTO_gcm128_setiv(&gcm, nonce, nonce_len); if (ad_len > 0 && !CRYPTO_gcm128_aad(&gcm, ad, ad_len)) { return 0; } if (gcm_ctx->ctr) { if (!<API key>(&gcm, in + bulk, out + bulk, in_len - bulk, gcm_ctx->ctr)) { return 0; } } else { if (!<API key>(&gcm, in + bulk, out + bulk, in_len - bulk)) { return 0; } } CRYPTO_gcm128_tag(&gcm, out + in_len, gcm_ctx->tag_len); *out_len = in_len + gcm_ctx->tag_len; return 1; } static int aead_aes_gcm_open(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len, const uint8_t *nonce, size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *ad, size_t ad_len) { size_t bulk = 0; const struct aead_aes_gcm_ctx *gcm_ctx = ctx->aead_state; uint8_t tag[<API key>]; size_t plaintext_len; GCM128_CONTEXT gcm; if (in_len < gcm_ctx->tag_len) { OPENSSL_PUT_ERROR(CIPHER, aead_aes_gcm_open, <API key>); return 0; } plaintext_len = in_len - gcm_ctx->tag_len; if (max_out_len < plaintext_len) { OPENSSL_PUT_ERROR(CIPHER, aead_aes_gcm_open, <API key>); return 0; } memcpy(&gcm, &gcm_ctx->gcm, sizeof(gcm)); CRYPTO_gcm128_setiv(&gcm, nonce, nonce_len); if (!CRYPTO_gcm128_aad(&gcm, ad, ad_len)) { return 0; } if (gcm_ctx->ctr) { if (!<API key>(&gcm, in + bulk, out + bulk, in_len - bulk - gcm_ctx->tag_len, gcm_ctx->ctr)) { return 0; } } else { if (!<API key>(&gcm, in + bulk, out + bulk, in_len - bulk - gcm_ctx->tag_len)) { return 0; } } CRYPTO_gcm128_tag(&gcm, tag, gcm_ctx->tag_len); if (CRYPTO_memcmp(tag, in + plaintext_len, gcm_ctx->tag_len) != 0) { OPENSSL_PUT_ERROR(CIPHER, aead_aes_gcm_open, <API key>); return 0; } *out_len = plaintext_len; return 1; } static const EVP_AEAD aead_aes_128_gcm = { 16, /* key len */ 12, /* nonce len */ <API key>, /* overhead */ <API key>, /* max tag length */ aead_aes_gcm_init, NULL, /* init_with_direction */ <API key>, aead_aes_gcm_seal, aead_aes_gcm_open, NULL, /* get_rc4_state */ }; static const EVP_AEAD aead_aes_256_gcm = { 32, /* key len */ 12, /* nonce len */ <API key>, /* overhead */ <API key>, /* max tag length */ aead_aes_gcm_init, NULL, /* init_with_direction */ <API key>, aead_aes_gcm_seal, aead_aes_gcm_open, NULL, /* get_rc4_state */ }; const EVP_AEAD *<API key>(void) { return &aead_aes_128_gcm; } const EVP_AEAD *<API key>(void) { return &aead_aes_256_gcm; } struct <API key> { uint8_t key[32]; unsigned key_bits; }; static int <API key>(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len, size_t tag_len) { struct <API key> *kw_ctx; const size_t key_bits = key_len * 8; if (key_bits != 128 && key_bits != 256) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; /* EVP_AEAD_CTX_init should catch this. */ } if (tag_len == <API key>) { tag_len = 8; } if (tag_len != 8) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } kw_ctx = OPENSSL_malloc(sizeof(struct <API key>)); if (kw_ctx == NULL) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } memcpy(kw_ctx->key, key, key_len); kw_ctx->key_bits = key_bits; ctx->aead_state = kw_ctx; return 1; } static void <API key>(EVP_AEAD_CTX *ctx) { struct <API key> *kw_ctx = ctx->aead_state; OPENSSL_cleanse(kw_ctx, sizeof(struct <API key>)); OPENSSL_free(kw_ctx); } /* <API key> is the default nonce value given in 2.2.3.1. */ static const uint8_t <API key>[8] = {0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6}; static int <API key>(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len, const uint8_t *nonce, size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *ad, size_t ad_len) { const struct <API key> *kw_ctx = ctx->aead_state; union { double align; AES_KEY ks; } ks; /* Variables in this function match up with the variables in the second half * of section 2.2.1. */ unsigned i, j, n; uint8_t A[AES_BLOCK_SIZE]; if (ad_len != 0) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } if (nonce_len == 0) { nonce = <API key>; nonce_len = sizeof(<API key>); } if (nonce_len != 8) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } if (in_len % 8 != 0) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } /* The code below only handles a 32-bit |t| thus 6*|n| must be less than * 2^32, where |n| is |in_len| / 8. So in_len < 4/3 * 2^32 and we * conservatively cap it to 2^32-16 to stop 32-bit platforms complaining that * a comparison is always true. */ if (in_len > 0xfffffff0) { OPENSSL_PUT_ERROR(CIPHER, <API key>, CIPHER_R_TOO_LARGE); return 0; } n = in_len / 8; if (n < 2) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } if (in_len + 8 < in_len) { OPENSSL_PUT_ERROR(CIPHER, <API key>, CIPHER_R_TOO_LARGE); return 0; } if (max_out_len < in_len + 8) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } if (AES_set_encrypt_key(kw_ctx->key, kw_ctx->key_bits, &ks.ks) < 0) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } memmove(out + 8, in, in_len); memcpy(A, nonce, 8); for (j = 0; j < 6; j++) { for (i = 1; i <= n; i++) { uint32_t t; memcpy(A + 8, out + 8 * i, 8); AES_encrypt(A, A, &ks.ks); t = n * j + i; A[7] ^= t & 0xff; A[6] ^= (t >> 8) & 0xff; A[5] ^= (t >> 16) & 0xff; A[4] ^= (t >> 24) & 0xff; memcpy(out + 8 * i, A + 8, 8); } } memcpy(out, A, 8); *out_len = in_len + 8; return 1; } static int <API key>(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len, const uint8_t *nonce, size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *ad, size_t ad_len) { const struct <API key> *kw_ctx = ctx->aead_state; union { double align; AES_KEY ks; } ks; /* Variables in this function match up with the variables in the second half * of section 2.2.1. */ unsigned i, j, n; uint8_t A[AES_BLOCK_SIZE]; if (ad_len != 0) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } if (nonce_len == 0) { nonce = <API key>; nonce_len = sizeof(<API key>); } if (nonce_len != 8) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } if (in_len % 8 != 0) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } /* The code below only handles a 32-bit |t| thus 6*|n| must be less than * 2^32, where |n| is |in_len| / 8. So in_len < 4/3 * 2^32 and we * conservatively cap it to 2^32-8 to stop 32-bit platforms complaining that * a comparison is always true. */ if (in_len > 0xfffffff8) { OPENSSL_PUT_ERROR(CIPHER, <API key>, CIPHER_R_TOO_LARGE); return 0; } if (in_len < 24) { OPENSSL_PUT_ERROR(CIPHER, aead_aes_gcm_open, <API key>); return 0; } n = (in_len / 8) - 1; if (max_out_len < in_len - 8) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } if (AES_set_decrypt_key(kw_ctx->key, kw_ctx->key_bits, &ks.ks) < 0) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } memcpy(A, in, 8); memmove(out, in + 8, in_len - 8); for (j = 5; j < 6; j for (i = n; i > 0; i uint32_t t; t = n * j + i; A[7] ^= t & 0xff; A[6] ^= (t >> 8) & 0xff; A[5] ^= (t >> 16) & 0xff; A[4] ^= (t >> 24) & 0xff; memcpy(A + 8, out + 8 * (i - 1), 8); AES_decrypt(A, A, &ks.ks); memcpy(out + 8 * (i - 1), A + 8, 8); } } if (CRYPTO_memcmp(A, nonce, 8) != 0) { OPENSSL_PUT_ERROR(CIPHER, aead_aes_gcm_open, <API key>); return 0; } *out_len = in_len - 8; return 1; } static const EVP_AEAD <API key> = { 16, /* key len */ 8, /* nonce len */ 8, /* overhead */ 8, /* max tag length */ <API key>, NULL, /* init_with_direction */ <API key>, <API key>, <API key>, NULL, /* get_rc4_state */ }; static const EVP_AEAD <API key> = { 32, /* key len */ 8, /* nonce len */ 8, /* overhead */ 8, /* max tag length */ <API key>, NULL, /* init_with_direction */ <API key>, <API key>, <API key>, NULL, /* get_rc4_state */ }; const EVP_AEAD *<API key>(void) { return &<API key>; } const EVP_AEAD *<API key>(void) { return &<API key>; } #define <API key> <API key> #define <API key> 12 struct <API key> { union { double align; AES_KEY ks; } ks; ctr128_f ctr; block128_f block; SHA256_CTX inner_init_state; SHA256_CTX outer_init_state; uint8_t tag_len; }; static void hmac_init(SHA256_CTX *out_inner, SHA256_CTX *out_outer, const uint8_t hmac_key[32]) { static const size_t hmac_key_len = 32; uint8_t block[SHA256_CBLOCK]; memcpy(block, hmac_key, hmac_key_len); memset(block + hmac_key_len, 0x36, sizeof(block) - hmac_key_len); unsigned i; for (i = 0; i < hmac_key_len; i++) { block[i] ^= 0x36; } SHA256_Init(out_inner); SHA256_Update(out_inner, block, sizeof(block)); memset(block + hmac_key_len, 0x5c, sizeof(block) - hmac_key_len); for (i = 0; i < hmac_key_len; i++) { block[i] ^= (0x36 ^ 0x5c); } SHA256_Init(out_outer); SHA256_Update(out_outer, block, sizeof(block)); } static int <API key>(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len, size_t tag_len) { struct <API key> *aes_ctx; static const size_t hmac_key_len = 32; if (key_len < hmac_key_len) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; /* EVP_AEAD_CTX_init should catch this. */ } const size_t aes_key_len = key_len - hmac_key_len; if (aes_key_len != 16 && aes_key_len != 32) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; /* EVP_AEAD_CTX_init should catch this. */ } if (tag_len == <API key>) { tag_len = <API key>; } if (tag_len > <API key>) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } aes_ctx = OPENSSL_malloc(sizeof(struct <API key>)); if (aes_ctx == NULL) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } aes_ctx->ctr = aes_ctr_set_key(&aes_ctx->ks.ks, NULL, &aes_ctx->block, key, aes_key_len); aes_ctx->tag_len = tag_len; hmac_init(&aes_ctx->inner_init_state, &aes_ctx->outer_init_state, key + aes_key_len); ctx->aead_state = aes_ctx; return 1; } static void <API key>(EVP_AEAD_CTX *ctx) { struct <API key> *aes_ctx = ctx->aead_state; OPENSSL_cleanse(aes_ctx, sizeof(struct <API key>)); OPENSSL_free(aes_ctx); } static void hmac_update_uint64(SHA256_CTX *sha256, uint64_t value) { unsigned i; uint8_t bytes[8]; for (i = 0; i < sizeof(bytes); i++) { bytes[i] = value & 0xff; value >>= 8; } SHA256_Update(sha256, bytes, sizeof(bytes)); } static void hmac_calculate(uint8_t out[<API key>], const SHA256_CTX *inner_init_state, const SHA256_CTX *outer_init_state, const uint8_t *ad, size_t ad_len, const uint8_t *nonce, const uint8_t *ciphertext, size_t ciphertext_len) { SHA256_CTX sha256; memcpy(&sha256, inner_init_state, sizeof(sha256)); hmac_update_uint64(&sha256, ad_len); hmac_update_uint64(&sha256, ciphertext_len); SHA256_Update(&sha256, nonce, <API key>); SHA256_Update(&sha256, ad, ad_len); /* Pad with zeros to the end of the SHA-256 block. */ const unsigned num_padding = (SHA256_CBLOCK - ((sizeof(uint64_t)*2 + <API key> + ad_len) % SHA256_CBLOCK)) % SHA256_CBLOCK; uint8_t padding[SHA256_CBLOCK]; memset(padding, 0, num_padding); SHA256_Update(&sha256, padding, num_padding); SHA256_Update(&sha256, ciphertext, ciphertext_len); uint8_t inner_digest[<API key>]; SHA256_Final(inner_digest, &sha256); memcpy(&sha256, outer_init_state, sizeof(sha256)); SHA256_Update(&sha256, inner_digest, sizeof(inner_digest)); SHA256_Final(out, &sha256); } static void <API key>( const struct <API key> *aes_ctx, uint8_t *out, const uint8_t *in, size_t len, const uint8_t *nonce) { /* Since the AEAD operation is one-shot, keeping a buffer of unused keystream * bytes is pointless. However, |<API key>| requires it. */ uint8_t <API key>[AES_BLOCK_SIZE]; unsigned <API key> = 0; memset(<API key>, 0, sizeof(<API key>)); uint8_t counter[AES_BLOCK_SIZE]; memcpy(counter, nonce, <API key>); memset(counter + <API key>, 0, 4); if (aes_ctx->ctr) { <API key>(in, out, len, &aes_ctx->ks.ks, counter, <API key>, &<API key>, aes_ctx->ctr); } else { <API key>(in, out, len, &aes_ctx->ks.ks, counter, <API key>, &<API key>, aes_ctx->block); } } static int <API key>(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len, const uint8_t *nonce, size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *ad, size_t ad_len) { const struct <API key> *aes_ctx = ctx->aead_state; const uint64_t in_len_64 = in_len; if (in_len + aes_ctx->tag_len < in_len || /* This input is so large it would overflow the 32-bit block counter. */ in_len_64 >= (OPENSSL_U64(1) << 32) * AES_BLOCK_SIZE) { OPENSSL_PUT_ERROR(CIPHER, <API key>, CIPHER_R_TOO_LARGE); return 0; } if (max_out_len < in_len + aes_ctx->tag_len) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } if (nonce_len != <API key>) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } <API key>(aes_ctx, out, in, in_len, nonce); uint8_t hmac_result[<API key>]; hmac_calculate(hmac_result, &aes_ctx->inner_init_state, &aes_ctx->outer_init_state, ad, ad_len, nonce, out, in_len); memcpy(out + in_len, hmac_result, aes_ctx->tag_len); *out_len = in_len + aes_ctx->tag_len; return 1; } static int <API key>(const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len, const uint8_t *nonce, size_t nonce_len, const uint8_t *in, size_t in_len, const uint8_t *ad, size_t ad_len) { const struct <API key> *aes_ctx = ctx->aead_state; size_t plaintext_len; if (in_len < aes_ctx->tag_len) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } plaintext_len = in_len - aes_ctx->tag_len; if (max_out_len < plaintext_len) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } if (nonce_len != <API key>) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } uint8_t hmac_result[<API key>]; hmac_calculate(hmac_result, &aes_ctx->inner_init_state, &aes_ctx->outer_init_state, ad, ad_len, nonce, in, plaintext_len); if (CRYPTO_memcmp(hmac_result, in + plaintext_len, aes_ctx->tag_len) != 0) { OPENSSL_PUT_ERROR(CIPHER, <API key>, <API key>); return 0; } <API key>(aes_ctx, out, in, plaintext_len, nonce); *out_len = plaintext_len; return 1; } static const EVP_AEAD <API key> = { 16 /* AES key */ + 32 /* HMAC key */, 12, /* nonce length */ <API key>, /* overhead */ <API key>, /* max tag length */ <API key>, NULL /* init_with_direction */, <API key>, <API key>, <API key>, }; static const EVP_AEAD <API key> = { 32 /* AES key */ + 32 /* HMAC key */, 12, /* nonce length */ <API key>, /* overhead */ <API key>, /* max tag length */ <API key>, NULL /* init_with_direction */, <API key>, <API key>, <API key>, }; const EVP_AEAD *<API key>(void) { return &<API key>; } const EVP_AEAD *<API key>(void) { return &<API key>; } int <API key>(void) { #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) return aesni_capable() && <API key>(); #elif defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) return hwaes_capable() && (OPENSSL_armcap_P & ARMV8_PMULL); #else return 0; #endif }
#!/bin/bash #bandwidth allocation experiments coefficients from guard relays on 1/1/13, cf network_analysis.py a = 299.45192815560563 b = 1104612.6683457776 r_squared = 0.74124917207592156 coefficients from exit relays 1/13-3/13, cf network_analysis.py a = 215.85762129136413 b = 1010231.1684564484 r_squared = 0.68600871839386535 #ratio guard bw exit bw guard cons bw exit cons bw #1:1 52428800 52428800 171394 238205 #2:1 69905067 34952533 229755 157244 #5:1 87381333 17476267 288115 76282 #10:1 95325091 9532509 314643 39481 #50:1 102801568 2056031 339610 4845 coefficients from guard relays 10/12-3/13, cf network_analysis.py # exit_a = 200.49050736264786 # exit_b = 1029509.7491675143 # exit_r_squared = 0.69361698646482162 coefficients from exit relays 10/12-3/13, cf network_analysis.py # guard_a = 191.94548955003913 # guard_b = 1368281.674385923 # guard_r_squared = 0.70610513990802581 #ratio guard bw exit bw guard cons bw exit cons bw #1:1 52428800 52428800 266016 256368 #2:1 69905067 34952533 357064 169200 #5:1 87381333 17476267 448112 82033 #10:1 95325091 9532509 489497 42411 #50:1 102801568 2056031 528448 5120 BASE_DIR=/home/ajohnson/research/torps.git NUM_PROCESSES=20 DATE_RANGE=$1 NSF_TYPE=$2 OUTPUT=2 ADV_GUARD_BW=$3 ADV_EXIT_BW=$4 ADV_TIME=0 NUM_ADV_GUARDS=1 USERMODEL=typical NUM_SAMPLES=5000 TRACEFILE=$BASE_DIR/in/users2-processed.traces.pickle PATH_ALG=tor EXP_NAME=$USERMODEL.$DATE_RANGE.$ADV_GUARD_BW-$ADV_EXIT_BW-$ADV_TIM-adv NSF_DIR=$BASE_DIR/out/network-state/$NSF_TYPE/ns-$DATE_RANGE # make output directory OUT_DIR=$BASE_DIR/out/simulate/$EXP_NAME mkdir -p $OUT_DIR i=1 while [ $i -le $NUM_PROCESSES ] do (time pypy pathsim.py simulate $NSF_DIR $NUM_SAMPLES $TRACEFILE $USERMODEL $OUTPUT $ADV_GUARD_BW $ADV_EXIT_BW $ADV_TIME $NUM_ADV_GUARDS $PATH_ALG) 2> $OUT_DIR/simulate.$EXP_NAME.$NUM_SAMPLES-samples.$i.time 1> $OUT_DIR/simulate.$EXP_NAME.$NUM_SAMPLES-samples.$i.out & i=$(($i+1)) done
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model backend\models\SaleorderlineSearch */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="<API key>"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <div class="form-inline"> <div class="input-group"> <?= $form->field($model, 'globalSearch')->textInput(['placeholder'=>'Search'])->label(false) ?> <span class="input-group"> <?= Html::submitButton('ค้นหา', ['class' => 'btn btn-flat']) ?> <!-- <button type='submit' name='search' id='search-btn' class="btn btn-flat"><i class="fa fa-search"></i> </button> </span> </div> </div> <?php ActiveForm::end(); ?> </div>
from nagm.engine.attack import Attack from .types import * from .defs import precision, stat, heal, offensive, faux_chage_effect prec = precision(prec=0.9) mimi_queue = Attack(name='Mimi-queue', type=normal, effects=(prec, stat(stat='dfse', value=-1),)) charge = Attack(name='Charge', type=normal, effects=(prec, offensive(force=10),)) griffe = Attack(name='Griffe', type=normal, effects=(prec, offensive(force=10),)) fouet_lianes = Attack(name='Fouet lianes', type=plante, effects=(prec, offensive(force=20),)) flameche = Attack(name='Flamèche', type=feu, effects=(prec, offensive(force=20),)) pistolet_a_o = Attack(name='Pistolet à o', type=eau, effects=(prec, offensive(force=20),)) eclair = Attack(name='Éclair', type=electrik, effects=(prec, offensive(force=20),)) soin = Attack(name='Soin', type=normal, effects=(prec, heal(heal=50),), reflexive=True) abime = Attack(name='Abîme', type=normal, effects=(precision(prec=0.1), offensive(force=1000),)) faux_chage = Attack(name='Faux-chage', type=normal, effects=(prec, faux_chage_effect,))
package org.sirix.gui.view.model.interfaces; import java.beans.<API key>; import java.util.Iterator; import java.util.List; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.nullness.qual.NonNull; import org.brackit.xquery.update.Insert; import org.sirix.gui.ReadDB; import org.sirix.gui.view.VisualItem; import org.sirix.gui.view.sunburst.SunburstItem; import org.sirix.gui.view.sunburst.SunburstView; /** * Interface which models of the {@link SunburstView} have to implement. * * All methods should throw {@code <API key>}s in case of null values for reference * parameters are passed and {@code <API key>} in case of any parameter which is * invalid. * * @author Johannes Lichtenberger, University of Konstanz * @param <S> type of container * @param <T> type of items * */ public interface Model<S, T extends VisualItem> extends Iterable<T>, Iterator<T>, <API key> { /** * Get the item reference which implements {@link VisualItem} at the specified index in a * datastructure. * * @param index the index * @return the {@link SunburstItem} at the specified index * @throws <API key> if {@code index > mItems.size() - 1 or < 0} */ T getItem(@NonNegative int index) throws <API key>; /** * Traverse the tree and create a {@link List} of {@link SunburstItem}s. * * @param container {@link Container} implementation with options */ void traverseTree(Container<S> container); /** Undo operation. */ void undo(); /** * Update root of the tree with the node currently clicked. * * @param container {@link Container} reference with options */ void update(final Container<S> container); /** * XPath evaluation. * * @param xPathExpression XPath expression to evaluate */ void evaluateXPath(String xPathExpression); /** * Spefify how to insert an XML fragment. * * @param paramInsert determines how to insert an XMl fragment */ void setInsert(Insert insert); /** * Update {@link ReadDB} instance. * * @param databaseReader used to read from a Sirix database * @param container {@link Container} instance */ void updateDb(ReadDB databaseReader, @NonNull Container<S> container); /** * Add a {@link <API key>}. * * @param listener the listener to add */ void <API key>(<API key> listener); /** * Remove a {@link <API key>}. * * @param listener the listener to remove */ void <API key>(<API key> listener); // /** // * Fire a property change. // * // * @param pPropertyName // * name of the property // * @param pOldValue // * old value // * @param pNewValue // * new value // */ // void firePropertyChange(String pPropertyName, @NonNull Object pOldValue, // @NonNull Object pNewValue); /** * Get the database handle. * * @return {@link ReadDB} reference */ ReadDB getDb(); /** * Set a list of new items. */ void setItems(List<T> pItems); /** * Set minimum and maximum text length as well as descendant count. */ void setMinMax(); /** * Get maximum depth. * * @return maximum depth */ int getDepthMax(); /** * Get the size of the item datastructure. * * @return items size */ int getItemsSize(); /** * Set the depth max of the outer ring. * * @param depthMax the new maximum depth */ void setNewDepthMax(@NonNegative int depthMax); /** * Set the depth max of the inner ring. * * @param pDepthMax the new maximum depth */ void setOldDepthMax(@NonNegative int oldDepthMax); /** * Get a sublist of items. * * @param fromIndex the index to start with (inclusive) * @param toIndex the index to end (exlusive) * @return sublist of items */ List<T> subList(@NonNegative int fromIndex, @NonNegative int toIndex); }
<?php namespace app\modules\task\models; //use Yii; use app\models\CActiveRecord; use app\modules\user\models\Company; use app\modules\user\models\User; /** * This is the model class for table "task_execute_info". * * @property integer $id * @property integer $company_id * @property integer $task_id * @property integer $money_id * @property string $price * @property string $finish_time * @property integer $create_author_uid * @property integer $update_author_uid * @property string $create_time * @property string $update_time */ class TaskExecuteInfo extends CActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'task_execute_info'; } /** * @inheritdoc */ public function rules() { return [ [['company_id', 'task_id', 'money_id', 'create_author_uid', 'update_author_uid'], 'integer'], [['price'], 'number'], [['finish_time'], 'string'], [['create_time', 'update_time'], 'safe'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'company_id' => '', 'task_id' => 'Task ID', 'money_id' => 'Money ID', 'price' => '', 'finish_time' => '', 'create_author_uid' => 'Create Author Uid', 'update_author_uid' => 'Update Author Uid', 'create_time' => 'Create Time', 'update_time' => 'Update Time', ]; } /** * @inheritdoc * @return <API key> the active query used by this AR class. */ public static function find() { return new <API key>(get_called_class()); } /** * * @return \yii\db\ActiveQuery */ public function getCreator() { return $this->hasOne(User::className(), ['id' => 'create_author_uid'])->alias('creator'); } /** * * @return \yii\db\ActiveQuery */ public function getUpdater() { return $this->hasOne(User::className(), ['id' => 'update_author_uid'])->alias('updater'); } public function getCompany() { return $this->hasOne(Company::className(),['id'=>'company_id']); } public function getUser() { return $this->hasMany(User::className(),['company_id'=>'company_id']); } }
from __future__ import unicode_literals from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.completion import WordCompleter, PathCompleter from prompt_toolkit.contrib.completers.system import SystemCompleter from prompt_toolkit.contrib.regular_languages.completion import GrammarCompleter from .grammar import COMMAND_GRAMMAR from .commands import get_commands, SET_COMMANDS __all__ = ( '<API key>', ) def <API key>(editor): commands = [c + ' ' for c in get_commands()] return GrammarCompleter(COMMAND_GRAMMAR, { 'command': WordCompleter(commands), 'location': PathCompleter(expanduser=True), 'set_option': WordCompleter(sorted(SET_COMMANDS)), 'buffer_name': BufferNameCompleter(editor), 'colorscheme': <API key>(editor), 'shell_command': SystemCompleter(), }) class BufferNameCompleter(Completer): """ Complete on buffer names. It is sufficient when the input appears anywhere in the buffer name, to trigger a completion. """ def __init__(self, editor): self.editor = editor def get_completions(self, document, complete_event): text = document.text_before_cursor for eb in self.editor.window_arrangement.editor_buffers: location = eb.location if location is not None and text in location: yield Completion(location, start_position=-len(text), display=location) class <API key>(Completer): """ Complete on the names of the color schemes that are currently known to the Editor instance. """ def __init__(self, editor): self.editor = editor def get_completions(self, document, complete_event): text = document.text_before_cursor for style_name in self.editor.styles: if style_name.startswith(text): yield Completion(style_name[len(text):], display=style_name)
package main import ( "flag" "fmt" "github.com/keybase/client/go/kbfs/env" "github.com/keybase/client/go/kbfs/fsrpc" "github.com/keybase/client/go/kbfs/libgit" "github.com/keybase/client/go/kbfs/libkbfs" "github.com/keybase/client/go/protocol/keybase1" "golang.org/x/net/context" ) const gitRenameUsageStr = `Usage: kbfstool git rename /keybase/tlf/path oldName newName ` func doGitRename(ctx context.Context, rpcHandler *libgit.RPCHandler, tlfStr, oldName, newName string) error { p, err := fsrpc.NewPath(tlfStr) if err != nil { return err } if p.PathType != fsrpc.TLFPathType { return fmt.Errorf("%q is not a TLF path", tlfStr) } if len(p.TLFComponents) > 0 { return fmt.Errorf("%q is not the root path of a TLF", tlfStr) } folder := keybase1.FolderHandle{ Name: p.TLFName, FolderType: p.TLFType.FolderType(), } return rpcHandler.RenameRepo(ctx, folder, oldName, newName) } func gitRename(ctx context.Context, config libkbfs.Config, args []string) (exitStatus int) { flags := flag.NewFlagSet("kbfs git rename", flag.ContinueOnError) err := flags.Parse(args) if err != nil { printError("git rename", err) return 1 } inputs := flags.Args() if len(inputs) != 3 { fmt.Print(gitRenameUsageStr) return 1 } kbfsCtx := env.NewContext() rpcHandler, shutdown := libgit.<API key>(kbfsCtx, config, nil) defer shutdown() err = doGitRename(ctx, rpcHandler, inputs[0], inputs[1], inputs[2]) if err != nil { printError("git rename", err) return 1 } return 0 }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_65) on Thu Mar 26 14:24:31 EDT 2015 --> <TITLE> Overview List (HIPI - Hadoop Image Processing Interface) </TITLE> <META NAME="date" CONTENT="2015-03-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TH ALIGN="left" NOWRAP><FONT size="+1" CLASS="FrameTitleFont"> <B></B></FONT></TH> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT CLASS="FrameItemFont"><A HREF="allclasses-frame.html" target="packageFrame">All Classes</A></FONT> <P> <FONT size="+1" CLASS="FrameHeadingFont"> Packages</FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="hipi/image/package-frame.html" target="packageFrame">hipi.image</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="hipi/image/convert/package-frame.html" target="packageFrame">hipi.image.convert</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="hipi/image/io/package-frame.html" target="packageFrame">hipi.image.io</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="hipi/imagebundle/package-frame.html" target="packageFrame">hipi.imagebundle</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="hipi/imagebundle/mapreduce/package-frame.html" target="packageFrame">hipi.imagebundle.mapreduce</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="hipi/imagebundle/mapreduce/output/package-frame.html" target="packageFrame">hipi.imagebundle.mapreduce.output</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="hipi/tool/package-frame.html" target="packageFrame">hipi.tool</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="hipi/unittest/package-frame.html" target="packageFrame">hipi.unittest</A></FONT> <BR> <FONT CLASS="FrameItemFont"><A HREF="hipi/util/package-frame.html" target="packageFrame">hipi.util</A></FONT> <BR> </TD> </TR> </TABLE> <P> &nbsp; </BODY> </HTML>
import json from functools import wraps from django.http import <API key> from django.shortcuts import render from django.utils import translation from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.http import require_POST from mobility.decorators import mobile_template from statsd import statsd import waffle from fjord.base.browsers import UNKNOWN from fjord.base.urlresolvers import reverse from fjord.base.utils import ( <API key>, ratelimit, smart_int, smart_str, <API key> ) from fjord.feedback import config from fjord.feedback import models from fjord.feedback.forms import ResponseForm from fjord.feedback.models import Response from fjord.feedback.utils import clean_url from fjord.feedback.config import TRUNCATE_LENGTH from fjord.suggest.utils import get_suggestions def happy_redirect(request): """Support older redirects from Input v1 era""" return <API key>(reverse('feedback') + '?happy=1') def sad_redirect(request): """Support older redirects from Input v1 era""" return <API key>(reverse('feedback') + '?happy=0') @mobile_template('feedback/{mobile/}download_firefox.html') def download_firefox(request, template): return render(request, template) def thanks(request): feedback = None suggestions = None # FIXME: Hard-coded default product. product = u'Firefox' response_id = None # If the user is an analyzer/admin, then we let them specify # the response_id via the querystring. This makes debugging # the system easier. if ((request.user.is_authenticated() and request.user.has_perm('analytics.can_view_dashboard'))): response_id = smart_int(request.GET.get('response_id', None)) # If we don't have a response_id, then pull it from the # session where it was placed if the user had just left # feedback. if not response_id: response_id = request.session.get('response_id') if response_id: try: feedback = Response.objects.get(id=response_id) except Response.DoesNotExist: pass if feedback: product = feedback.product if waffle.flag_is_active(request, 'thankyou'): suggestions = get_suggestions(feedback, request) return render(request, 'feedback/thanks.html', { 'product': product, 'feedback': feedback, 'suggestions': suggestions }) def requires_firefox(func): """Redirects to "download firefox" page if not Firefox. If it isn't a Firefox browser, then we don't want to deal with it. This is a temporary solution. See bug #848568. """ @wraps(func) def _requires_firefox(request, *args, **kwargs): # Note: This is sort of a lie. What's going on here is that # parse_ua only parses Firefox-y browsers. So if it's UNKNOWN # at this point, then it's not Firefox-y. If parse_ua ever # changes, then this will cease to be true. if request.BROWSER.browser == UNKNOWN: return <API key>(reverse('download-firefox')) return func(request, *args, **kwargs) return _requires_firefox @ratelimit(rulename='doublesubmit_1p10m', keyfun=<API key>( lambda req: req.POST.get('description', u'no description')), rate='1/10m') @ratelimit(rulename='50ph', rate='50/h') def <API key>(request, locale=None, product=None, version=None, channel=None): if getattr(request, 'limited', False): # If we're throttled, then return the thanks page, but don't # add the response to the db. return <API key>(reverse('thanks')) # Get the form and run is_valid() so it goes through the # validation and cleaning machinery. We don't really care if it's # valid, though, since we will take what we got and do the best we # can with it. Error validation is now in JS. form = ResponseForm(request.POST) form.is_valid() get_data = request.GET.copy() data = form.cleaned_data description = data.get('description', u'').strip() if not description: # If there's no description, then there's nothing to do here, # so thank the user and move on. return <API key>(reverse('thanks')) opinion = models.Response( # Data coming from the user happy=data['happy'], url=clean_url(data.get('url', u'').strip()), description=description, # Pulled from the form data or the url locale=data.get('locale', locale), # Data from mobile devices which is probably only # applicable to mobile devices manufacturer=data.get('manufacturer', ''), device=data.get('device', ''), ) # Add user_agent and inferred data. user_agent = request.META.get('HTTP_USER_AGENT', '') if user_agent: browser = request.BROWSER opinion.user_agent = user_agent opinion.browser = browser.browser opinion.browser_version = browser.browser_version opinion.browser_platform = browser.platform if browser.platform == 'Windows': opinion.browser_platform += ' ' + browser.platform_version # source is src or utm_source source = ( get_data.pop('src', [u''])[0] or get_data.pop('utm_source', [u''])[0] ) if source: opinion.source = source[:100] campaign = get_data.pop('utm_campaign', [u''])[0] if campaign: opinion.campaign = campaign[:100] # If they sent "happy=1"/"happy=0" in the querystring, it will get # picked up by the javascript in the form and we can just drop it # here. get_data.pop('happy', None) platform = u'' if product: # If we have a product at this point, then it came from the # url and it's a Product instance and we need to turn it into # the product.db_name which is a string. product_db_name = product.db_name else: # Check the POST data for the product. product_db_name = data.get('product', '') # For the version, we try the url data, then the POST data. version = version or data.get('version', '') # At this point, we have a bunch of values, but we might be # missing some values, too. We're going to cautiously infer data # from the user agent where we're very confident it's appropriate # to do so. if request.BROWSER != UNKNOWN: # If we don't have a product, try to infer that from the user # agent information. if not product_db_name: product_db_name = models.Response.infer_product(request.BROWSER) # If we have a product and it matches the user agent browser, # then we can infer the version and platform from the user # agent if they're missing. if product_db_name: product = models.Product.objects.get(db_name=product_db_name) if product.browser and product.browser == request.BROWSER.browser: if not version: version = request.BROWSER.browser_version if not platform: platform = models.Response.infer_platform( product_db_name, request.BROWSER) # Make sure values are at least empty strings--no Nones. opinion.product = product_db_name or u'' opinion.version = version or u'' opinion.channel = channel or u'' opinion.platform = platform or u'' opinion.save() # If there was an email address, save that separately. if data.get('email_ok') and data.get('email'): e = models.ResponseEmail(email=data['email'], opinion=opinion) e.save() statsd.incr('feedback.emaildata.optin') # If there's browser data, save that separately. if data.get('browser_ok'): # This comes in as a JSON string. Because we're using # JSONObjectField, we need to convert it back to Python and # then save it. This is kind of silly, but it does guarantee # we have valid JSON. try: browser_data = data['browser_data'] browser_data = json.loads(browser_data) except ValueError: # Handles empty string and any non-JSON value. statsd.incr('feedback.browserdata.badvalue') except KeyError: # Handles the case where it's missing from the data # dict. If it's missing, we don't want to do anything # including metrics. pass else: # If browser_data isn't an empty dict, then save it. if browser_data: rti = models.ResponsePI( data=browser_data, opinion=opinion) rti.save() statsd.incr('feedback.browserdata.optin') if get_data: # There was extra context in the query string, so we grab that # with some restrictions and save it separately. slop = {} # We capture at most the first 20 key/val pairs get_data_items = sorted(get_data.items())[:20] for key, val in get_data_items: # Keys can be at most 20 characters long. key = key[:20] if len(val) == 1: val = val[0] # Values can be at most 20 characters long. val = val[:100] slop[key.encode('utf-8')] = val.encode('utf-8') context = models.ResponseContext(data=slop, opinion=opinion) context.save() statsd.incr('feedback.contextdata.optin') if data['happy']: statsd.incr('feedback.happy') else: statsd.incr('feedback.sad') request.session['response_id'] = opinion.id return <API key>(reverse('thanks')) @csrf_protect def generic_feedback(request, locale=None, product=None, version=None, channel=None): """Generic feedback form for desktop and mobile""" form = ResponseForm() if request.method == 'POST': return <API key>(request, locale, product, version, channel) bd = product.<API key>(request.BROWSER.browser) return render(request, 'feedback/generic_feedback.html', { 'form': form, 'product': product, '<API key>': bd, 'TRUNCATE_LENGTH': TRUNCATE_LENGTH, }) @csrf_exempt def <API key>(request, locale=None, product=None, version=None, channel=None): # Localized country names are in region files in product # details. We try really hard to use localized country names, so # we use gettext and if that's not available, use whatever is in # product details. countries = [ (code, <API key>(translation.get_language(), code, name, name_l10n)) for code, name, name_l10n in config.<API key> ] return render(request, 'feedback/fxos_feedback.html', { 'countries': countries, 'devices': config.FIREFOX_OS_DEVICES, 'TRUNCATE_LENGTH': TRUNCATE_LENGTH, 'product': product }) @csrf_exempt @require_POST def <API key>(request, locale=None): """A view specifically for Firefox for Android. Firefox for Android has a feedback form built in that generates POSTS directly to Input, and is always sad or ideas. Since Input no longer supports idea feedbacks, everything is Sad. FIXME - measure usage of this and nix it when we can. See bug #964292. """ # Firefox for Android only sends up sad and idea responses, but it # uses the old `_type` variable from old Input. Tweak the data to do # what FfA means, not what it says. # Make `request.POST` mutable. request.POST = request.POST.copy() # For _type, 1 is happy, 2 is sad, 3 is idea. We convert that so # that _type = 1 -> happy = 1 and everything else -> happy = 0. if request.POST.get('_type') == '1': happy = 1 else: happy = 0 request.POST['happy'] = happy # Note: product, version and channel are always None in this view # since this is to handle <API key>. So we don't # bother passing them along. # We always return Thanks! now and ignore errors. return <API key>(request, locale) PRODUCT_OVERRIDE = { } def persist_feedbackdev(fun): """Persists a feedbackdev flag set via querystring in the cookies""" @wraps(fun) def <API key>(request, *args, **kwargs): qs_feedbackdev = request.GET.get('feedbackdev', None) resp = fun(request, *args, **kwargs) if resp is not None and qs_feedbackdev is not None: resp.set_cookie( waffle.settings.COOKIE_NAME % 'feedbackdev', qs_feedbackdev) return resp return <API key> @csrf_exempt @never_cache @persist_feedbackdev def feedback_router(request, product=None, version=None, channel=None, *args, **kwargs): """Determine a view to use, and call it. If product is given, reference `product_routes` to look up a view. If `product` is not passed, or isn't found in `product_routes`, asssume the user is either a stable desktop Firefox or a stable mobile Firefox based on the parsed UA, and serve them the appropriate page. This is to handle the old formname way of doing things. At some point P, we should measure usage of the old formnames and deprecate them. This also handles <API key> with the old Firefox for Android form which can't have a CSRF token. .. Note:: 1. We never want to cache this view 2. Pages returned from this view will get an:: X-Frame-Options: DENY HTTP header. That's important because these pages have magic powers and should never be used in frames. Please do not change this! """ view = None if '_type' in request.POST: # Checks to see if `_type` is in the POST data and if so this # is coming from Firefox for Android which doesn't know # anything about csrf tokens. If that's the case, we send it # to a view specifically for FfA Otherwise we pass it to one # of the normal views, which enforces CSRF. Also, nix the # product just in case we're crossing the streams and # confusing new-style product urls with old-style backwards # compatability for the Android form. # FIXME: Remove this hairbrained monstrosity when we don't need to # support the method that Firefox for Android currently uses to # post feedback which worked with the old input.mozilla.org. view = <API key> product = None # This lets us measure how often this section of code kicks # off and thus how often old android stuff is happening. When # we're not seeing this anymore, we can nix all the old # android stuff. statsd.incr('feedback.oldandroid') return <API key>(request, request.locale) # FIXME - validate these better product = smart_str(product, fallback=None) version = smart_str(version) channel = smart_str(channel).lower() if product == 'fxos' or request.BROWSER.browser == 'Firefox OS': # Firefox OS gets shunted to a different form which has # different Firefox OS specific questions. view = <API key> product = 'fxos' elif product in PRODUCT_OVERRIDE: # If the product is really a form name, we use that # form specifically. view = PRODUCT_OVERRIDE[product] product = None elif (product is None or product not in models.Product.objects.get_product_map()): picker_products = models.Product.objects.filter( enabled=True, on_picker=True) return render(request, 'feedback/picker.html', { 'products': picker_products }) product = models.Product.objects.from_slug(product) if view is None: view = generic_feedback return view(request, request.locale, product, version, channel, *args, **kwargs) def cyoa(request): template = 'feedback/picker.html' products = models.Product.objects.all() return render(request, template, { 'products': products })
<?php namespace Dive\Relation; use Dive\Collection\RecordCollection; use Dive\Record; use Dive\RecordManager; class Relation { const ONE_TO_ONE = '1-1'; const ONE_TO_MANY = '1-m'; /** * @var string */ protected $owningField = ''; /** * @var string */ protected $owningTable = ''; /** * @var string */ protected $owningAlias = ''; /** * @var string */ protected $refField = ''; /** * @var string */ protected $refTable = ''; /** * @var string */ protected $refAlias = ''; /** * @var int */ protected $type = ''; /** * @var string */ protected $onDelete = ''; /** * @var string */ protected $onUpdate = ''; /** * @var string */ protected $orderBy = ''; /** * @var ReferenceMap */ private $map = null; /** * constructor * @param string $owningAlias * @param string $owningTable * @param string $owningField * @param string $refAlias * @param string $refTable * @param string $refField * @param int $type * @param string $onDelete * @param string $onUpdate * @param string $orderBy * @throws \<API key> */ public function __construct( $owningAlias, $owningTable, $owningField, $refAlias, $refTable, $refField, $type, $onDelete = '', $onUpdate = '', $orderBy = '' ) { if ($owningAlias == $refAlias) { throw new \<API key>('Owning alias and referenced alias must not be equal!'); } $this->owningAlias = $owningAlias; $this->owningTable = $owningTable; $this->owningField = $owningField; $this->refAlias = $refAlias; $this->refTable = $refTable; $this->refField = $refField; $this->type = $type; $this->onDelete = $onDelete; $this->onUpdate = $onUpdate; $this->orderBy = $orderBy; $this->map = $this->isOneToMany() ? new ToManyReferenceMap($this) : new ToOneReferenceMap($this); } /** * @return array */ public function getDefinition() { return array( 'owningAlias' => $this->owningAlias, 'owningTable' => $this->owningTable, 'owningField' => $this->owningField, 'refAlias' => $this->refAlias, 'refTable' => $this->refTable, 'refField' => $this->refField, 'type' => $this->type, 'onDelete' => $this->onDelete, 'onUpdate' => $this->onUpdate, 'orderBy' => $this->orderBy, ); } /** * @param string $orderBy */ public function setOrderBy($orderBy) { $this->orderBy = $orderBy; } /** * Gets order by for relation * * @return string */ public function getOrderBy() { return $this->orderBy; } /** * @return bool */ public function isOneToOne() { return $this->type === self::ONE_TO_ONE; } /** * @return bool */ public function isOneToMany() { return $this->type === self::ONE_TO_MANY; } /** * Returns true, if relation name refers to the owning side * * @param string $relationName * @return bool */ public function isOwningSide($relationName) { return $relationName === $this->owningAlias; } /** * Returns true, if relation name refers to the referenced side * * @param string $relationName * @return bool */ public function isReferencedSide($relationName) { return $relationName === $this->refAlias; } /** * Gets referencing owning relation name * * @return string */ public function getOwningAlias() { return $this->owningAlias; } /** * Gets reference owning table name * * @return string */ public function getOwningTable() { return $this->owningTable; } /** * @return string */ public function getOwningField() { return $this->owningField; } /** * @return string */ public function getReferencedAlias() { return $this->refAlias; } /** * @return string */ public function getReferencedTable() { return $this->refTable; } /** * @return string */ public function getReferencedField() { return $this->refField; } /** * @return string */ public function getOnDelete() { return $this->onDelete; } /** * @return string */ public function getOnUpdate() { return $this->onUpdate; } /** * Gets join table name * * @param string $relationName * @return string */ public function getJoinTableName($relationName) { if ($relationName === $this->owningAlias) { return $this->owningTable; } return $this->refTable; } /** * Gets join table * * @param \Dive\RecordManager $rm * @param string $relationName * @return \Dive\Table */ public function getJoinTable(RecordManager $rm, $relationName) { $joinTableName = $this->getJoinTableName($relationName); return $rm->getTable($joinTableName); } /** * Gets join condition * * @param string $relationAlias * @param string $refTabAlias * @param string $tabAlias * @param string $quote * @return string */ public function getJoinOnCondition($relationAlias, $refTabAlias, $tabAlias, $quote = '') { $owningField = $quote . $this->owningField . $quote; $refField = $quote . $this->refField . $quote; $tabAliasQuoted = $quote . $refTabAlias . $quote; $refAliasQuoted = $quote . $tabAlias . $quote; if ($this->isOwningSide($relationAlias)) { $refField = $tabAliasQuoted . '.' . $refField; $owningField = $refAliasQuoted . '.' . $owningField; } else { $refField = $refAliasQuoted . '.' . $refField; $owningField = $tabAliasQuoted . '.' . $owningField; } return $owningField . ' = ' . $refField; } /** * Gets record referenced identifiers * * @param Record $record * @param string $relationName * @return bool|null|array|string * false: reference has not been loaded, yet * null: null-reference / not related * array: one-to-many related ids * string: referenced id */ public function <API key>(Record $record, $relationName) { $id = $record->getInternalId(); $isReferenceSide = $this->isReferencedSide($relationName); if ($isReferenceSide) { $owningOid = $record->getOid(); if ($this->map->hasFieldMapping($owningOid)) { $refOid = $this->map->getFieldMapping($owningOid); if ($refOid) { return Record::NEW_RECORD_ID_MARK . $refOid; } } return $record->get($this->owningField); } if (!$this->map->isReferenced($id) && !$this->map->hasNullReference($id)) { return false; } return $this->map->getOwning($id); } /** * Gets query for loading related records * * @param Record $record * @param string $relationName * @param array $identifiers * @return \Dive\Query\Query */ private function getReferenceQuery(Record $record, $relationName, array $identifiers = array()) { if (empty($identifiers)) { $identifiers = array($record-><API key>()); } $table = $record->getTable(); $rm = $table->getRecordManager(); $relatedTable = $this->getJoinTable($rm, $relationName); $query = $relatedTable->createQuery('a'); $query->distinct(); if ($this->isReferencedSide($relationName)) { $expression = $table-><API key>('b'); $query ->leftJoin("a.$this->owningAlias b") ->whereIn($expression, $identifiers); } else { $connection = $table->getConnection(); $expression = $connection->quoteIdentifier("a.$this->owningField"); $query->whereIn($expression, $identifiers); if ($this->isOneToMany() && $this->orderBy) { if (false !== ($pos = strpos($this->orderBy, '.'))) { list($<API key>, $orderByField) = explode('.', $this->orderBy); $query ->leftJoin("a.$<API key> b") ->orderBy("b.$orderByField"); } else if ($relatedTable->hasField($this->orderBy)) { $query->orderBy("a.$this->orderBy"); } } } return $query; } /** * Gets reference for given record * * @param Record $record * @param string $relationName * @return null|RecordCollection|Record[]|Record */ public function getReferenceFor(Record $record, $relationName) { $related = $this-><API key>($record, $relationName); if ($related !== false) { return $related; } $this->loadReferenceFor($record, $relationName); return $this-><API key>($record, $relationName); } /** * TODO $related should we allow an array of records for OneToMany-Relations, too?? * * Sets reference for given record * * @param Record $record * @param string $relationName * @param null|RecordCollection|Record[]|Record $related * @throws RelationException */ public function setReferenceFor(Record $record, $relationName, $related) { // one-to-one/one-to-many (referenced side) if ($this->isReferencedSide($relationName)) { $this-><API key>($relationName, $related); $this->map-><API key>($record, $related); } // one-to-many (owning side) else if ($this->isOneToMany()) { $this-><API key>($relationName, $related); $this->map-><API key>($record, $related); } // one-to-one (owning side) else { $this-><API key>($relationName, $related); $this->map-><API key>($related, $record); } } /** * Checks, if record has loaded references, or not * * @param Record $record * @param string $relationName * @return bool */ public function <API key>(Record $record, $relationName) { $isOwningSide = $this->isOwningSide($relationName); if (!$isOwningSide && $this->map->hasFieldMapping($record->getOid())) { return true; } if ($isOwningSide && $this->isOneToMany()) { $reference = $this->map-><API key>($record->getOid()); if (!$reference) { $refId = $this-><API key>($record, $relationName); if (!empty($refId)) { return true; } } else if (!$reference->isEmpty()) { return true; } } else { $refId = $this-><API key>($record, $relationName); if (!$refId) { return false; } $rm = $record->getTable()->getRecordManager(); $refTable = $this->getJoinTable($rm, $relationName); if (is_string($refId) && $refTable->isInRepository($refId)) { return true; } } return false; } /** * @param Record $record * @param string $relationName * @return array * @throws RelationException */ public function <API key>(Record $record, $relationName) { $isReferencedSide = $this->isReferencedSide($relationName); if ($isReferencedSide) { $owningField = $this->getOwningField(); if ($record->isFieldModified($owningField)) { return array($record-><API key>($owningField)); } return array($record->get($owningField)); } $query = $this->getReferenceQuery($record, $relationName, array($record->getInternalId())); $<API key> = $query->fetchScalars(); if ($this->isOneToOne()) { $moreThanOne = isset($<API key>[1]); if ($moreThanOne) { throw new RelationException("One-to-one relation has returned more than one result!"); } } return $<API key>; } /** * @param Record $record * @param string $relationName * @return bool|RecordCollection|Record|Record[]|null */ private function <API key>(Record $record, $relationName) { // is reference expected as collection if ($this->isOwningSide($relationName) && $this->isOneToMany()) { $reference = $this->map-><API key>($record->getOid()); if (!$reference) { $reference = $this->map-><API key>($record); } return $reference; } // is reference expected as record $refId = $this-><API key>($record, $relationName); // is a NULL-reference if (null === $refId) { return null; } $rm = $record->getTable()->getRecordManager(); $refTable = $this->getJoinTable($rm, $relationName); if (is_string($refId) && $refTable->isInRepository($refId)) { return $refTable->getFromRepository($refId); } return false; } /** * @TODO Remove result collections, use repository records instead * Loads reference for a given record * * @param Record $record * @param string $relationName */ private function loadReferenceFor(Record $record, $relationName) { $recordCollection = $record->getResultCollection(); if (!$recordCollection) { $recordCollection = new RecordCollection($record->getTable()); $recordCollection->add($record); } $relatedCollection = null; if ($record->exists()) { $identifiers = $recordCollection->getIdentifiers(); $query = $this->getReferenceQuery($record, $relationName, $identifiers); /** @var \Dive\Record[]|\Dive\Collection\RecordCollection $relatedCollection */ $relatedCollection = $query->execute(RecordManager::<API key>); } else if ($this->isReferencedSide($relationName)){ $relatedCollection = $this->loadReferenceSide($record, $relationName); } if ($relatedCollection === null) { $table = $record->getTable(); $rm = $table->getRecordManager(); $relatedTable = $this->getJoinTable($rm, $relationName); $relatedCollection = new RecordCollection($relatedTable); } // updates reference map between both collections $isOwningSide = $this->isOwningSide($relationName); $ownerCollection = $isOwningSide ? $relatedCollection : $recordCollection; $<API key> = $isOwningSide ? $recordCollection : $relatedCollection; if ($isOwningSide || $this->isOneToOne()) { $this->map-><API key>($ownerCollection, $<API key>); if ($isOwningSide && !$this->isOneToOne()) { $id = $record->getInternalId(); $this->map->setReferenceLoaded($id); } } } /** * @param Record $record * @param string $relationName * @return array */ private function loadReferenceSide(Record $record, $relationName) { $refId = $this-><API key>($record, $relationName); if ($refId) { $table = $record->getTable(); $rm = $table->getRecordManager(); $relatedTable = $this->getJoinTable($rm, $relationName); $connection = $rm->getConnection(); $expression = $connection->quoteIdentifier("a.$this->refField"); $query = $relatedTable->createQuery('a') ->where("$expression = ?", $refId); /** @var \Dive\Record[]|\Dive\Collection\RecordCollection $relatedCollection */ return $query->execute(RecordManager::<API key>); } return null; } /** * Gets referenced record (for owning field) * * @param Record $record * @param string $relationName * @throws RelationException * @return Record|null */ public function getRelatedRecord(Record $record, $relationName) { if ($this->isReferencedSide($relationName)) { return $this->map-><API key>($record); } if ($this->isOneToOne()) { return $this->map-><API key>($record); } throw new RelationException("Relation '$relationName' does not expected a record as reference!"); } /** * @param Record $owningRecord * @param string $newIdentifier * @param string $oldIdentifier */ public function <API key>(Record $owningRecord, $newIdentifier, $oldIdentifier) { if ($this->map-><API key>($newIdentifier, $oldIdentifier, $owningRecord)) { return; } if ($newIdentifier != $oldIdentifier) { // remove old reference $this->map-><API key>($owningRecord, $oldIdentifier); // setting new reference $this->map-><API key>($owningRecord, $newIdentifier); } } /** * @param Record $record * @param string $relationName */ public function clearReferenceFor(Record $record, $relationName) { $this->map-><API key>($record, $relationName); } /** * Updates record references for given owning record and given referenced record * * @param Record $owningRecord * @param Record $referencedRecord */ public function <API key>(Record $owningRecord = null, Record $referencedRecord = null) { $this->map-><API key>($owningRecord, $referencedRecord); } /** * @param Record $referencedRecord * @param string $relationName * @param string $newIdentifier * @param string $oldIdentifier */ public function <API key>(Record $referencedRecord, $relationName, $newIdentifier, $oldIdentifier) { if ($this->isOwningSide($relationName)) { $this->map-><API key>($newIdentifier, $oldIdentifier); } else { $this->map-><API key>($newIdentifier, $oldIdentifier, $referencedRecord); } } /** * Clears references */ public function clearReferences() { $this->map->clear(); } /** * @param string $relationName * @param Record|null $reference * @throws RelationException */ private function <API key>($relationName, $reference) { if ($reference !== null) { if (!($reference instanceof Record)) { throw new RelationException( "Reference for relation '$relationName' must be NULL or an instance of \\Dive\\Record!" . " Got: " . (is_object($reference) ? get_class($reference) : gettype($reference)) ); } $joinTableName = $this->getJoinTableName($relationName); if ($reference->getTable()->getTableName() !== $joinTableName) { throw new RelationException( "Reference for relation '$relationName' must be an record of table '$joinTableName'!" ); } } } /** * @param string $relationName * @param Record|null $reference * @throws RelationException */ private function <API key>($relationName, $reference) { if (!($reference instanceof RecordCollection)) { throw new RelationException( "Reference for relation '$relationName' must be an instance of \\Dive\\Collection\\RecordCollection!" ); } $joinTableName = $this->getJoinTableName($relationName); if ($reference->getTable()->getTableName() !== $joinTableName) { throw new RelationException( "RecordCollection for relation '$relationName' must be a collection for table '$joinTableName'!" ); } } /** * @param Record $record * @param string $relationName * @return null|Record|Record[]|RecordCollection */ public function <API key>(Record $record, $relationName) { $referenceIds = $this-><API key>($record, $relationName); if (!$referenceIds) { return array(); } $query = $this->getReferenceQuery($record, $relationName); return $query->execute(); } }
# Ebets Ebets is a decentralized betting platform, built using Ethereum, where you can create and join bets. Ebets focuses on sports and e-sports matches. You can access it in a convenient way at: [ebets.ch](https://ebets.ch) or at ipfs: ## Running You're right! To be fully decentralized you should be able to run it yourself, It is supposed to be really simple: cd front/ npm install npm start Open `http://127.0.0.1:8080/` and you're ready to use the system. ## Basics: The contract roles are: 1. Ebets 2. User 3. Arbiter # Ebets Ebets is used mainly to maintain the bets organized and indexed. We have a small fixed fee for this service, 1% of the losing side. Think of Ebets as a bets deposit: it will keep track of every bet created in the system, and index them accordingly. Ebets' power over a bet is very limited and it can only: * Feature and unfeature a bet * Change the bet's category # User Users can: * Create bets * Bet on existing matches * Call the arbiter * Collect their rewards A user can create bets in the system, and those bets appear in the *unfeatured* section. A user can also bet on an existing match and collect the rewards of the bet. # Arbiter The arbiter plays a major role in our system, make sure you understand how it works. An arbiter is responsible to decide the match's outcome. The arbiter itself is also a contract. For the first test release, we have a **Monarch** arbiter that decides the bet outcome, but don't worry, you can trust this monarch (said every tyrant). Our goal with the Monarch is just to bootstrap our community, as we encourage smart contract developers and the community to follow our interface for developing arbiters. We will later create a nice UI so that non-programmers can also develop arbiters. Arbiters are formed usually by a collection of trustworthy people, and some rules should exist for them to cast the outcome. For example, an arbiter can be composed by 3 members, where if 2 of them act correctly, the match's outcome is decided. In that way arbiters can minimize the chance of *failing*. ## What if an arbiter decides wrongly / doesn't decide? Arbiters are encouraged to have a higher instance, like a court of appeals in legal terms. That court of appeals could be evoked to solve a dispute when arbiters collude to lie about an outcome. There should also be a *slashing* mechanism to punish the faulty arbiters. We are still working on these concepts before any implementation follows. ## What if the higher instance colludes? This is a recursive problem, we don't think there is an easy solution for that. We hope that in higher instances the stakes are too high, and a collusion will do more damage than any outcome it can provide. We hope that every bet will have their own *trustworthy court*. But this is for the future! Right now we should all follow the Monarch, or whatever arbiter you can come up with. ## Workflow Bets represent a match between two teams, let's call them Team A and Team B. There can be, in principle, 3 outcomes: 1. Team A won 2. Team B won 3. Draw Bets are accepted until the match begins. When the match begins, bets are no longer accepted. When the match ends, any user can invoke the Arbiter, and that call will make a proposal to the arbiter to decide. The arbiter then, must decide the outcome until a fixed deadline. If the arbiter doesn't decide until then, anyone can make the bet a Draw. Once the result of the match is decided, the participants that have bet on the winning team can withdraw their rewards. The reward consists of the original bet plus a percentage of his/her stakes multiplied by the loser's side pool, minus the 1% tax. Let's say Alice bets 1 ether on team A and Bob 1 ether on team B. Team A wins. When Alice withdraws, she will have 1 ether + 100% * (1-0.01) = 1.99 ether. There is also a deadline when the bet can be self-destructed which is is encouraged to be long (couple of months). When the bet is self-destroyed, any ether it holds is transferred to Ebets. # Governance This is a tool for us all to use. We encourage the community to submit PRs to our repository and make suggestions in the Issues page. # TESTNET The contracts are deployed in the **Kovan** testnet, so make sure you don't send any ether to the main network! The system is unstable, so do not rely on the bets to be there in the following day, this is for testing only right now! # TODOs - [ ] Support ERC20 tokens - [ ] Make UI to create arbiters - [ ] Option to create no-fee private bets - [ ] Index bets by category in Ebets events - [ ] Fix my bets - [ ] Fix images for bets - [ ] Better format BigNumber - [ ] Fix "Win", sum with already bet by account, edit positioning - [ ] Paginate bets
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using Griffin.Networking.Http.Specification; namespace Griffin.Networking.Http.Implementation { public class <API key><T> : <API key><T> where T : IHttpCookie { List<T> _items = new List<T>(); <summary> Returns an enumerator that iterates through the collection. </summary> <returns> A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. </returns> <filterpriority>1</filterpriority> public IEnumerator<T> GetEnumerator() { return _items.GetEnumerator(); } <summary> Returns an enumerator that iterates through a collection. </summary> <returns> An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. </returns> <filterpriority>2</filterpriority> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } <summary> Gets the count of cookies in the collection. </summary> public int Count { get { return _items.Count; } } <summary> Gets the cookie of a given identifier (<c>null</c> if not existing). </summary> public T this[string id] { get { return _items.FirstOrDefault(x => x.Name.Equals(id, StringComparison.OrdinalIgnoreCase)); } set { _items.Add(value); } } <summary> Remove all cookies. </summary> public void Clear() { _items.Clear(); } <summary> Remove a cookie from the collection. </summary> <param name="cookieName">Name of cookie.</param> public void Remove(string cookieName) { _items.RemoveAll(x => x.Name.Equals(cookieName, StringComparison.OrdinalIgnoreCase)); } } }
Spree::Core::Engine.routes.draw do devise_for :spree_user, :class_name => Spree::User, :skip => [:unlocks, :sessions, :registrations, :passwords], :controllers => { :omniauth_callbacks => "spree/omniauth_callbacks" }, :path => Spree::SocialConfig[:path_prefix] resources :<API key> get 'account' => 'users#show', :as => 'user_root' namespace :admin do resources :<API key> end end
<?php namespace Core\Validator; require_once 'PHPUnit/Framework.php'; require_once __DIR__ . '/../../../bootstrap.php'; use \Mockery as m; /** * Test class for Params Validator. */ class ParamsTest extends \CMSTestCase { protected function tearDown() { m::close(); } public function testValidator() { $route = m::mock(); $route->shouldReceive('getId')->andReturn('id'); $pageRouteById = m::mock(); $pageRouteById->shouldReceive('getRoute')->andReturn($route); $repository = m::mock(); $repository->shouldReceive('findOneBy')->andReturn($pageRouteById); $em = m::mock('Doctrine\ORM\EntityManager'); $em->shouldReceive('getRepository')->andReturn($repository); $em->shouldReceive('getReference')->andReturn($pageRouteById); $validator = new \Core\Validator\Params(); $validator->setEntityManager($em); $string = 'param1-_'; $this->assertEquals(true, $validator->isValid($string)); $string = 'param1 '; $this->assertEquals(false, $validator->isValid($string)); } }
<?php namespace app\modules\admin\assets; use yii\web\AssetBundle; /** * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class AppAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [ 'css/site.css','css/<API key>.flags.css', ]; public $js = [ ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; }
#pragma once #include <string> #include <Poco/SharedPtr.h> namespace BeeeOn { class QueryLoader { public: typedef Poco::SharedPtr<QueryLoader> Ptr; QueryLoader(); virtual ~QueryLoader(); virtual std::string find(const std::string &key) const = 0; }; }
layout: post title: Building GitTrophy date: 2017-08-11 07:38:51 tags: aws lambda react dataviz github javascript python s3 web I've been working on a site for the past month that generates 3D models from Github's contribution graphs. After a month of work, it's complete! So, I'm happy to announce [GitTrophy](https://gittrophy.com). It's pretty slick: type in a Github user or repo name, and you'll get a 3D preview of the contribution model. I 3D printed my chart from 2016, and it turned out pretty well.<!--break--> {% include blog_image.html url="/img/<API key>/demo.gif" description="Demo of GitTrophy" %} ## Inspiration Looking at my [Github profile](https: My initial idea was to have some type of generator to create 3d models of Github contributions. I wasn't sure if I'd be able to hack it to work in a browser (though that was the ultimate goal), or if it'd be just a script. The design for the models was largely inspired by Isometric Contributions, and the resulting web page was inspired heavily by Commit Print. ## Initial Prototype My initial thought was that model creation would *have* to be done server-side. After looking at the landscape of Python 3d modeling frameworks, I was left pretty disappointed. The only tool that seemed to fit all my requirements -- scriptable modeling, output to commonly accepted file formats, ability to run headless, and ability to apply colors/textures -- was [Blender](http: Model Generation I tooled around with creating a Blender Python script (against [bpy](https://docs.blender.org/api/<API key>/info_overview.html)), and came up with something that could take a list of days and colors, and transform it into something that looked like the Github contributions chart. {% include blog_image.html url="/img/<API key>/contributions.png" description="The Github Contributions Chart" %} Then, I wrote a simple Python module ([<API key>](https://github.com/bcongdon/<API key>)) to help scraping a user's contribution history.[^2] Combining these two components, I had something that worked "on my machine" for generating contribution models. I was elated! It took me about a week to get this prototype up and running, but when I saw the first model using real contribution data, I knew I was on to something pretty neat. {% include blog_image.html url="/img/<API key>/blender.png" description="Example Blender Preview of Initial Models" %} Backend The other design constraint I imposed on myself is that rendering needed to be done quickly and cheaply. [AWS Lambda](https://aws.amazon.com/lambda/) was my platform of choice -- as it is for many of my projects. Using a serverless platform allows projects persist online for longer, because their hosting costs are usage based -- you only pay when someone uses it, instead of having fixed server costs. However, it is a bit of a pain to get anything that requires binaries or libraries to run in Lambda. I spent about a week getting Blender to compile statically into a binary that could be shipped off to lambda. This was **_not fun_**. The fruit of this work was [bpy_lambda](https://github.com/bcongdon/bpy_lambda), which should allow anyone to use Blender inside Lambda with minimal effort. I put together a Lambda function that scraped Github contributions, and spat out a X3D model. It worked! The only problem was that it too >8 seconds per model *just* to generate -- too slow. Another hurdle was filesize. Rendered models -- even compressed -- were upwards of 800Kb. Long request times and large response bodies are two things I wanted to avoid in the final version. ## Current Architecture After deciding I needed to use something other than Blender, I discovered Three.js. Three.js is a really awesome projects: it's a really solid 3D Javascript library that sits on top of WebGL. I decided to switch around my design to do model generation in the Frontend, and have the Backend only scrape/serve Github data. Backend In the final version of the site, I kept the Lambda backend, but used it only for scraping Github contribution data. The Lambda functions are managed by [Zappa](https://github.com/Miserlou/Zappa/). I've used Zappa in a bunch of previous projects -- it's a really awesome project, and allows you to write normal web apps (Flask, Django, etc) and deploy them in a serverless context. # Scraping Repo Contribution Data One challenge with the backend was scraping contribution data for Github repositories. Users are easy -- you can just grab the day-aggregated statistics from their profile page. Repos are harder. The Github API doesn't expose these stats in a meaningful way. After mulling over this problem for a while, and consulting with [Aaron Francis](https://twitter.com/aarondfrancis) (who created CommmitPrint), I decided to get repo statistics by using git to clone the repo, and then processing the git log. This introduced another headache of getting a binary to compile for lambda -- this time, with `git`. Again, I packaged this up in a Python module for others to use: [git_lambda](https://github.com/bcongdon/git_lambda). To call `git` within the backend API request, I used kennethreitz's [delegator](https://github.com/kennethreitz/delegator.py). It provides a nice, clean interface to the `subprocess` module. For instance, here is how I get the logs from git: python log_cmd = delegator.run( ' '.join(['git', 'log', '--pretty=format:"%ad"', '--date=short']) ) log_lines = log_cmd.out.split('\n') Unfortunately, cloning git repos -- especially large or popular ones -- can be quite slow. I was able to improve performance slightly by doing a [bare](https://git-scm.com/docs/git-clone # S3 Repo Data Cache The `git clone` optimizations brought down the time-to-scrape significantly, but there was still room for improvement. To further reduce API request times, I cache the results of each repo I scraped in S3. GitTrophy data is collected in 1-year windows, so I cache indefinitely the repo data from previous years, and have a 1 day cache retention period on repo data from the current year. Assuming that larger repos likely tend to be more popular (and vice-versa), I expect the hit rate for this cached data to be rather high. I also pre-fetched the [top 1000 most popular repositories](http://github-rank.com/star) in S3, just to cover-the-bases of really popular repos. {% include blog_image.html url="/img/<API key>/aws.png" description="GitTrophy AWS Setup" %} Frontend The GitTrophy frontend uses React + Redux for the site logic, and [<API key>](https://github.com/toxicFork/<API key>) as the Three.js <-> React interface. # Model Generation Using <API key>, it was pretty simple to generate the models. All the 3D elements use normal React semantics -- each cube and material is just a React component. I did have to mess around with Three.js's rendering settings to get something that looked decent. Enabling anti-aliasing, raising material roughness, and setting material shading to `flat` went a long way to making the models look better in the preview window. Each day bar in the chart is rendered like this: <mesh key={idx} position={pos}> <boxGeometry width={1 / 7} height={height} depth={1 / 7} /> <<API key> color={new THREE.Color(BAR_COLORS[day.level])} roughness={ROUGHNESS} shading={THREE.FlatShading} /> </mesh> I really like <API key>; it encourages functional, declarative design-patterns that work really well with React. The rest of the model-generation logic is pretty simple: It's just a matter of transforming and positioning cubes, and adding a label to the model using Three.js' [TextGeometry](https://threejs.org/docs/index.html#api/geometries/TextGeometry). # Model Exports Exporting the models was the biggest hurdle of switching from Blender to Three.js. Blender has native X3D support, which made it trivial to export models. Three.js does not. Fortunately, I'd earlier done some work on a [Three.js X3D loader](https://github.com/jonaskello/three-x3d-loader/pull/6), so I was somewhat familiar with the format. I ended up writing a simple X3D exporter for Three.js. I don't think it's quite general enough to be split out into a separate package (although, it's something I'm considering), but it does the job! X3D is a surprisingly simple XML-based format, so writing an exporter wasn't that difficult. (The main challenge was actually finding the spec for X3D, because all the online documentation is rather terse) I finally used a recursive tree-traversal _in real life_ while writing the exporter, so... that was fun. Other than that, the site is just a normal React app. I used `react-semantic-ui` for the UI components -- it's my current favorite React UI component library. [SemanticUI](https://semantic-ui.com/) looks clean, has a wide range of components, and scales nicely -- making it easy to produce a mobile-ready version of GitTrophy. Conclusion In the end, I'm really happy with how the site turned out. It feels responsive, and pulls data down relatively quickly. I also wrangled with Three.js enough to have the models look decent in the preview, and am happy with how the preview "look and feel". I'm also quite happy with how the models turned out. I got my 2016 Github contributions printed by Shapeways; it's a really cool desk ornament. I've had very minimal experience with 3D printing in the past, so I was glad that the print went as well as it did. {% include blog_image.html url="/img/<API key>/printed.jpg" description="Printed 3d Model of My 2016 Github Contributions" %} {% include blog_image.html url="/img/<API key>/printed_with_floss.jpg" description="Box of Floss for Scale" %} Any questions? I'm on Twitter as [@BenRCongdon](https: [^1]: I'm aware that there's been some controversy in the past months about contribution graphs being [harmful](https://github.com/isaacs/github/issues/627) to contributors. I agree that there's merit to these arguments. But, for the time being, I still enjoy the "gamification" of making contributions. [^2]: Unfortunately, Github doesn't provide a public API that provides this data, so I used BeautifulSoup to scrape the SVG data of the actual contributions chart. [^3]: I'm a bit disappointed that `git clone` doesn't have a `--shallow-until` argument, but I can see that it would have limited usefulness outside of projects like this.
#include "inmost_mesh.h" #if defined(USE_MESH) #define _m0(x) (x & 0x7FF) #define _m1(x) (x >> 11 & 0x7FF) #define _m2(x) (x >> 22 ) namespace INMOST { inline static void crossproduct(const Storage::real vecin1[3],const Storage::real vecin2[3], Storage::real vecout[3]) { vecout[0] = vecin1[1]*vecin2[2] - vecin1[2]*vecin2[1]; vecout[1] = vecin1[2]*vecin2[0] - vecin1[0]*vecin2[2]; vecout[2] = vecin1[0]*vecin2[1] - vecin1[1]*vecin2[0]; } inline static Storage::real dotproduct(const Storage::real * vecin1, const Storage::real * vecin2) { return vecin1[0]*vecin2[0]+vecin1[1]*vecin2[1]+vecin1[2]*vecin2[2]; } template<typename bbox_type> inline int SearchKDTree::bbox_point(const Storage::real p[3], const bbox_type bbox[6]) { for(int i = 0; i < 3; i++) { if( p[i] < bbox[i*2]-1.0e-3 || p[i] > bbox[i*2+1]+1.0e-3 ) return 0; } return 1; } template<typename bbox_type> inline int SearchKDTree::bbox_point_print(const Storage::real p[3], const bbox_type bbox[6], std::ostream & sout) { for (int i = 0; i < 3; i++) { if (p[i] < bbox[i * 2] - 1.0e-3 || p[i] > bbox[i * 2 + 1] + 1.0e-3) { sout << "fail on " << i << " "; if (p[i] < bbox[i * 2] - 1.0e-3) sout << p[i] << " is less then " << bbox[i * 2] - 1.0e-3 << "(" << bbox[i * 2] << ")"; if (p[i] > bbox[i * 2 + 1] + 1.0e-3) sout << p[i] << " is greater then " << bbox[i * 2 + 1] + 1.0e-3 << "(" << bbox[i * 2 + 1] << ")"; sout << std::endl; return 0; } } sout << "all ok!" << std::endl; return 1; } template<typename bbox_type> inline void SearchKDTree::bbox_closest_point(const Storage::real p[3], const bbox_type bbox[6], Storage::real pout[3]) { for (int i = 0; i < 3; i++) { if (p[i] < bbox[i * 2] ) pout[i] = bbox[i * 2]; else if (p[i] > bbox[i * 2 + 1]) pout[i] = bbox[i * 2 + 1]; else pout[i] = p[i]; } return; } template<typename bbox_type> inline int SearchKDTree::bbox_sphere(const Storage::real p[3], Storage::real r, const bbox_type bbox[6]) { Storage::real pb[3], d; bbox_closest_point(p, bbox, pb); d = sqrt((pb[0] - p[0]) * (pb[0] - p[0]) + (pb[1] - p[1]) * (pb[1] - p[1]) + (pb[2] - p[2]) * (pb[2] - p[2])); return d <= r ? 1 : 0; } inline Storage::real SearchKDTree::segment_distance(const Storage::real a[3], const Storage::real b[3], const Storage::real p[3]) { Storage::real pout[3]; Storage::real v[3] = { b[0] - a[0],b[1] - a[1],b[2] - a[2] }; Storage::real d = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; Storage::real t = (v[0] * (p[0] - a[0]) + v[1] * (p[1] - a[1]) + v[2] * (p[2] - a[2])) / d; if (t >= 0.0 && t <= 1.0) { pout[0] = a[0] + t * v[0]; pout[1] = a[1] + t * v[1]; pout[2] = a[2] + t * v[2]; } else if (t < 0.0) { pout[0] = a[0]; pout[1] = a[1]; pout[2] = a[2]; } else { pout[0] = b[0]; pout[1] = b[1]; pout[2] = b[2]; } return sqrt((pout[0] - p[0]) * (pout[0] - p[0]) + (pout[1] - p[1]) * (pout[1] - p[1]) + (pout[2] - p[2]) * (pout[2] - p[2])); } inline Storage::real SearchKDTree::triangle_distance(const Storage::real a[3], const Storage::real b[3], const Storage::real c[3], const Storage::real p[3]) { Storage::real pout[3]; Storage::real n[3], d, t, q1[3], q2[3], q3[3], q12, q23, q13; n[0] = (b[1] - a[1]) * (c[2] - a[2]) - (b[2] - a[2]) * (c[1] - a[1]); n[1] = (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2]); n[2] = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); d = sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); if (d) { n[0] /= d; n[1] /= d; n[2] /= d; } t = (a[0] - p[0]) * n[0] + (a[1] - p[1]) * n[1] + (a[2] - p[2]) * n[2]; pout[0] = p[0] + t * n[0]; pout[1] = p[1] + t * n[1]; pout[2] = p[2] + t * n[2]; q1[0] = (pout[1] - a[1]) * (pout[2] - b[2]) - (pout[1] - b[1]) * (pout[2] - a[2]); q1[1] = (pout[2] - a[2]) * (pout[0] - b[0]) - (pout[2] - b[2]) * (pout[0] - a[0]); q1[2] = (pout[0] - a[0]) * (pout[1] - b[1]) - (pout[0] - b[0]) * (pout[1] - a[1]); q2[0] = (pout[1] - b[1]) * (pout[2] - c[2]) - (pout[1] - c[1]) * (pout[2] - b[2]); q2[1] = (pout[2] - b[2]) * (pout[0] - c[0]) - (pout[2] - c[2]) * (pout[0] - b[0]); q2[2] = (pout[0] - b[0]) * (pout[1] - c[1]) - (pout[0] - c[0]) * (pout[1] - b[1]); q3[0] = (pout[1] - c[1]) * (pout[2] - a[2]) - (pout[1] - a[1]) * (pout[2] - c[2]); q3[1] = (pout[2] - c[2]) * (pout[0] - a[0]) - (pout[2] - a[2]) * (pout[0] - c[0]); q3[2] = (pout[0] - c[0]) * (pout[1] - a[1]) - (pout[0] - a[0]) * (pout[1] - c[1]); q12 = q1[0] * q2[0] + q1[1] * q2[1] + q1[2] * q2[2]; q23 = q2[0] * q3[0] + q2[1] * q3[1] + q2[2] * q3[2]; q13 = q1[0] * q3[0] + q1[1] * q3[1] + q1[2] * q3[2]; if (q12 >= 0 && q23 >= 0 && q13 >= 0) return fabs(t); Storage::real dmin = segment_distance(a, b, p); dmin = std::min(dmin, segment_distance(b, c, p)); dmin = std::min(dmin, segment_distance(c, a, p)); return dmin; } int SearchKDTree::cmpElements0(const void * a,const void * b) { const entry * ea = ((const entry *)a); const entry * eb = ((const entry *)b); float ad = ea->xyz[0]; float bd = eb->xyz[0]; return (ad > bd) - (ad < bd); } int SearchKDTree::cmpElements1(const void * a,const void * b) { const entry * ea = ((const entry *)a); const entry * eb = ((const entry *)b); float ad = ea->xyz[1]; float bd = eb->xyz[1]; return (ad > bd) - (ad < bd); } int SearchKDTree::cmpElements2(const void * a,const void * b) { const entry * ea = ((const entry *)a); const entry * eb = ((const entry *)b); float ad = ea->xyz[2]; float bd = eb->xyz[2]; return (ad > bd) - (ad < bd); } inline unsigned int SearchKDTree::flip(const unsigned int * fp) { unsigned int mask = -((int)(*fp >> 31)) | 0x80000000; return *fp ^ mask; } void SearchKDTree::radix_sort(int dim, struct entry * temp) { unsigned int i; const unsigned int kHist = 2048; unsigned int b0[kHist * 3]; unsigned int *b1 = b0 + kHist; unsigned int *b2 = b1 + kHist; memset(b0,0,sizeof(unsigned int)*kHist*3); for (i = 0; i < size; i++) { unsigned int fi = flip((unsigned int *)&set[i].xyz[dim]); ++b0[_m0(fi)]; ++b1[_m1(fi)]; ++b2[_m2(fi)]; } { unsigned int sum0 = 0, sum1 = 0, sum2 = 0; for (i = 0; i < kHist; i++) { b0[kHist-1] = b0[i] + sum0; b0[i] = sum0 - 1; sum0 = b0[kHist-1]; b1[kHist-1] = b1[i] + sum1; b1[i] = sum1 - 1; sum1 = b1[kHist-1]; b2[kHist-1] = b2[i] + sum2; b2[i] = sum2 - 1; sum2 = b2[kHist-1]; } } for (i = 0; i < size; i++) temp[++b0[_m0(flip((unsigned int *)&set[i].xyz[dim]))]] = set[i]; for (i = 0; i < size; i++) set[++b1[_m1(flip((unsigned int *)&temp[i].xyz[dim]))]] = temp[i]; for (i = 0; i < size; i++) temp[++b2[_m2(flip((unsigned int *)&set[i].xyz[dim]))]] = set[i]; for (i = 0; i < size; i++) set[i] = temp[i]; } void SearchKDTree::kdtree_build(int dim, int & done, int total, struct entry * temp) { if( size > 1 ) { if( size > 128 ) radix_sort(dim,temp); else switch(dim) { case 0: qsort(set,size,sizeof(entry),cmpElements0);break; case 1: qsort(set,size,sizeof(entry),cmpElements1);break; case 2: qsort(set,size,sizeof(entry),cmpElements2);break; } children = static_cast<SearchKDTree *>(malloc(sizeof(SearchKDTree)*2));//new kdtree[2]; children[0].children = NULL; children[0].set = set; children[0].size = size/2; children[0].m = m; children[1].children = NULL; children[1].set = set+size/2; children[1].size = size - size/2; children[1].m = m; children[0].kdtree_build((dim+1)%3,done,total,temp); children[1].kdtree_build((dim+1)%3,done,total,temp); for(int k = 0; k < 3; k++) { bbox[0+2*k] = std::min<float>(children[0].bbox[0+2*k],children[1].bbox[0+2*k]); bbox[1+2*k] = std::max<float>(children[0].bbox[1+2*k],children[1].bbox[1+2*k]); } } else { assert(size == 1); { bool checkm = false, invm = false; if( m->HideMarker() ) { checkm = true; if( m->GetMarker(set[0].e,m->HideMarker()) ) invm = true; } std::vector<HandleType> nodes; if (<API key>(set[0].e) == CELL) { if (m->HighConnTag().isDefined(CELL)) { Element::adj_type& cnodes = m->HighConn(set[0].e); nodes.insert(nodes.end(), cnodes.begin(), cnodes.end()); } else { MarkerType mrk = m->CreatePrivateMarker(); Element::adj_type& faces = m->LowConn(set[0].e); for (unsigned k = 0; k < faces.size(); ++k) { Element::adj_type& fedges = m->LowConn(faces[k]); for (unsigned q = 0; q < fedges.size(); ++q) { Element::adj_type& enodes = m->LowConn(fedges[q]); for (unsigned l = 0; l < enodes.size(); ++l) if (!m->GetPrivateMarker(enodes[l], mrk)) { nodes.push_back(enodes[l]); m->SetPrivateMarker(enodes[l], mrk); } } } if (!nodes.empty()) m-><API key>(&nodes[0], (Storage::enumerator)nodes.size(), mrk); m-><API key>(mrk); } } else if (<API key>(set[0].e) == FACE) { MarkerType mrk = m->CreatePrivateMarker(); Element::adj_type& fedges = m->LowConn(set[0].e); for (unsigned q = 0; q < fedges.size(); ++q) { Element::adj_type& enodes = m->LowConn(fedges[q]); for (unsigned l = 0; l < enodes.size(); ++l) if (!m->GetPrivateMarker(enodes[l], mrk)) { nodes.push_back(enodes[l]); m->SetPrivateMarker(enodes[l], mrk); } } if (!nodes.empty()) m-><API key>(&nodes[0], (Storage::enumerator)nodes.size(), mrk); m-><API key>(mrk); } else { std::cout << "Unsupported element type in kd-tree" << std::endl; throw Impossible; } bbox[0] = bbox[2] = bbox[4] = 1.0e20f; bbox[1] = bbox[3] = bbox[5] = -1.0e20f; if( checkm ) { for(unsigned k = 0; k < nodes.size(); ++k) { bool hidn = m->GetMarker(nodes[k],m->HideMarker()); bool newn = m->GetMarker(nodes[k],m->NewMarker()); if( invm && newn ) continue; if( !invm && hidn ) continue; Storage::real_array coords = m->RealArrayDF(nodes[k],m->CoordsTag());; for(unsigned q = 0; q < coords.size(); q++) { bbox[q*2+0] = std::min<float>(bbox[q*2+0],(float)coords[q]); bbox[q*2+1] = std::max<float>(bbox[q*2+1],(float)coords[q]); } } } else for(unsigned k = 0; k < nodes.size(); ++k) { Storage::real_array coords = m->RealArrayDF(nodes[k],m->CoordsTag());; for(unsigned q = 0; q < coords.size(); q++) { bbox[q*2+0] = std::min<float>(bbox[q*2+0],(float)coords[q]); bbox[q*2+1] = std::max<float>(bbox[q*2+1],(float)coords[q]); } } for(int k = m->GetDimensions(); k < 3; ++k) { bbox[k*2+0] = -1.0e20f; bbox[k*2+1] = 1.0e20f; } } } } Cell SearchKDTree::SubSearchCell(const Storage::real p[3]) const { Cell ret = InvalidCell(); if( size == 1 ) { if( m->HideMarker() && m->GetMarker(set[0].e,m->HideMarker()) ) { m->SwapModification(false); if( cell_point(Cell(m,set[0].e),p) ) ret = Cell(m,set[0].e); m->SwapModification(false); } else { if( cell_point(Cell(m,set[0].e),p) ) ret = Cell(m,set[0].e); } } else { assert(size > 1); if( bbox_point(p,bbox) ) { ret = children[0].SubSearchCell(p); if( !ret.isValid() ) ret = children[1].SubSearchCell(p); } } return ret; } void PrintElement(Element c, std::ostream& sout) { sout << ElementTypeName(c.GetElementType()) << ":" << c.LocalID(); sout << " " << Element::GeometricTypeName(c.GetGeometricType()) << std::endl; sout << " faces: " << c.nbAdjElements(FACE) << " edges: " << c.nbAdjElements(EDGE) << " nodes: " << c.nbAdjElements(NODE) << std::endl; if (c.GetElementType() == CELL) { Storage::real xc[3]; c.Centroid(xc); sout << " closure: " << (c.getAsCell().Closure() ? "true" : "false"); sout << " volume: " << c.getAsCell().Volume(); sout << " x " << xc[0] << " " << xc[1] << " " << xc[2]; sout << std::endl; ElementArray<Face> faces = c.getFaces(); for (ElementArray<Face>::iterator it = faces.begin(); it != faces.end(); ++it) { Storage::real x[3], n[3]; it->Centroid(x); it->UnitNormal(n); sout << "FACE:" << it->LocalID() << " nodes " << it->nbAdjElements(NODE); sout << " closure: " << (it->Closure() ? "true" : "false"); sout << " flat: " << (it->Planarity() ? "true" : "false"); sout << " bnd " << (it->Boundary() ? "true" : "false"); sout << " ornt " << (it-><API key>() ? "true" : "false"); sout << " x " << x[0] << " " << x[1] << " " << x[2] << " n " << n[0] << " " << n[1] << " " << n[2] << " " << " area " << it->Area() << std::endl; } } else if (c.GetElementType() == FACE) { Face it = c.getAsFace(); Storage::real x[3], n[3]; it->Centroid(x); it->UnitNormal(n); sout << " closure: " << (it->Closure() ? "true" : "false"); sout << " flat: " << (it->Planarity() ? "true" : "false"); sout << " bnd " << (it->Boundary() ? "true" : "false"); sout << " ornt " << (it-><API key>() ? "true" : "false"); sout << " x " << x[0] << " " << x[1] << " " << x[2] << " n " << n[0] << " " << n[1] << " " << n[2] << " " << " area " << it->Area() << std::endl; } ElementArray<Node> nodes = c.getNodes(); for (ElementArray<Node>::iterator it = nodes.begin(); it != nodes.end(); ++it) sout << "NODE:" << it->LocalID() << " x " << it->Coords()[0] << " " << it->Coords()[1] << " " << it->Coords()[2] << std::endl; } Cell SearchKDTree::SubSearchCellPrint(const Storage::real p[3], std::ostream & sout) const { Cell ret = InvalidCell(); if (size == 1) { sout << "test cell " << GetHandleID(set[0].e) << std::endl; PrintElement(Cell(m, set[0].e), sout); if (m->HideMarker() && m->GetMarker(set[0].e, m->HideMarker())) { m->SwapModification(false); if (cell_point_print(Cell(m, set[0].e), p,sout)) ret = Cell(m, set[0].e); m->SwapModification(false); } else { if (cell_point_print(Cell(m, set[0].e), p,sout)) ret = Cell(m, set[0].e); } } else { assert(size > 1); if (bbox_point(p, bbox)) { { sout << "point " << p[0] << " " << p[1] << " " << p[2] << " is in bbox "; sout << " x " << bbox[0] << ":" << bbox[1]; sout << " y " << bbox[2] << ":" << bbox[3]; sout << " z " << bbox[4] << ":" << bbox[5]; sout << std::endl; } sout << "try left child" << std::endl; ret = children[0].SubSearchCellPrint(p, sout); sout << "ret " << (ret.isValid() ? ret.LocalID() : -1) << std::endl; if (!ret.isValid()) { sout << "try right child" << std::endl; ret = children[1].SubSearchCellPrint(p, sout); sout << "ret " << (ret.isValid() ? ret.LocalID() : -1) << std::endl; } } else { sout << "point " << p[0] << " " << p[1] << " " << p[2] << " is not in bbox "; sout << " x " << bbox[0] << ":" << bbox[1]; sout << " y " << bbox[2] << ":" << bbox[3]; sout << " z " << bbox[4] << ":" << bbox[5]; sout << std::endl; bbox_point_print(p, bbox, sout); } } return ret; } void SearchKDTree::clear_children() { if( children ) { children[0].clear_children(); children[1].clear_children(); free(children); } } SearchKDTree::SearchKDTree(Mesh * m) : m(m), children(NULL) { size = m->NumberOfCells(); if( size ) { set = new entry[size]; <API key> k = 0; for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it) { set[k].e = it->GetHandle(); Storage::real cnt[3] = {0,0,0}; m->GetGeometricData(set[k].e,CENTROID,cnt); set[k].xyz[0] = (float)cnt[0]; set[k].xyz[1] = (float)cnt[1]; set[k].xyz[2] = (float)cnt[2]; ++k; } int done = 0, total = size; struct entry * temp = new entry[size]; kdtree_build(0,done,total,temp); delete [] temp; if( size > 1 ) { for(int k = 0; k < 3; k++) { bbox[0+2*k] = std::min<float>(children[0].bbox[0+2*k],children[1].bbox[0+2*k]); bbox[1+2*k] = std::max<float>(children[0].bbox[1+2*k],children[1].bbox[1+2*k]); } } } } SearchKDTree::SearchKDTree(Mesh * m, HandleType * _set, unsigned set_size) : m(m), children(NULL) { size = set_size; if( size ) { set = new entry[size]; for(unsigned k = 0; k < set_size; ++k) { set[k].e = _set[k]; Storage::real cnt[3] = {0,0,0}; m->GetGeometricData(set[k].e,CENTROID,cnt); set[k].xyz[0] = (float)cnt[0]; set[k].xyz[1] = (float)cnt[1]; set[k].xyz[2] = (float)cnt[2]; } int done = 0, total = size; struct entry * temp = new entry[size]; kdtree_build(0,done,total,temp); delete [] temp; if( size > 1 ) { for(int k = 0; k < 3; k++) { bbox[0+2*k] = std::min<float>(children[0].bbox[0+2*k],children[1].bbox[0+2*k]); bbox[1+2*k] = std::max<float>(children[0].bbox[1+2*k],children[1].bbox[1+2*k]); } } } else set = NULL; } inline int SearchKDTree::sphere_tri(const Storage::real tri[3][3], const Storage::real p[3], Storage::real r) const { return triangle_distance(tri[0], tri[1], tri[2], p) <= r ? 1 : 0; } inline int SearchKDTree::segment_tri(const Storage::real tri[3][3], const Storage::real p1[3], const Storage::real p2[3]) const { const Storage::real eps = 1.0e-7; Storage::real a[3],b[3],c[3],n[3], ray[3], d, k, m, l; Storage::real dot00,dot01,dot02,dot11,dot12,invdenom, uq,vq; ray[0] = p2[0]-p1[0]; ray[1] = p2[1]-p1[1]; ray[2] = p2[2]-p1[2]; /* l = sqrt(dotproduct(ray,ray)); if (l) { ray[0] /= l; ray[1] /= l; ray[2] /= l; } */ a[0] = tri[0][0] - tri[2][0]; a[1] = tri[0][1] - tri[2][1]; a[2] = tri[0][2] - tri[2][2]; b[0] = tri[1][0] - tri[2][0]; b[1] = tri[1][1] - tri[2][1]; b[2] = tri[1][2] - tri[2][2]; crossproduct(a,b,n); l = sqrt(dotproduct(n, n)); if (l) { n[0] /= l; n[1] /= l; n[2] /= l; } d = -dotproduct(n,tri[2]); m = dotproduct(n,ray); if( fabs(m) < 1.0e-25 ) return 0; k = -(d + dotproduct(n,p1))/m; if (k < -1.0e-10 || k > 1.0 + 1.0e-10) return 0; c[0] = p1[0] + k*ray[0] - tri[2][0]; c[1] = p1[1] + k*ray[1] - tri[2][1]; c[2] = p1[2] + k*ray[2] - tri[2][2]; dot00 = dotproduct(a,a); dot01 = dotproduct(a,b); dot02 = dotproduct(a,c); dot11 = dotproduct(b,b); dot12 = dotproduct(b,c); invdenom = (dot00*dot11 - dot01*dot01); uq = (dot11*dot02-dot01*dot12); vq = (dot00*dot12-dot01*dot02); if( fabs(invdenom) < 1.0e-25 && fabs(uq) > 0.0 && fabs(vq) > 0.0 ) return 0; uq = uq/invdenom; vq = vq/invdenom; if( uq >= -eps && vq >= -eps && 1.0-(uq+vq) >= -eps ) return 1; return 0; } inline int SearchKDTree::segment_tri_print(const Storage::real tri[3][3], const Storage::real p1[3], const Storage::real p2[3], std::ostream& sout) const { const Storage::real eps = 1.0e-7; Storage::real a[3], b[3], c[3], n[3], ray[3], d, k, m, l; Storage::real dot00, dot01, dot02, dot11, dot12, invdenom, uq, vq; ray[0] = p2[0] - p1[0]; ray[1] = p2[1] - p1[1]; ray[2] = p2[2] - p1[2]; /* l = sqrt(dotproduct(ray,ray)); if (l) { ray[0] /= l; ray[1] /= l; ray[2] /= l; } */ a[0] = tri[0][0] - tri[2][0]; a[1] = tri[0][1] - tri[2][1]; a[2] = tri[0][2] - tri[2][2]; b[0] = tri[1][0] - tri[2][0]; b[1] = tri[1][1] - tri[2][1]; b[2] = tri[1][2] - tri[2][2]; crossproduct(a, b, n); l = sqrt(dotproduct(n, n)); if (l) { n[0] /= l; n[1] /= l; n[2] /= l; } sout << "n " << n[0] << " " << n[1] << " " << n[2]; d = -dotproduct(n, tri[2]); m = dotproduct(n, ray); sout << " d " << d << " m " << m; if (fabs(m) < 1.0e-25) { sout << std::endl; return 0; } k = -(d + dotproduct(n, p1)) / m; sout << " k " << k; if (k < -1.0e-10 || k > 1.0 + 1.0e-10) { sout << std::endl; return 0; } c[0] = p1[0] + k * ray[0] - tri[2][0]; c[1] = p1[1] + k * ray[1] - tri[2][1]; c[2] = p1[2] + k * ray[2] - tri[2][2]; sout << " c " << c[0] << " " << c[1] << " " << c[2]; dot00 = dotproduct(a, a); dot01 = dotproduct(a, b); dot02 = dotproduct(a, c); dot11 = dotproduct(b, b); dot12 = dotproduct(b, c); invdenom = (dot00 * dot11 - dot01 * dot01); uq = (dot11 * dot02 - dot01 * dot12); vq = (dot00 * dot12 - dot01 * dot02); sout << " invdenom " << invdenom << " uq " << uq << " vq " << vq; if (fabs(invdenom) < 1.0e-25 && fabs(uq) > 0.0 && fabs(vq) > 0.0) { sout << std::endl; return 0; } uq = uq / invdenom; vq = vq / invdenom; sout << " coefs " << 1 - uq - vq << " " << uq << " " << vq; if (uq >= -eps && vq >= -eps && 1.0 - (uq + vq) >= -eps) { sout << " hit!" << std::endl; return 1; } sout << std::endl; return 0; } inline int SearchKDTree::segment_bbox(const Storage::real p1[3], const Storage::real p2[3]) const { Storage::real tnear = -1.0e20, tfar = 1.0e20; Storage::real t1,t2,c; for(int i = 0; i < 3; i++) { if( fabs(p2[i]-p1[i]) < 1.0e-15 ) { if( p1[i] < bbox[i*2]-1.0e-3 || p1[i] > bbox[i*2+1]+1.0e-3 ) return 0; } else { t1 = (bbox[i*2+0]-1.0e-3 - p1[i])/(p2[i]-p1[i]); t2 = (bbox[i*2+1]+1.0e-3 - p1[i])/(p2[i]-p1[i]); if( t1 > t2 ) { c = t1; t1 = t2; t2 = c; } if( t1 > tnear ) tnear = t1; if( t2 < tfar ) tfar = t2; if( tnear > tfar ) return 0; if( tfar < 0 ) return 0; if( tnear > 1 ) return 0; } } return 1; } inline int SearchKDTree::sphere_bbox(const Storage::real p[3], Storage::real r) const { return bbox_sphere(p, r, bbox); } inline int SearchKDTree::ray_bbox(double pos[3], double ray[3], double closest) const { double tnear = -1.0e20, tfar = 1.0e20, t1, t2, c; for (int i = 0; i < 3; i++) { if (fabs(ray[i]) < 1.0e-15) { if (pos[i] < bbox[i * 2] || pos[i] > bbox[i * 2 + 1]) return 0; } else { t1 = (bbox[i * 2 + 0] - pos[i]) / ray[i]; t2 = (bbox[i * 2 + 1] - pos[i]) / ray[i]; if (t1 > t2) { c = t1; t1 = t2; t2 = c; } if (t1 > tnear) tnear = t1; if (t2 < tfar) tfar = t2; if (tnear > closest) return 0; if (tnear > tfar) return 0; if (tfar < 0) return 0; } } return 1; } inline bool SearchKDTree::segment_face(const Element & f, const Storage::real p1[3], const Storage::real p2[3]) const { Mesh * m = f->GetMeshLink(); Storage::real tri[3][3] = {{0,0,0},{0,0,0},{0,0,0}}; m->GetGeometricData(f->GetHandle(),CENTROID,tri[2]); ElementArray<Node> nodes = f->getNodes(); m->GetGeometricData(nodes[0]->GetHandle(),CENTROID,tri[1]); for(ElementArray<Node>::size_type k = 0; k < nodes.size(); ++k) { memcpy(tri[0],tri[1],sizeof(Storage::real)*3); //m->GetGeometricData(nodes[k]->GetHandle(),CENTROID,tri[0]); m->GetGeometricData(nodes[(k+1)%nodes.size()]->GetHandle(),CENTROID,tri[1]); if( segment_tri(tri,p1,p2) ) return true; } return false; } inline bool SearchKDTree::segment_face_print(const Element& f, const Storage::real p1[3], const Storage::real p2[3], std::ostream & sout) const { Mesh* m = f->GetMeshLink(); Storage::real tri[3][3] = { {0,0,0},{0,0,0},{0,0,0} }, nrm[3]; f.getAsFace().UnitNormal(nrm); m->GetGeometricData(f->GetHandle(), CENTROID, tri[2]); sout << "segment_face FACE:" << f.LocalID(); sout << " x " << tri[2][0] << " " << tri[2][1] << " " << tri[2][2]; sout << " n " << nrm[0] << " " << nrm[1] << " " << nrm[2]; sout << " bnd " << (f.getAsFace().Boundary() ? "true" : "false"); sout << " ornt " << (f.getAsFace().<API key>() ? "true" : "false"); sout << " nodes " << f.nbAdjElements(NODE); sout << std::endl; ElementArray<Node> nodes = f->getNodes(); m->GetGeometricData(nodes[0]->GetHandle(), CENTROID, tri[1]); for (ElementArray<Node>::size_type k = 0; k < nodes.size(); ++k) { memcpy(tri[0], tri[1], sizeof(Storage::real) * 3); //m->GetGeometricData(nodes[k]->GetHandle(),CENTROID,tri[0]); m->GetGeometricData(nodes[(k + 1) % nodes.size()]->GetHandle(), CENTROID, tri[1]); if (segment_tri_print(tri, p1, p2,sout)) return true; } return false; } inline bool SearchKDTree::sphere_face(const Element& f, const Storage::real p[3], Storage::real r) const { Mesh* m = f->GetMeshLink(); Storage::real tri[3][3] = { {0,0,0},{0,0,0},{0,0,0} }; m->GetGeometricData(f->GetHandle(), CENTROID, tri[2]); ElementArray<Node> nodes = f->getNodes(); m->GetGeometricData(nodes[0]->GetHandle(), CENTROID, tri[1]); for (ElementArray<Node>::size_type k = 0; k < nodes.size(); ++k) { memcpy(tri[0], tri[1], sizeof(Storage::real) * 3); //m->GetGeometricData(nodes[k]->GetHandle(),CENTROID,tri[0]); m->GetGeometricData(nodes[(k + 1) % nodes.size()]->GetHandle(), CENTROID, tri[1]); if (sphere_tri(tri, p, r)) return true; } return false; } inline bool SearchKDTree::segment_cell(const Element & c, const Storage::real p1[3], const Storage::real p2[3]) const { ElementArray<Face> faces = c->getFaces(); for(ElementArray<Face>::iterator it = faces.begin(); it != faces.end(); ++it) if( segment_face(it->self(),p1,p2) ) return true; return false; } inline bool SearchKDTree::sphere_cell(const Element& c, const Storage::real p[3], Storage::real r) const { ElementArray<Face> faces = c->getFaces(); for (ElementArray<Face>::iterator it = faces.begin(); it != faces.end(); ++it) if (sphere_face(it->self(), p, r)) return true; return false; } void SearchKDTree::IntersectSegment(ElementArray<Cell> & cells, const Storage::real p1[3], const Storage::real p2[3]) const { ElementArray<Element> temp(m); MarkerType mrk = m->CreatePrivateMarker(); <API key>(temp, mrk, p1, p2); m-><API key>(temp.data(), static_cast<Storage::enumerator>(temp.size()), mrk); for (ElementArray<Element>::iterator it = temp.begin(); it != temp.end(); ++it) { if (it->GetElementType() == CELL && !it->GetPrivateMarker(mrk)) { cells.push_back(it->getAsCell()); it->SetPrivateMarker(mrk); } else if (it->GetElementType() == FACE) { ElementArray<Cell> f_cells = it->getCells(); for (ElementArray<Cell>::iterator kt = f_cells.begin(); kt != f_cells.end(); ++kt) if (!kt->GetPrivateMarker(mrk)) { cells.push_back(kt->self()); kt->SetPrivateMarker(mrk); } } } m-><API key>(cells.data(), static_cast<Storage::enumerator>(cells.size()), mrk); m-><API key>(mrk); } void SearchKDTree::IntersectSegment(ElementArray<Face>& faces, const Storage::real p1[3], const Storage::real p2[3]) const { ElementArray<Element> temp(m); MarkerType mrk = m->CreatePrivateMarker(); <API key>(temp, mrk, p1, p2); m-><API key>(temp.data(), static_cast<Storage::enumerator>(temp.size()), mrk); for (ElementArray<Element>::iterator it = temp.begin(); it != temp.end(); ++it) { if (it->GetElementType() == CELL) { ElementArray<Face> f = it->getFaces(); for (ElementArray<Face>::iterator jt = f.begin(); jt != f.end(); ++jt) if( !jt->GetPrivateMarker(mrk) ) { faces.push_back(*jt); jt->SetPrivateMarker(mrk); } } else if (it->GetElementType() == FACE) { faces.push_back(it->getAsFace()); it->SetPrivateMarker(mrk); } } m-><API key>(faces.data(), static_cast<Storage::enumerator>(faces.size()), mrk); m-><API key>(mrk); } void SearchKDTree::<API key>(ElementArray<Face>& faces, const Storage::real p1[3], const Storage::real p2[3], std::ostream & sout) const { ElementArray<Element> temp(m); MarkerType mrk = m->CreatePrivateMarker(); <API key>(temp, mrk, p1, p2, sout); sout << "found elements: " << temp.size() << std::endl; m-><API key>(temp.data(), static_cast<Storage::enumerator>(temp.size()), mrk); for (ElementArray<Element>::iterator it = temp.begin(); it != temp.end(); ++it) { sout << ElementTypeName(it->GetElementType()) << ":" << it->LocalID() << " "; if (it->GetElementType() == CELL) { ElementArray<Face> f = it->getFaces(); for (ElementArray<Face>::iterator jt = f.begin(); jt != f.end(); ++jt) if (!jt->GetPrivateMarker(mrk)) { faces.push_back(*jt); jt->SetPrivateMarker(mrk); } } else if (it->GetElementType() == FACE) { faces.push_back(it->getAsFace()); it->SetPrivateMarker(mrk); } } sout << std::endl; sout << "Output faces: " << faces.size() << std::endl; for (ElementArray<Face>::iterator it = faces.begin(); it != faces.end(); ++it) sout << ElementTypeName(it->GetElementType()) << ":" << it->LocalID() << " "; sout << std::endl; m-><API key>(faces.data(), static_cast<Storage::enumerator>(faces.size()), mrk); m-><API key>(mrk); } void SearchKDTree::IntersectSphere(ElementArray<Cell>& cells, const Storage::real p[3], Storage::real r) const { ElementArray<Element> temp(m); MarkerType mrk = m->CreatePrivateMarker(); <API key>(temp, mrk, p, r); m-><API key>(temp.data(), static_cast<Storage::enumerator>(temp.size()), mrk); for (ElementArray<Element>::iterator it = temp.begin(); it != temp.end(); ++it) { if (it->GetElementType() == CELL && !it->GetPrivateMarker(mrk)) { cells.push_back(it->getAsCell()); it->SetPrivateMarker(mrk); } else if (it->GetElementType() == FACE) { ElementArray<Cell> f_cells = it->getCells(); for (ElementArray<Cell>::iterator kt = f_cells.begin(); kt != f_cells.end(); ++kt) if (!kt->GetPrivateMarker(mrk)) { cells.push_back(kt->self()); kt->SetPrivateMarker(mrk); } } } m-><API key>(cells.data(), static_cast<Storage::enumerator>(cells.size()), mrk); m-><API key>(mrk); } void SearchKDTree::IntersectSphere(ElementArray<Face>& faces, const Storage::real p[3], Storage::real r) const { ElementArray<Element> temp(m); MarkerType mrk = m->CreatePrivateMarker(); <API key>(temp, mrk, p, r); m-><API key>(temp.data(), static_cast<Storage::enumerator>(temp.size()), mrk); for (ElementArray<Element>::iterator it = temp.begin(); it != temp.end(); ++it) { if (it->GetElementType() == CELL) { ElementArray<Face> f = it->getFaces(); for (ElementArray<Face>::iterator jt = f.begin(); jt != f.end(); ++jt) if (!jt->GetPrivateMarker(mrk)) { faces.push_back(*jt); jt->SetPrivateMarker(mrk); } } else if (it->GetElementType() == FACE) { faces.push_back(it->getAsFace()); it->SetPrivateMarker(mrk); } } m-><API key>(faces.data(), static_cast<Storage::enumerator>(faces.size()), mrk); m-><API key>(mrk); } void SearchKDTree::<API key>(ElementArray<Element> & hits, MarkerType mrk, const Storage::real p1[3], const Storage::real p2[3]) const { if( size == 1 ) { if( !m->GetPrivateMarker(set[0].e,mrk) ) { Storage::integer edim = Element::<API key>(m->GetGeometricType(set[0].e)); if( edim == 2 ) { if( segment_face(Element(m,set[0].e),p1,p2) ) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e,mrk); } } else if( edim == 3 ) { if( segment_cell(Element(m,set[0].e),p1,p2) ) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e,mrk); } } else { std::cout << __FILE__ << ":" << __LINE__ << " kd-tree structure is not implemented to intersect edges with segments" << std::endl; exit(-1); } } } else { assert(size > 1); if( segment_bbox(p1,p2) ) { children[0].<API key>(hits,mrk,p1,p2); children[1].<API key>(hits,mrk,p1,p2); } } } void SearchKDTree::<API key>(ElementArray<Element>& hits, MarkerType mrk, const Storage::real p1[3], const Storage::real p2[3], std::ostream & sout) const { if (size == 1) { if (!m->GetPrivateMarker(set[0].e, mrk)) { Storage::integer edim = Element::<API key>(m->GetGeometricType(set[0].e)); PrintElement(Cell(m, set[0].e), sout); if (edim == 2) { if (segment_face_print(Element(m, set[0].e), p1, p2, sout)) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e, mrk); } } else if (edim == 3) { if (segment_cell(Element(m, set[0].e), p1, p2)) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e, mrk); } } else { std::cout << __FILE__ << ":" << __LINE__ << " kd-tree structure is not implemented to intersect edges with segments" << std::endl; exit(-1); } } } else { assert(size > 1); if (segment_bbox(p1, p2)) { { sout << "segment "; sout << p1[0] << " " << p1[1] << " " << p1[2]; sout << " <-> "; sout << p2[0] << " " << p2[1] << " " << p2[2]; sout << " is in bbox "; sout << " x " << bbox[0] << ":" << bbox[1]; sout << " y " << bbox[2] << ":" << bbox[3]; sout << " z " << bbox[4] << ":" << bbox[5]; sout << std::endl; } children[0].<API key>(hits, mrk, p1, p2, sout); children[1].<API key>(hits, mrk, p1, p2, sout); } else { sout << "segment "; sout << p1[0] << " " << p1[1] << " " << p1[2]; sout << " <-> "; sout << p2[0] << " " << p2[1] << " " << p2[2]; sout << " is not in bbox "; sout << " x " << bbox[0] << ":" << bbox[1]; sout << " y " << bbox[2] << ":" << bbox[3]; sout << " z " << bbox[4] << ":" << bbox[5]; sout << std::endl; } } } void SearchKDTree::<API key>(ElementArray<Element>& hits, MarkerType mrk, const Storage::real p[3], Storage::real r) const { if (size == 1) { if (!m->GetPrivateMarker(set[0].e, mrk)) { Storage::integer edim = Element::<API key>(m->GetGeometricType(set[0].e)); if (edim == 2) { if (sphere_face(Element(m, set[0].e), p, r)) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e, mrk); } } else if (edim == 3) { if (sphere_cell(Element(m, set[0].e), p, r)) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e, mrk); } } else { std::cout << __FILE__ << ":" << __LINE__ << " kd-tree structure is not implemented to intersect edges with spheres" << std::endl; exit(-1); } } } else { assert(size > 1); if (sphere_bbox(p, r)) { children[0].<API key>(hits, mrk, p, r); children[1].<API key>(hits, mrk, p, r); } } } SearchKDTree::~SearchKDTree() { if( size ) { delete [] set; clear_children(); } } Cell SearchKDTree::SearchCell(const Storage::real * point) const { return SubSearchCell(point); } Cell SearchKDTree::SearchCellPrint(const Storage::real* point, std::ostream & sout) const { return SubSearchCellPrint(point, sout); } } #endif
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package frc.circuitrunners; /** * * @author James */ public class R { public static int BALL_COUNT = 0; public static boolean AUTO_AIM = false; public static int STAGE = 0; public static class stage { public static final int PREPARATION = 1; //Prepare the shooter for shooting, lock back panel for conveyor, autoaim public static final int SHOOT = 2; //Run conveyor, keep shooter rolling, shoot public static final int BACKUP = 3; //Move backwards toward coop bridge public static final int BALL_SMASH = 4; //Smashes the co-op bridge } }
<!DOCTYPE html><html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <meta charset="utf-8"> <title>Phing API Documentation » \<API key></title> <meta name="author" content="Mike van Riel"> <meta name="description" content=""> <link href="../css/template.css" rel="stylesheet" media="all"> <script src="../js/jquery-1.7.1.min.js" type="text/javascript"></script><script src="../js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script><script src="../js/jquery.mousewheel.min.js" type="text/javascript"></script><script src="../js/bootstrap.js" type="text/javascript"></script><script src="../js/template.js" type="text/javascript"></script><script src="../js/prettify/prettify.min.js" type="text/javascript"></script><link rel="shortcut icon" href="../img/favicon.ico"> <link rel="apple-touch-icon" href="../img/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="../img/<API key>.png"> <link rel="apple-touch-icon" sizes="114x114" href="../img/<API key>.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"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></a><a class="brand" href="../index.html">Phing API Documentation</a><div class="nav-collapse"><ul class="nav"> <li class="dropdown"> <a href="#api" class="dropdown-toggle" data-toggle="dropdown"> API Documentation <b class="caret"></b></a><ul class="dropdown-menu"> <li><a>Packages</a></li> <li><a href="../packages/Default.html"><i class="icon-folder-open"></i> Default</a></li> <li><a href="../packages/JSMin.html"><i class="icon-folder-open"></i> JSMin</a></li> <li><a href="../packages/Parallel.html"><i class="icon-folder-open"></i> Parallel</a></li> <li><a href="../packages/Phing.html"><i class="icon-folder-open"></i> Phing</a></li> <li><a href="../packages/phing.html"><i class="icon-folder-open"></i> phing</a></li> </ul> </li> <li class="dropdown" id="charts-menu"> <a href="#charts" class="dropdown-toggle" data-toggle="dropdown"> Charts <b class="caret"></b></a><ul class="dropdown-menu"><li><a href="../graph_class.html"><i class="icon-list-alt"></i> Class hierarchy diagram</a></li></ul> </li> <li class="dropdown" id="reports-menu"> <a href="#reports" class="dropdown-toggle" data-toggle="dropdown"> Reports <b class="caret"></b></a><ul class="dropdown-menu"> <li><a href="../errors.html"><i class="icon-remove-sign"></i> Errors <span class="label label-info">2573</span></a></li> <li><a href="../markers.html"><i class="icon-map-marker"></i> Markers <ul> <li>todo <span class="label label-info">15</span> </li> <li>fixme <span class="label label-info">8</span> </li> </ul></a></li> <li><a href="../deprecated.html"><i class="icon-stop"></i> Deprecated elements <span class="label label-info">11</span></a></li> </ul> </li> </ul></div> </div></div> <div class="go_to_top"><a href=" </div> <div id="___" class="container"> <noscript><div class="alert alert-warning"> Javascript is disabled; several features are only available if Javascript is enabled. </div></noscript> <div class="row"> <div class="span4"> <span class="btn-group visibility" data-toggle="buttons-checkbox"><button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button></span><div class="btn-group view pull-right" data-toggle="buttons-radio"> <button class="btn details" title="Show descriptions and method names"><i class="icon-list"></i></button><button class="btn simple" title="Show only method names"><i class="icon-align-justify"></i></button> </div> <ul class="side-nav nav nav-list"> <li class="nav-header"> <i class="icon-custom icon-method"></i> Methods <ul> <li class="method public "><a href="#method_close" title="close :: Write XML to file and free the DOM objects."><span class="description">Write XML to file and free the DOM objects.</span><pre>close()</pre></a></li> <li class="method public inherited"><a href="#method_getOutput" title="getOutput :: Gets the output writer."><span class="description">Gets the output writer.</span><pre>getOutput()</pre></a></li> <li class="method public "><a href="#<API key>" title="getPreferredOutfile :: Gets a preferred filename for an output file."><span class="description">Gets a preferred filename for an output file.</span><pre>getPreferredOutfile()</pre></a></li> <li class="method public "><a href="#method_initialize" title="initialize :: Perform any initialization."><span class="description">Perform any initialization.</span><pre>initialize()</pre></a></li> <li class="method public "><a href="#method_processRow" title="processRow :: Processes a specific row from PDO result set."><span class="description">Processes a specific row from PDO result set.</span><pre>processRow()</pre></a></li> <li class="method public "><a href="#method_setEncoding" title="setEncoding :: Set the DOM document encoding."><span class="description">Set the DOM document encoding.</span><pre>setEncoding()</pre></a></li> <li class="method public "><a href="#<API key>" title="setFormatOutput :: "><span class="description">setFormatOutput() </span><pre>setFormatOutput()</pre></a></li> <li class="method public inherited"><a href="#method_setOutput" title="setOutput :: Sets the output writer."><span class="description">Sets the output writer.</span><pre>setOutput()</pre></a></li> </ul> </li> <li class="nav-header"> <i class="icon-custom icon-property"></i> Properties <ul></ul> </li> <li class="nav-header protected">» Protected <ul><li class="property protected inherited"><a href="#property_out" title="$out :: Output writer."><span class="description"></span><pre>$out</pre></a></li></ul> </li> <li class="nav-header private">» Private <ul> <li class="property private "><a href="#property_doc" title="$doc :: The XML document being created."><span class="description"></span><pre>$doc</pre></a></li> <li class="property private "><a href="#property_encoding" title="$encoding :: XML document encoding"><span class="description"></span><pre>$encoding</pre></a></li> <li class="property private "><a href="#<API key>" title="$formatOutput :: "><span class="description"></span><pre>$formatOutput</pre></a></li> <li class="property private "><a href="#property_rootNode" title="$rootNode :: "><span class="description"></span><pre>$rootNode</pre></a></li> </ul> </li> </ul> </div> <div class="span8"> <a id="\<API key>"></a><ul class="breadcrumb"> <li> <a href="../index.html"><i class="icon-custom icon-class"></i></a><span class="divider">\</span> </li> <li><a href="../namespaces/global.html">global</a></li> <li class="active"> <span class="divider">\</span><a href="../classes/<API key>.html"><API key></a> </li> </ul> <div class="element class"> <p class="short_description">XML formatter for PDO results.</p> <div class="details"> <div class="long_description"><p>This class reprsents the output of a query using a simple XML schema.</p> <p><results> <row> <col name="id">value</col> <col name="name">value2</col> </row> <row> <col name="id">value</col> <col name="name">value2</col> </row> </results></p> <p>The actual names of the colums will depend on the fetchmode that was used with PDO.</p></div> <table class="table table-bordered"> <tr> <th>author</th> <td><a href="mailto:hans@xmpl.org">Hans Lellelid</a></td> </tr> <tr> <th>package</th> <td><a href="../packages/phing.tasks.ext.pdo.html">phing.tasks.ext.pdo</a></td> </tr> <tr> <th>since</th> <td>2.3.0</td> </tr> </table> <h3> <i class="icon-custom icon-method"></i> Methods</h3> <a id="method_close"></a><div class="element clickable method public method_close" data-toggle="collapse" data-target=".method_close .collapse"> <h2>Write XML to file and free the DOM objects.</h2> <pre>close() </pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div> </div> <a id="method_getOutput"></a><div class="element clickable method public method_getOutput" data-toggle="collapse" data-target=".method_getOutput .collapse"> <h2>Gets the output writer.</h2> <pre>getOutput() : <a href="../classes/Writer.html">\Writer</a></pre> <div class="labels"><span class="label">Inherited</span></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <table class="table table-bordered"><tr> <th>inherited_from</th> <td>\PDOResultFormatter::getOutput()</td> </tr></table> <h3>Returns</h3> <div class="subelement response"><code><a href="../classes/Writer.html">\Writer</a></code></div> </div></div> </div> <a id="<API key>"></a><div class="element clickable method public <API key>" data-toggle="collapse" data-target=".<API key> .collapse"> <h2>Gets a preferred filename for an output file.</h2> <pre>getPreferredOutfile() : string</pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"><p>If no filename is specified, this is where the results will be placed (unless usefile=false).</p></div> <h3>Returns</h3> <div class="subelement response"><code>string</code></div> </div></div> </div> <a id="method_initialize"></a><div class="element clickable method public method_initialize" data-toggle="collapse" data-target=".method_initialize .collapse"> <h2>Perform any initialization.</h2> <pre>initialize() </pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div> </div> <a id="method_processRow"></a><div class="element clickable method public method_processRow" data-toggle="collapse" data-target=".method_processRow .collapse"> <h2>Processes a specific row from PDO result set.</h2> <pre>processRow(array $row) </pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <h3>Parameters</h3> <div class="subelement argument"> <h4>$row</h4> <code>array</code><p>Row of PDO result set.</p></div> </div></div> </div> <a id="method_setEncoding"></a><div class="element clickable method public method_setEncoding" data-toggle="collapse" data-target=".method_setEncoding .collapse"> <h2>Set the DOM document encoding.</h2> <pre>setEncoding(string $v) </pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <h3>Parameters</h3> <div class="subelement argument"> <h4>$v</h4> <code>string</code> </div> </div></div> </div> <a id="<API key>"></a><div class="element clickable method public <API key>" data-toggle="collapse" data-target=".<API key> .collapse"> <h2>setFormatOutput() </h2> <pre>setFormatOutput(boolean $v) </pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <h3>Parameters</h3> <div class="subelement argument"> <h4>$v</h4> <code>boolean</code> </div> </div></div> </div> <a id="method_setOutput"></a><div class="element clickable method public method_setOutput" data-toggle="collapse" data-target=".method_setOutput .collapse"> <h2>Sets the output writer.</h2> <pre>setOutput(\Writer $out) </pre> <div class="labels"><span class="label">Inherited</span></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <table class="table table-bordered"><tr> <th>inherited_from</th> <td>\PDOResultFormatter::setOutput()</td> </tr></table> <h3>Parameters</h3> <div class="subelement argument"> <h4>$out</h4> <code><a href="../classes/Writer.html">\Writer</a></code> </div> </div></div> </div> <h3> <i class="icon-custom icon-property"></i> Properties</h3> <a id="property_out"> </a><div class="element clickable property protected property_out" data-toggle="collapse" data-target=".property_out .collapse"> <h2></h2> <pre>$out : <a href="../classes/Writer.html">\Writer</a></pre> <div class="labels"><span class="label">Inherited</span></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <table class="table table-bordered"><tr> <th>inherited_from</th> <td>\PDOResultFormatter::$$out</td> </tr></table> </div></div> </div> <a id="property_doc"> </a><div class="element clickable property private property_doc" data-toggle="collapse" data-target=".property_doc .collapse"> <h2></h2> <pre>$doc : <a href="http://php.net/manual/en/class.domdocument.php">\DOMDocument</a></pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div> </div> <a id="property_encoding"> </a><div class="element clickable property private property_encoding" data-toggle="collapse" data-target=".property_encoding .collapse"> <h2></h2> <pre>$encoding : string</pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div> </div> <a id="<API key>"> </a><div class="element clickable property private <API key>" data-toggle="collapse" data-target=".<API key> .collapse"> <h2></h2> <pre>$formatOutput : boolean</pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div> </div> <a id="property_rootNode"> </a><div class="element clickable property private property_rootNode" data-toggle="collapse" data-target=".property_rootNode .collapse"> <h2></h2> <pre>$rootNode : <a href="http://php.net/manual/en/class.domelement.php">\DOMElement</a></pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div> </div> </div> </div> </div> </div> <div class="row"><footer class="span12"> Template is built using <a href="http: Documentation is powered by <a href="http: generated on 2012-11-20T07:50:28+01:00.<br></footer></div> </div> </body> </html>
#pragma once #include <folly/io/IOBuf.h> #include <ostream> #include <string> namespace proxygen { class IOBufPrinter { public: enum class Format : uint8_t { HEX_FOLLY = 0, HEX_16 = 1, CHAIN_INFO = 2, BIN = 3, }; static std::string printChain(const folly::IOBuf* buf, Format format, bool coalesce); static std::string printHexFolly(const folly::IOBuf* buf, bool coalesce=false) { return printChain(buf, Format::HEX_FOLLY, coalesce); } static std::string printHex16(const folly::IOBuf* buf, bool coalesce=false) { return printChain(buf, Format::HEX_16, coalesce); } static std::string printChainInfo(const folly::IOBuf* buf) { return printChain(buf, Format::CHAIN_INFO, false); } static std::string printBin(const folly::IOBuf* buf, bool coalesce=false) { return printChain(buf, Format::BIN, coalesce); } IOBufPrinter() {} virtual ~IOBufPrinter() {} virtual std::string print(const folly::IOBuf* buf) = 0; }; class Hex16Printer : public IOBufPrinter { public: std::string print(const folly::IOBuf* buf) override; }; class HexFollyPrinter : public IOBufPrinter { public: std::string print(const folly::IOBuf* buf) override; }; class ChainInfoPrinter : public IOBufPrinter { public: std::string print(const folly::IOBuf* buf) override; }; class BinPrinter : public IOBufPrinter { public: std::string print(const folly::IOBuf* buf) override; }; /** * write the entire binary content from all the buffers into a binary file */ void dumpBinToFile(const std::string& filename, const folly::IOBuf* buf); /** * helper functions for printing in hex a byte array * see unit test for example */ std::string hexStr(folly::StringPiece sp); }
jaxon.cmd.style = { /* Function: jaxon.cmd.style.add Add a LINK reference to the specified .css file if it does not already exist in the HEAD of the current document. Parameters: filename - (string): The URI of the .css file to reference. media - (string): The media type of the css file (print/screen/handheld,..) Returns: true - The operation completed successfully. */ add: function(fileName, media) { const oDoc = jaxon.config.baseDocument; const oHeads = oDoc.<API key>('head'); const oHead = oHeads[0]; const oLinks = oHead.<API key>('link'); const found = false; const iLen = oLinks.length; for (let i = 0; i < iLen && false == found; ++i) if (0 <= oLinks[i].href.indexOf(fileName) && oLinks[i].media == media) found = true; if (false == found) { const oCSS = oDoc.createElement('link'); oCSS.rel = 'stylesheet'; oCSS.type = 'text/css'; oCSS.href = fileName; oCSS.media = media; oHead.appendChild(oCSS); } return true; }, /* Function: jaxon.cmd.style.remove Locate and remove a LINK reference from the current document's HEAD. Parameters: filename - (string): The URI of the .css file. Returns: true - The operation completed successfully. */ remove: function(fileName, media) { const oDoc = jaxon.config.baseDocument; const oHeads = oDoc.<API key>('head'); const oHead = oHeads[0]; const oLinks = oHead.<API key>('link'); let i = 0; while (i < oLinks.length) if (0 <= oLinks[i].href.indexOf(fileName) && oLinks[i].media == media) oHead.removeChild(oLinks[i]); else ++i; return true; }, /* Function: jaxon.cmd.style.waitForCSS Attempt to detect when all .css files have been loaded once they are referenced by a LINK tag in the HEAD of the current document. Parameters: command - (object): The response command object which will contain the following: - command.prop - (integer): The number of 1/10ths of a second to wait before giving up. Returns: true - The .css files appear to be loaded. false - The .css files do not appear to be loaded and the timeout has not expired. */ waitForCSS: function(command) { const oDocSS = jaxon.config.baseDocument.styleSheets; const ssEnabled = []; let iLen = oDocSS.length; for (let i = 0; i < iLen; ++i) { ssEnabled[i] = 0; try { ssEnabled[i] = oDocSS[i].cssRules.length; } catch (e) { try { ssEnabled[i] = oDocSS[i].rules.length; } catch (e) {} } } const ssLoaded = true; iLen = ssEnabled.length; for (let i = 0; i < iLen; ++i) if (0 == ssEnabled[i]) ssLoaded = false; if (false == ssLoaded) { // inject a delay in the queue processing // handle retry counter if (jaxon.cmd.delay.retry(command, command.prop)) { jaxon.cmd.delay.setWakeup(command.response, 10); return false; } // give up, continue processing queue } return true; } };
<?php namespace Phalcon\Forms\Element; use \Phalcon\Tag; use \Phalcon\Forms\Element; use \Phalcon\Forms\ElementInterface; use \Phalcon\Forms\Exception; class File extends Element implements ElementInterface { /** * Renders the element widget returning html * * @param array|null $attributes * @return string * @throws Exception */ public function render($attributes = null) { if (is_array($attributes) === false && is_null($attributes) === false) { throw new Exception('Invalid parameter type.'); } return Tag::emailField($this->fileField($attributes)); } }
package lrstorm; import java.util.ArrayList; import java.util.HashMap; public class <API key> { // state for one segment with information about accidents... private boolean hasAccident; private boolean isNewAccident; private boolean isCleared; private long timeNew; private long timeCleared; private boolean isNewCleared; private HashMap<Integer, Vehicle> vehicles; private ArrayList<Vehicle> stopped; private HashMap<Integer, ArrayList<Vehicle>> accidents; public <API key>() { vehicles = new HashMap<Integer, Vehicle>(); stopped = new ArrayList<Vehicle>(); accidents = new HashMap<Integer, ArrayList<Vehicle>>(); } @Override public String toString() { String res = "accident:" + this.hasAccident + " is new:" + this.isNewAccident + " is cleared:" + this.isCleared + " timeNew:" + this.timeNew + " timeCleared:" + this.timeCleared; for (Vehicle v : stopped) { res += " " + v.id; } res += " all vehicles: " + vehicles.size(); return res; } public Vehicle addVehicle(int vid, long time, int xway, int lane, int segment, int position, int speed) { Vehicle v; if (vehicles.get(vid) == null) { v = new Vehicle(vid, time, xway, lane, segment, position); vehicles.put(vid, v); } else { v = vehicles.get(vid); // int pos, int xway, int seg, int lane, int speed, long time v.update(position, xway, segment, lane, speed, time); } return v; } public class UpdateSegmentAnswer { public boolean cleared; public boolean newacc; public UpdateSegmentAnswer(boolean cleared, boolean newacc) { this.cleared = cleared; this.newacc = newacc; } } public UpdateSegmentAnswer updateSegmentState(int vid, long time, int xway, int lane, int segment, int position, int speed) { Vehicle v = this.addVehicle(vid, time, xway, lane, segment, position, speed); boolean cleared = false; boolean newacc = false; if (v.stopped) { // check if it is stopped in the same position as the other // vehicles newacc = addStoppedVehicle(v); } else { cleared = addRunningVehicle(v); } return new UpdateSegmentAnswer(cleared, newacc); } private boolean addRunningVehicle(Vehicle v) { boolean cleared = false; if (stopped.size() == 0) { return cleared; } if (stopped.contains(v)) { // vehicle was stopped and is not anymore stopped.remove(v); // we have at least one accident if (this.accidents.size() != 0) { if (this.accidents.containsKey(v.pos)) { ArrayList<Vehicle> vlist = this.accidents.get(v.pos); vlist.remove(v); if (vlist.size() <= 1) { this.accidents.remove(v.pos); if (this.accidents.size() == 0) { this.isCleared = true; cleared = true; this.timeCleared = v.time; this.timeNew = -1; } } } } } return cleared; } private boolean addStoppedVehicle(Vehicle v) { System.out.println("Adding stopped vehicle " + v.id); if (!this.stopped.contains(v) && this.stopped.size() == 0) { this.stopped.add(v); return false; } boolean newacc = false; // check if there is an accident for (Vehicle elem : this.stopped) { if (elem.id == v.id) continue; if (v.pos == elem.pos && v.lane == elem.lane && (v.time - elem.time) <= 120000 && v.xway == elem.xway) { // if accident position is not in array of accidents if (this.accidents.size() == 0) { newacc = true; this.isNewAccident = true; this.timeNew = v.time; } if (this.accidents.containsKey(v.pos)) { // add this vehicle as involved in accident? this.accidents.get(v.pos).add(v); } else { ArrayList<Vehicle> vids = new ArrayList<Vehicle>(); vids.add(v); vids.add(elem); this.accidents.put(v.pos, vids); } } break; } if (!stopped.contains(v)) stopped.add(v); return newacc; } public boolean hasAccident() { return hasAccident; } public void setAccident(boolean hasAccident) { this.hasAccident = hasAccident; } public boolean isCleared() { return isCleared; } public void setCleared(boolean isCleared) { this.isCleared = isCleared; } public boolean isNewAccident() { return isNewAccident; } public void setNewAccident(boolean isNewAccident) { this.isNewAccident = isNewAccident; } public boolean isNewCleared() { return isNewCleared; } public void setNewCleared(boolean isNewCleared) { this.isNewCleared = isNewCleared; } public long getTimeNew() { return timeNew; } public void setTimeNew(long timeNew) { this.timeNew = timeNew; } public long getTimeCleared() { return timeCleared; } public void setTimeCleared(long timeCleared) { this.timeCleared = timeCleared; } }
#include "content/shell/app/shell_main_delegate.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "cc/base/switches.h" #include "content/public/browser/browser_main_runner.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "content/public/test/layouttest_support.h" #include "content/shell/app/<API key>.h" #include "content/shell/browser/shell_browser_main.h" #include "content/shell/browser/<API key>.h" #include "content/shell/common/shell_switches.h" #include "content/shell/renderer/<API key>.h" #include "net/cookies/cookie_monster.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/base/ui_base_switches.h" #include "ui/gfx/switches.h" #include "ui/gl/gl_switches.h" #include "ipc/ipc_message.h" // For <API key>. #if defined(<API key>) #define <API key> #include "content/public/common/content_ipc_logging.h" #define <API key>(msg_id, logger) \ content::RegisterIPCLogger(msg_id, logger) #include "content/shell/common/shell_messages.h" #endif #if defined(OS_ANDROID) #include "base/posix/global_descriptors.h" #include "content/shell/android/shell_descriptors.h" #endif #if defined(OS_MACOSX) #include "content/shell/app/paths_mac.h" #include "content/shell/app/<API key>.h" #endif // OS_MACOSX #if defined(OS_WIN) #include <initguid.h> #include "base/logging_win.h" #endif namespace { #if defined(OS_WIN) // If "Content Shell" doesn't show up in your list of trace providers in // Sawbuck, add these registry entries to your machine (NOTE the optional // Wow6432Node key for x64 machines): // 1. Find: HKLM\SOFTWARE\[Wow6432Node\]Google\Sawbuck\Providers // 2. Add a subkey with the name "{<API key>}" // 3. Add these values: // "default_flags"=dword:00000001 // "default_level"=dword:00000004 // @="Content Shell" // {<API key>} const GUID <API key> = { 0x6a3e50a4, 0x7e15, 0x4099, { 0x84, 0x13, 0xec, 0x94, 0xd8, 0xc2, 0xa4, 0xb6 } }; #endif void InitLogging() { base::FilePath log_filename; PathService::Get(base::DIR_EXE, &log_filename); log_filename = log_filename.AppendASCII("content_shell.log"); logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_ALL; settings.log_file = log_filename.value().c_str(); settings.delete_old = logging::DELETE_OLD_LOG_FILE; logging::InitLogging(settings); logging::SetLogItems(true, true, true, true); } } // namespace namespace content { ShellMainDelegate::ShellMainDelegate() { } ShellMainDelegate::~ShellMainDelegate() { } bool ShellMainDelegate::<API key>(int* exit_code) { #if defined(OS_WIN) // Enable trace control and transport through event tracing for Windows. logging::LogEventProvider::Initialize(<API key>); #endif #if defined(OS_MACOSX) // Needs to happen before <API key>() and before // <API key>() are called. <API key>(); <API key>(); <API key>(); #endif // OS_MACOSX InitLogging(); CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::<API key>)) { if (!<API key>()) { if (exit_code) *exit_code = 1; return true; } } if (command_line.HasSwitch(switches::kDumpRenderTree)) { <API key>(); command_line.AppendSwitch(switches::kProcessPerTab); command_line.AppendSwitch(switches::kEnableLogging); command_line.AppendSwitch(switches::<API key>); #if !defined(OS_ANDROID) command_line.AppendSwitchASCII( switches::kUseGL, gfx::<API key>); #endif command_line.AppendSwitch(switches::kSkipGpuDataLoading); command_line.AppendSwitchASCII(switches::kTouchEvents, switches::kTouchEventsEnabled); command_line.AppendSwitch(switches::<API key>); command_line.AppendSwitchASCII(switches::<API key>, "1.0"); #if defined(OS_ANDROID) command_line.AppendSwitch( switches::<API key>); // Capturing pixel results does not yet work when implementation-side command_line.AppendSwitch(cc::switches::<API key>); #endif if (!command_line.HasSwitch(switches::kStableReleaseMode)) { command_line.AppendSwitch( switches::<API key>); command_line.AppendSwitch(switches::kEnableCssShaders); } if (!command_line.HasSwitch(switches::<API key>)) command_line.AppendSwitch(cc::switches::<API key>); command_line.AppendSwitch(switches::<API key>); command_line.AppendSwitch(switches::kMuteAudio); net::CookieMonster::EnableFileScheme(); // Unless/until WebM files are added to the media layout tests, we need to // avoid removing MP4/H264/AAC so that layout tests can run on Android. #if !defined(OS_ANDROID) net::<API key>(); #endif if (!<API key>()) { if (exit_code) *exit_code = 1; return true; } } SetContentClient(&content_client_); return false; } void ShellMainDelegate::PreSandboxStartup() { <API key>(); } int ShellMainDelegate::RunProcess( const std::string& process_type, const MainFunctionParams& <API key>) { if (!process_type.empty()) return -1; #if !defined(OS_ANDROID) // Android stores the BrowserMainRunner instance as a scoped member pointer // on the ShellMainDelegate class because of different object lifetime. scoped_ptr<BrowserMainRunner> browser_runner_; #endif browser_runner_.reset(BrowserMainRunner::Create()); return ShellBrowserMain(<API key>, browser_runner_); } void ShellMainDelegate::<API key>() { #if defined(OS_ANDROID) // In the Android case, the renderer runs with a different UID and can never // access the file system. So we are passed a file descriptor to the // ResourceBundle pak at launch time. int pak_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(kShellPakDescriptor); if (pak_fd != base::<API key>) { ui::ResourceBundle::<API key>(pak_fd, false); ResourceBundle::GetSharedInstance().AddDataPackFromFile( pak_fd, ui::SCALE_FACTOR_100P); return; } #endif base::FilePath pak_file; #if defined(OS_MACOSX) pak_file = <API key>(); #else base::FilePath pak_dir; #if defined(OS_ANDROID) bool got_path = PathService::Get(base::<API key>, &pak_dir); DCHECK(got_path); pak_dir = pak_dir.Append(FILE_PATH_LITERAL("paks")); #else PathService::Get(base::DIR_MODULE, &pak_dir); #endif pak_file = pak_dir.Append(FILE_PATH_LITERAL("content_shell.pak")); #endif ui::ResourceBundle::<API key>(pak_file); } <API key>* ShellMainDelegate::<API key>() { browser_client_.reset(new <API key>); return browser_client_.get(); } <API key>* ShellMainDelegate::<API key>() { renderer_client_.reset(new <API key>); return renderer_client_.get(); } } // namespace content
<?php // use Yii; use yii\helpers\Html; use yii\grid\GridView; use yii\widgets\ListView; use frontend\components\TagsCloudWidgets; use frontend\components\RctReplayWidget; use common\models\Post; /* @var $this yii\web\View */ /* @var $searchModel common\models\PostSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ ?> <div class='container'> <div class='row'> <div class='col-md-9'> <ol class="breadcrumb"> <li><a href="<?= Yii::$app->HomeUrl; ?>"></a></li> <li></li> </ol> <?= ListView::widget( [ 'id' => 'postList', 'dataProvider' => $dataProvider, 'itemView' => '_listitem', 'pager' => [ 'maxButtonCount' => 10, 'nextPageLabel' => Yii::t('app', ''), 'prevPageLabel' => Yii::t('app', ''), ], ] )?> </div> <div class='col-md-3'> <div class="searchchbox"> <ul class="list-group"> <li class="list-group-item"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> <?php // $data = Post::find()->count(); // sleep(5); $data = Yii::$app->cache->get('postCount'); if ($data === false) { $data = Post::find()->count(); sleep(5); Yii::$app->cache->set('postCount',$data); } echo '('.$data.')'; ?> </li> <li class="list-group-item"> <form class="form-inline" action="index.php?r=post/index" id="w0" method="get"> <input type="form-group" class="form-control" name="PostSearch[title]" id="w0input" placeholder=""> <button type="submit" class="btn btn-default"></button> </form> </li> </ul> </div> <div class="tagcloudbox"> <ul class="list-group"> <li class="list-group-item"> <span class="glyphicon glyphicon-tags" aria-hidden="true"></span> </li> <li class="list-group-item"> <?= TagsCloudWidgets::widget(['tags'=>$tags]); ?> </li> </ul> </div> <div class="commentbox"> <ul class="list-group"> <li class="list-group-item"> <span class="glyphicon glyphicon-comment" aria-hidden="true"></span> </li> <li class="list-group-item"> <?= RctReplayWidget::widget(['recentComments'=>$recentComments]); ?> </li> </ul> </div> </div> </div> </div>
import { Metadata } from '../rpc_types'; export const singleDemoEntry: Metadata = { revision: { url: 'example.com', hash: '123', }, demos: ['demo0'], }; export const twoDemoEntries: Metadata = { revision: { url: 'example.com', hash: '123', }, demos: ['demo0', 'demo1'], };
#ifndef <API key> #define <API key> // INCLUDES #include "<API key>.h" #include <scShared/Plugins/abstractalgorithm.h> #include <utils/generics/circularbuffer.h> #include <connectivity/<API key>.h> #include <connectivity/network/network.h> // QT INCLUDES #include <QMutex> #include <QElapsedTimer> #include <QPointer> // EIGEN INCLUDES #include <Eigen/Core> // FORWARD DECLARATIONS namespace FIFFLIB { class FiffInfo; } namespace DISPLIB { class <API key>; } namespace RTPROCESSINGLIB { class RtConnectivity; } namespace SCMEASLIB { class <API key>; class <API key>; class <API key>; class RealTimeEvokedSet; } // DEFINE NAMESPACE <API key> namespace <API key> { // <API key> FORWARD DECLARATIONS class <API key>; /** * DECLARE CLASS <API key> * * @brief The <API key> class provides a <API key> plugin for online processing. */ class <API key> <API key> : public SCSHAREDLIB::AbstractAlgorithm { Q_OBJECT Q_PLUGIN_METADATA(IID "scsharedlib/1.0" FILE "<API key>.json") //New Qt5 Plugin system replaces Q_EXPORT_PLUGIN2 macro // Use the Q_INTERFACES() macro to tell Qt's meta-object system about the interfaces Q_INTERFACES(SCSHAREDLIB::AbstractAlgorithm) public: /** * Constructs a <API key>. */ <API key>(); /** * Destroys the <API key>. */ ~<API key>(); /** * AbstractAlgorithm functions */ virtual QSharedPointer<SCSHAREDLIB::AbstractPlugin> clone() const; virtual void init(); /** * Inits widgets which are used to control this plugin, then emits them in form of a QList. */ void <API key>(); virtual void unload(); virtual bool start(); virtual bool stop(); virtual SCSHAREDLIB::AbstractPlugin::PluginType getType() const; virtual QString getName() const; virtual QWidget* setupWidget(); virtual QString getBuildInfo(); /** * Udates the pugin with new (incoming) data. * * @param[in] pMeasurement The incoming data in form of a generalized Measurement. */ void updateSource(SCMEASLIB::Measurement::SPtr pMeasurement); /** * Updates the real time multi sample array data * * @param[in] pMeasurement The incoming data in form of a generalized Measurement. */ void updateRTMSA(SCMEASLIB::Measurement::SPtr pMeasurement); /** * Slot to update the fiff evoked * * @param[in] pMeasurement The evoked to be appended. */ void updateRTEV(SCMEASLIB::Measurement::SPtr pMeasurement); signals: void <API key>(const QStringList& <API key>); protected: /** * Generate the node positions based on the current incoming data. Also take into account selected bad channels. */ void <API key>(); /** * AbstractAlgorithm function */ virtual void run(); /** * Slot called when a new real-time connectivity estimate is available. * * @param[in] connectivityResult The new connectivity estimate. */ void <API key>(const QList<CONNECTIVITYLIB::Network>& connectivityResults, const CONNECTIVITYLIB::<API key>& <API key>); /** * Slot called when the metric changed. * * @param[in] sMetric The new metric. */ void onMetricChanged(const QString &sMetric); /** * Slot called when the number of trials changed. * * @param[in] iNumberTrials The new number of trials. */ void <API key>(int iNumberTrials); /** * Slot called when the window type changed. * * @param[in] windowType The new window type. */ void onWindowTypeChanged(const QString& windowType); /** * Slot called when the trigger type changed. * * @param[in] triggerType The new trigger type. */ void <API key>(const QString& triggerType); /** * Slot called when the frequency band changed. * * @param[in] fFreqLow The new lower frequency band. * @param[in] fFreqHigh The new higher frequency band. */ void <API key>(float fFreqLow, float fFreqHigh); private: qint32 m_iDownSample; /**< Sampling rate. */ qint32 m_iNumberAverages; /**< The number of averages used to calculate the connectivity estimate. Use this only for resting state data when the averaging plugin is not connected.*/ qint32 <API key>; /**< The current number of bad channels. USed to test if new bad channels were selected. */ float m_fFreqBandLow; /**< The lower frequency band to average the connectivity weights from. */ float m_fFreqBandHigh; /**< The higher frequency band to average the connectivity weights to. */ qint32 m_iBlockSize; /**< The block size of teh last received data block. In frequency bins. */ QString m_sAvrType; /**< The average type. */ QStringList <API key>; /**< The connectivity metric to use. */ QMutex m_mutex; /**< The mutex to guarantee thread safety. */ QElapsedTimer m_timer; /**< The timer to evaluate performance. */ CONNECTIVITYLIB::<API key> <API key>; /**< The connectivity settings.*/ QSharedPointer<UTILSLIB::CircularBuffer<CONNECTIVITYLIB::Network> > m_pCircularBuffer; /**< The circular buffer holding the connectivity estimates.*/ QSharedPointer<RTPROCESSINGLIB::RtConnectivity> m_pRtConnectivity; /**< The real-time connectivity estimation object.*/ QSharedPointer<FIFFLIB::FiffInfo> m_pFiffInfo; /**< Fiff measurement info.*/ QSharedPointer<DISPLIB::<API key>> <API key>; /**< The connectivity settings widget which will be added to the Quick Control view. The QuickControlView will not take ownership. Ownership will be managed by the QSharedPointer.*/ QAction* <API key>; /**< flag whether thread is running.*/ SCSHAREDLIB::PluginInputData<SCMEASLIB::<API key>>::SPtr m_pRTSEInput; /**< The <API key> input.*/ SCSHAREDLIB::PluginInputData<SCMEASLIB::<API key>>::SPtr m_pRTMSAInput; /**< The <API key> input.*/ SCSHAREDLIB::PluginInputData<SCMEASLIB::RealTimeEvokedSet>::SPtr m_pRTEVSInput; /**< The RealTimeEvoked input.*/ SCSHAREDLIB::PluginOutputData<SCMEASLIB::<API key>>::SPtr m_pRTCEOutput; /**< The <API key> output.*/ CONNECTIVITYLIB::Network <API key>; /**< The current connectivity estimate.*/ Eigen::MatrixX3f m_matNodeVertLeft; /**< Holds the left hemi vertex postions of the network nodes. Corresponding to the neuronal sources.*/ Eigen::MatrixX3f m_matNodeVertRight; /**< Holds the right hemi vertex postions of the network nodes. Corresponding to the neuronal sources.*/ Eigen::MatrixX3f m_matNodeVertComb; /**< Holds both hemi vertex postions of the network nodes. Corresponding to the neuronal sources.*/ Eigen::RowVectorXi m_vecPicks; /**< The picked data channels. */ CONNECTIVITYLIB::Network <API key>; /**< The current connectivity result.*/ }; } // NAMESPACE #endif // <API key>
// modification, are permitted provided that the following conditions are met: // and/or other materials provided with the distribution. // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System; using System.Collections.Generic; using System.Xml.Serialization; using System.IO; <summary> Constants for Sponsored Links BlogEngine.NET WidgetControl </summary> public static class <API key> { public static string CurrentIndex = "CurrentIndex"; public static string AdCollectionKey = "adsCollection"; public static string DefaultAdText = "<span style='font-family: Verdana;font-size: x-small'><b>Technical Interview Patterns</b><br> Logically sound approach to technical interview... <br/><A Href='http: public static string DefaultAdName = "Sample Ad Provider"; public static int DefaultAdWeight = 1; public static string <API key> = "hideForAdmin"; public static string SerializedAdsKey = "ads"; public static string WidgetSettingsKey = "<API key>"; public static string EmptyAdName = "Script public static string EmptyAdText = "Paste script here..."; public static int EmptyAdWeight = 1; public static string AuthZUserMessage = "<b style='font-size:10px;'>Ads are hidded for authenticated user</B>"; public static string WidgetName = "Sponsored Links"; } <summary> Ad base class </summary> [Serializable()] public class Ad { public Ad() { _id = Guid.NewGuid(); _script = string.Empty; _tagName = string.Empty; _weight = 1; } public Ad(Guid id, string content, string name, int weight) { _id = id; _script = content; _tagName = name; _weight = weight; } private Guid _id; public Guid ID { get { return _id; } set { _id = value; } } private string _script; public string Script { get { return _script; } set { _script = value == null ? value : value.Replace(">", "&gt;").Replace("<", "&lt;"); } } private String _tagName; public String TagName { get { return _tagName; } set { _tagName = value; } } private int _weight; public int RWeight { get { return _weight; } set { _weight = value; } } } <summary> AdManagementBase </summary> public class AdManagementBase { private ICache _cache; private List<Ad> _ads; public AdManagementBase(ICache cache,List<Ad> ads) { _cache = cache; _ads = ads; } public Ad GetNextRandomAd() { if (_ads.Count < 1) return null; int seed = (int)DateTime.Now.Ticks; Random rnd = new Random(seed); int index = rnd.Next(_ads.Count); return _ads[index]; } public Ad <API key>(int weight) { if (_ads.Count < 1) return null; int seed = (int)DateTime.Now.Ticks; Random rnd = new Random(seed); Boolean found = false; Ad finalCandidate = null; while (found == false) { finalCandidate = GetNextRandomAd(); int toss= rnd.Next(weight); found = toss <= finalCandidate.RWeight; } return finalCandidate; } public List<Ad> GetAds() { return _ads; } public static string SerializeAds(List<Ad> ads) { if ((ads == null) || (ads.Count == 0)) return string.Empty; XmlSerializer serializer = new XmlSerializer(typeof(List<Ad>)); StringWriter stream = new StringWriter(); serializer.Serialize(stream, ads); return stream.ToString(); } public static List<Ad> DeSerializeAds(string serializedStream) { if (string.IsNullOrEmpty(serializedStream)) return new List<Ad>(); XmlSerializer serializer = new XmlSerializer(typeof(List<Ad>)); return (List<Ad>)serializer.Deserialize(new StringReader(serializedStream)); } } <summary> Generic Adapter Interface for Cache Object </summary> public interface ICache { void Insert<T>(string key, T obj); T GetObject<T>(string key); }
package clean import ( "flag" "os" "github.com/tueftler/doget/command" "github.com/tueftler/doget/config" "github.com/tueftler/doget/dockerfile" ) // CleanCommand allows to remove the vendor directory and all of its contents type CleanCommand struct { command.Command flags *flag.FlagSet } // NewCommand creates new clean command instance func NewCommand(name string) *CleanCommand { return &CleanCommand{flags: flag.NewFlagSet(name, flag.ExitOnError)} } // Run performs action of clean command func (c *CleanCommand) Run(parser *dockerfile.Parser, args []string) error { target := config.Vendordir if _, err := os.Stat(target); nil == err { return os.RemoveAll(target) } return nil }
#ifndef <API key> #define <API key> #if (defined(_MSC_VER) && (_MSC_VER > 1000)) #pragma once #endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */ #include "mmcore/api/MegaMolCore.std.h" #include "mmcore/factories/CallAutoDescription.h" #include "mmcore/view/CallRender3D.h" #include <glowl/FramebufferObject.hpp> namespace megamol { namespace core_gl { namespace view { inline constexpr char callrender2dgl_name[] = "CallRender2DGL"; inline constexpr char callrender2dgl_desc[] = "New and improved call for rendering a frame with OpenGL"; /** * Call for rendering 2d images * * Function "Render" tells the callee to render itself into the currently * active opengl context (TODO: Later on it could also be a FBO). * The bounding box member will be set to the world space rectangle * containing the visible part. * * Function "GetExtents" asks the callee to fill the extents member of the * call (bounding boxes). * The renderer should not draw anything outside the bounding box */ class CallRender2DGL : public core::view::BaseCallRender<glowl::FramebufferObject, callrender2dgl_name, callrender2dgl_desc> { public: /** Ctor. */ CallRender2DGL(void) : BaseCallRender<glowl::FramebufferObject, callrender2dgl_name, callrender2dgl_desc>() { this->caps.RequireOpenGL(); } /** Dtor. */ virtual ~CallRender2DGL(void) = default; }; /** Description class typedef */ typedef core::factories::CallAutoDescription<CallRender2DGL> <API key>; } /* end namespace view */ } // namespace core_gl } /* end namespace megamol */ #endif /* <API key> */
<!DOCTYPE html> <! Copyright (c) 2015 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. <link rel="import" href="/tracing/extras/importer/jszip.html"> <link rel="import" href="/tracing/model/model.html"> <link rel="import" href="/tracing/importer/importer.html"> <script> /** * @fileoverview Blah. */ 'use strict'; tr.exportTo('tr.e.importer.ddms', function() { var Importer = tr.importer.Importer; var kPid = 0; var kCategory = 'java'; var kMethodLutEndMarker = '\n*end\n'; var kThreadsStart = '\n*threads\n'; var kMethodsStart = '\n*methods\n'; var kTraceMethodEnter = 0x00; // method entry var kTraceMethodExit = 0x01; // method exit var kTraceUnroll = 0x02; // method exited by exception unrolling // 0x03 currently unused var <API key> = 0x03; // two bits var kTraceHeaderLength = 32; var kTraceMagicValue = 0x574f4c53; var <API key> = 2; var <API key> = 3; var <API key> = 10; // using v2 var <API key> = 14; // using v3 with two timestamps function Reader(string_payload) { this.position_ = 0; this.data_ = JSZip.utils.transformTo('uint8array', string_payload); } Reader.prototype = { __proto__: Object.prototype, uint8: function() { var result = this.data_[this.position_]; this.position_ += 1; return result; }, uint16: function() { var result = 0; result += this.uint8(); result += this.uint8() << 8; return result; }, uint32: function() { var result = 0; result += this.uint8(); result += this.uint8() << 8; result += this.uint8() << 16; result += this.uint8() << 24; return result; }, uint64: function() { // Javascript isn't able to manage 64-bit numeric values. var low = this.uint32(); var high = this.uint32(); var low_str = ('0000000' + low.toString(16)).substr(-8); var high_str = ('0000000' + high.toString(16)).substr(-8); var result = high_str + low_str; return result; }, seekTo: function(position) { this.position_ = position; }, hasMore: function() { return this.position_ < this.data_.length; } }; /** * Imports DDMS method tracing events into a specified model. * @constructor */ function DdmsImporter(model, data) { this.importPriority = 3; this.model_ = model; this.data_ = data; } /** * Guesses whether the provided events is from a DDMS method trace. * @return {boolean} True when events is a DDMS method trace. */ DdmsImporter.canImport = function(data) { if (typeof(data) === 'string' || data instanceof String) { var header = data.slice(0, 1000); return header.startsWith('*version\n') && header.indexOf('\nvm=') >= 0 && header.indexOf(kThreadsStart) >= 0; } /* key bit */ return false; }; DdmsImporter.prototype = { __proto__: Importer.prototype, get model() { return this.model_; }, /** * Imports the data in this.data_ into this.model_. */ importEvents: function(isSecondaryImport) { var divider = this.data_.indexOf(kMethodLutEndMarker) + kMethodLutEndMarker.length; this.metadata_ = this.data_.slice(0, divider); this.methods_ = {}; this.parseThreads(); this.parseMethods(); var traceReader = new Reader(this.data_.slice(divider)); var magic = traceReader.uint32(); if (magic != kTraceMagicValue) { throw Error('Failed to match magic value'); } this.version_ = traceReader.uint16(); if (this.version_ != <API key>) { throw Error('Unknown version'); } var dataOffest = traceReader.uint16(); var startDateTime = traceReader.uint64(); var recordSize = traceReader.uint16(); traceReader.seekTo(dataOffest); while (traceReader.hasMore()) { this.parseTraceEntry(traceReader); } }, parseTraceEntry: function(reader) { var tid = reader.uint16(); var methodPacked = reader.uint32(); var cpuSinceStart = reader.uint32(); var wallClockSinceStart = reader.uint32(); var method = methodPacked & ~<API key>; var action = methodPacked & <API key>; var thread = this.getTid(tid); method = this.getMethodName(method); if (action == kTraceMethodEnter) { thread.sliceGroup.beginSlice(kCategory, method, wallClockSinceStart, undefined, cpuSinceStart); } else if (thread.sliceGroup.openSliceCount) { thread.sliceGroup.endSlice(wallClockSinceStart, cpuSinceStart); } }, parseThreads: function() { var threads = this.metadata_.slice(this.metadata_.indexOf(kThreadsStart) + kThreadsStart.length); threads = threads.slice(0, threads.indexOf('\n*')); threads = threads.split('\n'); threads.forEach(this.parseThread.bind(this)); }, parseThread: function(thread_line) { var tid = thread_line.slice(0, thread_line.indexOf('\t')); var thread = this.getTid(parseInt(tid)); thread.name = thread_line.slice(thread_line.indexOf('\t') + 1); }, getTid: function(tid) { return this.model_.getOrCreateProcess(kPid) .getOrCreateThread(tid); }, parseMethods: function() { var methods = this.metadata_.slice(this.metadata_.indexOf(kMethodsStart) + kMethodsStart.length); methods = methods.slice(0, methods.indexOf('\n*')); methods = methods.split('\n'); methods.forEach(this.parseMethod.bind(this)); }, parseMethod: function(method_line) { var data = method_line.split('\t'); var methodId = parseInt(data[0]); var methodName = data[1] + '.' + data[2] + data[3]; this.addMethod(methodId, methodName); }, addMethod: function(methodId, methodName) { this.methods_[methodId] = methodName; }, getMethodName: function(methodId) { return this.methods_[methodId]; } }; // Register the DdmsImporter to the Importer. tr.importer.Importer.register(DdmsImporter); return { DdmsImporter: DdmsImporter }; }); </script>
# Android-<TwitterConsumerkey> Xamarin bindings for the twitter android sdk ## Xamarin bindings for twitter android sdk core In this document we document how we got very rough but working [Xamarin bindings](http: Installation with visual studio Do not use these bindings directly. They are really quick and really dirty. If you still want to: - Clone this repository into an arbitrary folder. - Select your solution in visual studio. - File -> Add -> Existing Project -> Choose this .csproj file. - Add a reference in your android project. Xamarin Android has to use a jdk with at least version 1.7. How we got here The main reference is [this guide](http://developer.xamarin.com/guides/android/advanced_topics/<API key>/<API key>(.jar)/). We created a new project from the "Xamarin Bindings library" project. # Getting the jar We located the relevant java archive at a [private twitter maven repository](https: # Getting the depedencies In the [maven repository for twitter core](https: # Adding the jars to the project We added all four jars to the `Jars` folder in our project. We chose build action `EmbeddedJar` for `twitter-core-1.4.0.jar` and `fabric-1.3.4.jar` and build action `<API key>` for `gson-2.2.4.jar` and `retrofit-1.6.1.jar`. Contrary to what the accompanying `AboutJars.txt` says we did not choose `InputJar` and `ReferenceJar`. We did not [know beforehand](http://stackoverflow.com/questions/26629838/<TwitterConsumerkey>) that we would have to directly use `fabric`. Only later we set its build action from `<API key>` to `EmbeddedJar` to generate bindings for it as well. # Fixing errors The errors we had to fix fall into four categories: 1. Methods with the same name as the class. Easy to fix by specifying a renaming in `Metadata.xml` like so: `<attr path="/api/package[@name='com.twitter.sdk.android.core.models']/class[@name='Coordinates']/field[@name='coordinates']" name="name">Coordinats</attr>` 2. Some classes were private but should be public. Easy to fix by overriding the visibility in `Metadata.xml`: `<attr path="/api/package[@name='com.twitter.sdk.android.core.models']/class[@name='Entity']" name="visibility">public</attr>` 3. An interface was missing. We created an empty interface in `Additions/IAppSpiCall.cs`. 4. An overriding method returned `ICollection<ITask>` while the overriden method returned `ICollection`. We added a method that does an explicit cast in `Additions/PriorityTask.cs`. It was helpful that [<TwitterConsumerkey>](https: # Adding resources Twitter core for android needs [resources](https: What we had to do is add twitter-corre-1.4.0 as a library project that includes its resources. We created an archive `twitter-core-1.4.0.zip` with the following structure: twitter-core-1.4.0.zip |_bin |_classes.jar |_AndroidMainfest.xml |_res |_layout |_ ... |_drawable |_ ... |_ ... The `res` folder and `AndroidManifest.xml` are from the original `twitter-core-1.4.0.aar`. `classes.jar` is the original twitter core `classes.jar`. In Visual Studio we chose `LibraryProjectZip` as build action for `twitter-core-1.4.0.zip`.
feature 'Reviews', :js do given!(:someone) { create(:user, email: 'ryan@spree.com') } given!(:review) { create(:review, :approved, user: someone) } background do Spree::Reviews::Config.<API key> = false end context 'product with no review' do given!(:product_no_reviews) { create(:product) } scenario 'informs that no reviews has been written yet' do visit spree.product_path(product_no_reviews) expect(page).to have_text Spree.t(:<API key>) end # Regression test for #103 context 'shows correct number of previews' do background do create_list :review, 3, product: product_no_reviews, approved: true Spree::Reviews::Config[:preview_size] = 2 end scenario 'displayed reviews are limited by the set preview size' do visit spree.product_path(product_no_reviews) expect(page.all('.review').count).to be(2) end end end context 'when anonymous user' do background do Spree::Reviews::Config.require_login = true end context 'visit product with review' do background do visit spree.product_path(review.product) end scenario 'can see review title' do expect(page).to have_text review.title end scenario 'can see a prompt to review' do expect(page).to have_text Spree.t(:<API key>) end end end context 'when logged in user' do given!(:user) { create(:user) } background do sign_in_as! user end context 'visit product with review' do background do <API key> visit spree.product_path(review.product) end scenario 'can see review title' do expect(page).to have_text review.title end scenario 'can see create new review button' do expect(page).to have_text Spree.t(:<API key>) end scenario 'can create new review' do click_on Spree.t(:<API key>) expect(page).to have_text Spree.t(:<API key>, name: review.product.name) expect(page).not_to have_text 'Show Identifier' within '#new_review' do click_star(3) fill_in 'review_name', with: user.email fill_in 'review_title', with: 'Great product!' fill_in 'review_review', with: 'Some big review text..' click_on 'Submit your review' end expect(page).to have_text Spree.t(:<API key>) expect(page).not_to have_text 'Some big review text..' end end end context 'visits product with review where show_identifier is false' do given!(:user) { create(:user) } given!(:review) { create(:review, :approved, :hide_identifier, review: 'review text', user: user) } background do visit spree.product_path(review.product) end scenario 'show anonymous review' do expect(page).to have_text Spree.t(:anonymous) expect(page).to have_text 'review text' end end private def sign_in_as!(user) visit spree.login_path within '#new_spree_user' do fill_in 'Email', with: user.email fill_in 'Password', with: user.password end click_button 'Login' end def click_star(num) page.all(:xpath, "//a[@title='#{num} stars']")[0].click end end
package com.cra.figaro.algorithm.factored.factors.factory import com.cra.figaro.language._ import com.cra.figaro.algorithm.factored.factors._ import com.cra.figaro.algorithm.lazyfactored.Star import com.cra.figaro.algorithm.structured.ComponentCollection /** * A Sub-Factory to make Star Factors from arbitrary elements */ object StarFactory { /** * Make a StarFactor from an Element <p. * * This Factor has only one value whose probability is 1.0 */ def makeStarFactor[T](cc: ComponentCollection, elem: Element[T]): List[Factor[Double]] = { val elemVar = Factory.getVariable(cc, elem) require(elemVar.range.size == 1 && elemVar.range(0) == Star[T], "Trying to create a star factor from a value set that is not only star") val factor = new BasicFactor[Double](List(), List(elemVar)) factor.set(List(0), 1.0) List(factor) } }
<div id="footer"> Copyright &copy; 2010 Deoxxa Development and the Mineserver Project. All rights reserved. </div>
#!/bin/env python # Automatically translated python version of # OpenSceneGraph example program "osglight" # !!! This program will need manual tuning before it will work. !!! import sys from osgpypp import osg from osgpypp import osgDB from osgpypp import osgUtil from osgpypp import osgViewer # Translated from file 'osglight.cpp' # OpenSceneGraph example, osglight. #* of this software and associated documentation files (the "Software"), to deal #* in the Software without restriction, including without limitation the rights #* copies of the Software, and to permit persons to whom the Software is #* furnished to do so, subject to the following conditions: #* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #* 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. #include <osgViewer/Viewer> #include <osg/Group> #include <osg/Node> #include <osg/Light> #include <osg/LightSource> #include <osg/StateAttribute> #include <osg/Geometry> #include <osg/Point> #include <osg/MatrixTransform> #include <osg/<API key>> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgUtil/Optimizer> #include <osgUtil/SmoothingVisitor> #include "stdio.h" # callback to make the loaded model oscilate up and down. class <API key> (osg.NodeCallback) : <API key>( osg.BoundingSphere bs) _firstTime = 0.0 _period = 4.0 _range = bs.radius()*0.5 virtual void operator()(osg.Node* node, osg.NodeVisitor* nv) pat = dynamic_cast<osg.<API key>*>(node) frameStamp = nv.getFrameStamp() if pat and frameStamp : if _firstTime==0.0 : _firstTime = frameStamp.getSimulationTime() phase = (frameStamp.getSimulationTime()-_firstTime)/_period phase -= floor(phase) phase *= (2.0 * osg.PI) rotation = osg.Quat() rotation.makeRotate(phase,1.0,1.0,1.0) pat.setAttitude(rotation) pat.setPosition(osg.Vec3(0.0,0.0,sin(phase))*_range) # must traverse the Node's subgraph traverse(node,nv) _firstTime = double() _period = double() _range = double() def createLights(bb, rootStateSet): lightGroup = osg.Group() modelSize = bb.radius() # create a spot light. myLight1 = osg.Light() myLight1.setLightNum(0) myLight1.setPosition(osg.Vec4(bb.corner(4),1.0)) myLight1.setAmbient(osg.Vec4(1.0,0.0,0.0,1.0)) myLight1.setDiffuse(osg.Vec4(1.0,0.0,0.0,1.0)) myLight1.setSpotCutoff(20.0) myLight1.setSpotExponent(50.0) myLight1.setDirection(osg.Vec3(1.0,1.0,-1.0)) lightS1 = osg.LightSource() lightS1.setLight(myLight1) lightS1.<API key>(osg.StateAttribute.ON) lightS1.setStateSetModes(*rootStateSet,osg.StateAttribute.ON) lightGroup.addChild(lightS1) # create a local light. myLight2 = osg.Light() myLight2.setLightNum(1) myLight2.setPosition(osg.Vec4(0.0,0.0,0.0,1.0)) myLight2.setAmbient(osg.Vec4(0.0,1.0,1.0,1.0)) myLight2.setDiffuse(osg.Vec4(0.0,1.0,1.0,1.0)) myLight2.<API key>(1.0) myLight2.<API key>(2.0/modelSize) myLight2.<API key>(2.0/osg.square(modelSize)) lightS2 = osg.LightSource() lightS2.setLight(myLight2) lightS2.<API key>(osg.StateAttribute.ON) lightS2.setStateSetModes(*rootStateSet,osg.StateAttribute.ON) mt = osg.MatrixTransform() # set up the animation path animationPath = osg.AnimationPath() animationPath.insert(0.0,osg.AnimationPath.ControlPoint(bb.corner(0))) animationPath.insert(1.0,osg.AnimationPath.ControlPoint(bb.corner(1))) animationPath.insert(2.0,osg.AnimationPath.ControlPoint(bb.corner(2))) animationPath.insert(3.0,osg.AnimationPath.ControlPoint(bb.corner(3))) animationPath.insert(4.0,osg.AnimationPath.ControlPoint(bb.corner(4))) animationPath.insert(5.0,osg.AnimationPath.ControlPoint(bb.corner(5))) animationPath.insert(6.0,osg.AnimationPath.ControlPoint(bb.corner(6))) animationPath.insert(7.0,osg.AnimationPath.ControlPoint(bb.corner(7))) animationPath.insert(8.0,osg.AnimationPath.ControlPoint(bb.corner(0))) animationPath.setLoopMode(osg.AnimationPath.SWING) mt.setUpdateCallback(osg.<API key>(animationPath)) # create marker for point light. marker = osg.Geometry() vertices = osg.Vec3Array() vertices.push_back(osg.Vec3(0.0,0.0,0.0)) marker.setVertexArray(vertices) marker.addPrimitiveSet(osg.DrawArrays(GL_POINTS,0,1)) stateset = osg.StateSet() point = osg.Point() point.setSize(4.0) stateset.setAttribute(point) marker.setStateSet(stateset) markerGeode = osg.Geode() markerGeode.addDrawable(marker) mt.addChild(lightS2) mt.addChild(markerGeode) lightGroup.addChild(mt) return lightGroup def createWall(v1, v2, v3, stateset): # create a drawable for occluder. geom = osg.Geometry() geom.setStateSet(stateset) noXSteps = 100 noYSteps = 100 coords = osg.Vec3Array() coords.reserve(noXSteps*noYSteps) dx = (v2-v1)/((float)noXSteps-1.0) dy = (v3-v1)/((float)noYSteps-1.0) row = unsigned int() vRowStart = v1 for(row=0row<noYSteps++row) v = vRowStart for(unsigned int col=0col<noXSteps++col) coords.push_back(v) v += dx vRowStart+=dy geom.setVertexArray(coords) colors = osg.Vec4Array(1) (*colors)[0].set(1.0,1.0,1.0,1.0) geom.setColorArray(colors, osg.Array.BIND_OVERALL) for(row=0row<noYSteps-1++row) quadstrip = osg.DrawElementsUShort(osg.PrimitiveSet.QUAD_STRIP) quadstrip.reserve(noXSteps*2) for(unsigned int col=0col<noXSteps++col) quadstrip.push_back((row+1)*noXSteps+col) quadstrip.push_back(row*noXSteps+col) geom.addPrimitiveSet(quadstrip) # create the normals. osgUtil.SmoothingVisitor.smooth(*geom) return geom def createRoom(loadedModel): # default scale for this model. bs = osg.BoundingSphere(osg.Vec3(0.0,0.0,0.0),1.0) root = osg.Group() if loadedModel : loaded_bs = loadedModel.getBound() pat = osg.<API key>() pat.setPivotPoint(loaded_bs.center()) pat.setUpdateCallback(<API key>(loaded_bs)) pat.addChild(loadedModel) bs = pat.getBound() root.addChild(pat) bs.radius()*=1.5 # create a bounding box, which we'll use to size the room. bb = osg.BoundingBox() bb.expandBy(bs) # create statesets. rootStateSet = osg.StateSet() root.setStateSet(rootStateSet) wall = osg.StateSet() wall.setMode(GL_CULL_FACE,osg.StateAttribute.ON) floor = osg.StateSet() floor.setMode(GL_CULL_FACE,osg.StateAttribute.ON) roof = osg.StateSet() roof.setMode(GL_CULL_FACE,osg.StateAttribute.ON) geode = osg.Geode() # create front side. geode.addDrawable(createWall(bb.corner(0), bb.corner(4), bb.corner(1), wall)) # right side geode.addDrawable(createWall(bb.corner(1), bb.corner(5), bb.corner(3), wall)) # left side geode.addDrawable(createWall(bb.corner(2), bb.corner(6), bb.corner(0), wall)) # back side geode.addDrawable(createWall(bb.corner(3), bb.corner(7), bb.corner(2), wall)) # floor geode.addDrawable(createWall(bb.corner(0), bb.corner(1), bb.corner(2), floor)) # roof geode.addDrawable(createWall(bb.corner(6), bb.corner(7), bb.corner(4), roof)) root.addChild(geode) root.addChild(createLights(bb,rootStateSet)) return root def main(argv): # use an ArgumentParser object to manage the program arguments. arguments = osg.ArgumentParser(argv) # construct the viewer. viewer = osgViewer.Viewer() # load the nodes from the commandline arguments. loadedModel = osgDB.readNodeFiles(arguments) # if not loaded assume no arguments passed in, try use default mode instead. if not loadedModel : loadedModel = osgDB.readNodeFile("glider.osgt") # create a room made of foor walls, a floor, a roof, and swinging light fitting. rootnode = createRoom(loadedModel) # run optimization over the scene graph optimzer = osgUtil.Optimizer() optimzer.optimize(rootnode) # add a viewport to the viewer and attach the scene graph. viewer.setSceneData( rootnode ) # create the windows and run the threads. viewer.realize() viewer.getCamera().setCullingMode( viewer.getCamera().getCullingMode() ~osg.CullStack.<API key>) return viewer.run() if __name__ == "__main__": main(sys.argv)
<?php namespace SilverStripe\GraphQL\Tests\Middleware; use GraphQL\Type\Schema; use SilverStripe\GraphQL\Middleware\QueryMiddleware; class <API key> implements QueryMiddleware { public function process(Schema $schema, $query, $context, $params, callable $next) { return ['result' => "It was me, {$params['name']}!"]; } }
<?php namespace Admin; // module/Admin/cong/module.config.php: return array( 'controllers' => array( //add module controllers 'invokables' => array( 'Admin\Controller\Index' => 'Admin\Controller\IndexController', 'Admin\Controller\Auth' => 'Admin\Controller\AuthController', 'Admin\Controller\Usuario' => 'Admin\Controller\UsuarioController', ), ), 'router' => array( 'routes' => array( 'admin' => array( 'type' => 'Literal', 'options' => array( 'route' => '/admin', 'defaults' => array( '__NAMESPACE__' => 'Admin\Controller', 'controller' => 'Index', 'action' => 'index', 'module' => 'admin' ), ), 'may_terminate' => true, 'child_routes' => array( 'default' => array( 'type' => 'Segment', 'options' => array( 'route' => '/[:controller[/:action]]', 'constraints' => array( 'controller' => '[a-zA-Z][a-zA-Z0-9_-]*', 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', ), 'defaults' => array( ), ), 'child_routes' => array( //permite mandar dados pela url 'wildcard' => array( 'type' => 'Wildcard' ), ), ), ), ), ), ), 'view_manager' => array( //the module can have a specific layout // 'template_map' => array( // 'layout/layout' => __DIR__ . '/../view/layout/layout.phtml', 'template_path_stack' => array( 'admin' => __DIR__ . '/../view', ), ), 'service_manager' => array( 'factories' => array( 'Session' => function($sm) { return new \Zend\Session\Container('Sigecon'); }, 'Cache' => function($sm) { $config = $sm->get('Configuration'); $cache = StorageFactory::factory( array( 'adapter' => $config['cache']['adapter'], 'plugins' => array( 'exception_handler' => array('throw_exceptions' => false), 'Serializer' ), ) ); return $cache; }, ) ), 'doctrine' => array( 'driver' => array( __NAMESPACE__ .'_driver' => array( 'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver', 'cache' => 'array', 'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Model') ), 'orm_default' => array( 'drivers' => array( __NAMESPACE__.'\Model' => __NAMESPACE__.'_driver' ) ) ) ), );
// rw.cpp - written and placed in the public domain by Wei Dai #include "pch.h" #include "rw.h" #include "nbtheory.h" #include "asn.h" NAMESPACE_BEGIN(CryptoPP) template<> const byte <API key><SHA>::decoration = 0x33; template<> const byte <API key><RIPEMD160>::decoration = 0x31; void EMSA2Pad::Pad(<API key> &, const byte *input, unsigned int inputLen, byte *emsa2Block, unsigned int emsa2BlockLen) const { assert (inputLen > 0 && inputLen <= MaxUnpaddedLength(emsa2BlockLen)); // convert from bit length to byte length emsa2BlockLen++; if (emsa2BlockLen % 8 > 1) { emsa2Block[0] = 0; emsa2Block++; } emsa2BlockLen /= 8; emsa2Block[0] = input[0]; // indicate empty or non-empty message memset(emsa2Block+1, 0xbb, <API key>); // padd with 0xbb emsa2Block[<API key>] = 0xba; // separator memcpy(emsa2Block+<API key>, input+1, inputLen-1); emsa2Block[emsa2BlockLen-1] = 0xcc; // make it congruent to 12 mod 16 } DecodingResult EMSA2Pad::Unpad(const byte *emsa2Block, unsigned int emsa2BlockLen, byte *output) const { // convert from bit length to byte length emsa2BlockLen++; if (emsa2BlockLen % 8 > 1) { if (emsa2Block[0] != 0) return DecodingResult(); emsa2Block++; } emsa2BlockLen /= 8; // check last byte if (emsa2Block[emsa2BlockLen-1] != 0xcc) return DecodingResult(); // skip past the padding until we find the seperator unsigned i=1; while (i<emsa2BlockLen-1 && emsa2Block[i++] != 0xba) if (emsa2Block[i-1] != 0xbb) // not valid padding return DecodingResult(); assert(i==emsa2BlockLen-1 || emsa2Block[i-1]==0xba); unsigned int outputLen = emsa2BlockLen - i; output[0] = emsa2Block[0]; memcpy (output+1, emsa2Block+i, outputLen-1); return DecodingResult(outputLen); } template <word r> void RWFunction<r>::BERDecode(<API key> &bt) { BERSequenceDecoder seq(bt); m_n.BERDecode(seq); seq.MessageEnd(); } template <word r> void RWFunction<r>::DEREncode(<API key> &bt) const { DERSequenceEncoder seq(bt); m_n.DEREncode(seq); seq.MessageEnd(); } template <word r> Integer RWFunction<r>::ApplyFunction(const Integer &in) const { DoQuickSanityCheck(); Integer out = in.Squared()%m_n; const word r2 = r/2; const word r3a = (16 + 5 - r) % 16; // n%16 could be 5 or 13 const word r3b = (16 + 13 - r) % 16; const word r4 = (8 + 5 - r/2) % 8; // n%8 == 5 switch (out % 16) { case r: break; case r2: case r2+8: out <<= 1; break; case r3a: case r3b: out.Negate(); out += m_n; break; case r4: case r4+8: out.Negate(); out += m_n; out <<= 1; break; default: out = Integer::Zero(); } return out; } template <word r> bool RWFunction<r>::Validate(<API key> &rng, unsigned int level) const { bool pass = true; pass = pass && m_n > Integer::One() && m_n%8 == 5; return pass; } template <word r> bool RWFunction<r>::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const { return GetValueHelper(this, name, valueType, pValue).Assignable() <API key>(Modulus) ; } template <word r> void RWFunction<r>::AssignFrom(const NameValuePairs &source) { AssignFromHelper(this, source) <API key>(Modulus) ; } // private key operations: // generate a random private key template <word r> void <API key><r>::GenerateRandom(<API key> &rng, const NameValuePairs &alg) { int modulusSize = 2048; alg.GetIntValue("ModulusSize", modulusSize) || alg.GetIntValue("KeySize", modulusSize); if (modulusSize < 16) throw InvalidArgument("<API key>: specified modulus length is too small"); const NameValuePairs &primeParam = <API key>(modulusSize); m_p.GenerateRandom(rng, <API key>(primeParam, MakeParameters("EquivalentTo", 3)("Mod", 8))); m_q.GenerateRandom(rng, <API key>(primeParam, MakeParameters("EquivalentTo", 7)("Mod", 8))); m_n = m_p * m_q; m_u = m_q.InverseMod(m_p); } template <word r> void <API key><r>::BERDecode(<API key> &bt) { BERSequenceDecoder seq(bt); m_n.BERDecode(seq); m_p.BERDecode(seq); m_q.BERDecode(seq); m_u.BERDecode(seq); seq.MessageEnd(); } template <word r> void <API key><r>::DEREncode(<API key> &bt) const { DERSequenceEncoder seq(bt); m_n.DEREncode(seq); m_p.DEREncode(seq); m_q.DEREncode(seq); m_u.DEREncode(seq); seq.MessageEnd(); } template <word r> Integer <API key><r>::CalculateInverse(const Integer &in) const { DoQuickSanityCheck(); Integer cp=in%m_p, cq=in%m_q; if (Jacobi(cp, m_p) * Jacobi(cq, m_q) != 1) { cp = cp%2 ? (cp+m_p) >> 1 : cp >> 1; cq = cq%2 ? (cq+m_q) >> 1 : cq >> 1; } cp = ModularSquareRoot(cp, m_p); cq = ModularSquareRoot(cq, m_q); Integer out = CRT(cq, m_q, cp, m_p, m_u); return STDMIN(out, m_n-out); } template <word r> bool <API key><r>::Validate(<API key> &rng, unsigned int level) const { bool pass = RWFunction<r>::Validate(rng, level); pass = pass && m_p > Integer::One() && m_p%8 == 3 && m_p < m_n; pass = pass && m_q > Integer::One() && m_q%8 == 7 && m_q < m_n; pass = pass && m_u.IsPositive() && m_u < m_p; if (level >= 1) { pass = pass && m_p * m_q == m_n; pass = pass && m_u * m_q % m_p == 1; } if (level >= 2) pass = pass && VerifyPrime(rng, m_p, level-2) && VerifyPrime(rng, m_q, level-2); return pass; } template <word r> bool <API key><r>::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const { return GetValueHelper<RWFunction<r> >(this, name, valueType, pValue).Assignable() <API key>(Prime1) <API key>(Prime2) <API key>(<API key>) ; } template <word r> void <API key><r>::AssignFrom(const NameValuePairs &source) { AssignFromHelper<RWFunction<r> >(this, source) <API key>(Prime1) <API key>(Prime2) <API key>(<API key>) ; } template class RWFunction<IFSSA_R>; template class <API key><IFSSA_R>; NAMESPACE_END
<div id="doc"> <div id="head" class="clearfix"> <h1><a href="/">Shaker Demo</a></h1> <div id="nav"> {{{buttons}}} </div> </div> <div id="main" class="clearfix"> {{{primary}}} {{{secondary}}} </div> </div>
import React from "react"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Books from "./pages/Books"; import Detail from "./pages/Detail"; import NoMatch from "./pages/NoMatch"; import Nav from "./components/Nav"; const App = () => ( <Router> <div> <Nav /> <Switch> {/* <Route exact path="/" component={Books} /> <Route exact path="/books" component={Books} /> <Route exact path="/books/:id" component={Detail} /> */} <Route component={NoMatch} /> </Switch> </div> </Router> ); export default App;
<?php namespace app\controllers; use Yii; class <API key> extends \app\extentions\BaseController { public function actionIndex() { return $this->render('index'); } public function actionEquipment($pId = null) { Yii::$app->calculator->initComponent(); return $this->render('equipment',[ 'products' => Yii::$app->calculator->products, ]); } public function actionProduct($pId = null) { Yii::$app->calculator->initComponent([ 'pId' => $pId ]); $this->layout = 'calculator'; return $this->render('product',[ 'products' => Yii::$app->calculator->products, 'product' => Yii::$app->calculator->product ]); } }
package net.dougqh.jak.jvm.assembler.macros.api; import static net.dougqh.jak.Jak.*; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import net.dougqh.jak.jvm.assembler.JvmClassWriter; import net.dougqh.jak.jvm.assembler.JvmWriter; import net.dougqh.jak.jvm.assembler.macros.stmt; import org.junit.Test; public final class SynchronizedTest { @Test public final void sync() { JvmClassWriter classWriter = new JvmWriter().define( public_().class_( "FunctionImpl" ).implements_( Function.class ) ); classWriter.<API key>(); classWriter.define( public_().method( int.class, "eval" ) ). ideclare( 0, "x" ). synchronized_( "this", new stmt() { protected void body() { iinc( "x" ); } } ). ireturn( "x" ); Function func = classWriter.< Function >newInstance(); assertThat( func.eval(), is( 1 ) ); } @Test public final void sync_with_return() { JvmClassWriter classWriter = new JvmWriter().define( public_().class_( "FunctionImpl" ).implements_( Function.class ) ); classWriter.<API key>(); classWriter.define( public_().method( int.class, "eval" ) ).ideclare( 0, "x" ). synchronized_( "this", new stmt() { protected void body() { ireturn( 1 ); } } ); Function func = classWriter.< Function >newInstance(); assertThat( func.eval(), is( 1 ) ); } public static interface Function { public int eval(); } }
using System; using System.Data; namespace MyMeta.MySql5 { #if ENTERPRISE using System.Runtime.InteropServices; [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IProcedure))] #endif public class MySql5Procedure : Procedure { public MySql5Procedure() { } } }
<?php use yii\helpers\Html; use yii\bootstrap\ActiveForm; use yii\captcha\Captcha; /* @var $this yii\web\View */ $this->title = 'Отблагодарить'; ?> <h1 class="page-header"><?= Html::encode($this->title) ?></h1> <p>Деньги пойдут на развитие проекта и развитие планетарной инфраструктуры объединения человечества на основе Любви, Счастья, Радости, Процветания и Изобилия</p> <iframe frameborder="0" allowtransparency="true" scrolling="no" src="https:
package org.basex.query.expr.gflwor; import org.basex.query.*; import org.basex.query.expr.*; import org.basex.query.util.*; import org.basex.query.value.type.*; import org.basex.query.var.*; import org.basex.util.*; import org.basex.util.hash.*; public abstract class Clause extends ParseExpr { /** All variables declared in this clause. */ Var[] vars; /** * Constructor. * @param info input info * @param seqType sequence type * @param vars declared variables */ Clause(final InputInfo info, final SeqType seqType, final Var... vars) { super(info, seqType); this.vars = vars; } /** * Cleans unused variables from this clause. * @param decl variables declared by this FLWOR expression * @param used list of the IDs of all variables used in the following clauses * @return {@code true} if something changed, {@code false} otherwise */ @SuppressWarnings("unused") boolean clean(final IntObjMap<Var> decl, final BitArray used) { return false; } /** * Evaluates the clause. * @param sub wrapped evaluator * @return evaluator */ abstract Eval eval(Eval sub); @Override public abstract Clause compile(CompileContext cc) throws QueryException; @Override public abstract Clause optimize(CompileContext cc) throws QueryException; @Override public abstract Clause inline(Var var, Expr ex, CompileContext cc) throws QueryException; @Override public abstract Clause copy(CompileContext cc, IntObjMap<Var> vm); /** * Checks if the given clause (currently: let or where) can be slid over this clause. * @param cl clause * @return result of check */ boolean skippable(final Clause cl) { return cl.accept(new ASTVisitor() { @Override public boolean used(final VarRef ref) { for(final Var var : vars) { if(var.is(ref.var)) return false; } return true; } }); } /** * All declared variables of this clause. * @return declared variables */ public final Var[] vars() { return vars; } /** * Checks if the given variable is declared by this clause. * @param var variable * @return {code true} if the variable was declared here, {@code false} otherwise */ public final boolean declares(final Var var) { for(final Var decl : vars) { if(var.is(decl)) return true; } return false; } /** * Calculates the minimum and maximum number of results. * @param minMax minimum and maximum number of incoming tuples */ void calcSize(@SuppressWarnings("unused") final long[] minMax) { } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Mon Mar 31 17:30:31 CST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title></title> <meta name="date" content="2014-03-31"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="\u5DF2\u8FC7\u65F6\u7684\u5217\u8868"; } </script> <noscript> <div> JavaScript</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title=""></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title=""> <li><a href="overview-summary.html"></a></li> <li></li> <li></li> <li></li> <li><a href="overview-tree.html"></a></li> <li class="navBarCell1Rev"></li> <li><a href="index-files/index-1.html"></a></li> <li><a href="help-doc.html"></a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li></li> <li></li> </ul> <ul class="navList"> <li><a href="index.html?deprecated-list.html" target="_top"></a></li> <li><a href="deprecated-list.html" target="_top"></a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="allclasses-noframe.html"></a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h1 title=" API" class="title"> API</h1> <h2 title=""></h2> <ul> <li><a href="#method"></a></li> </ul> </div> <div class="contentContainer"><a name="method"> </a> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary=", "> <caption><span></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col"></th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="com/baidu/mapapi/map/ItemizedOverlay.html#boundCenter(com.baidu.mapapi.map.OverlayItem)">com.baidu.mapapi.map.ItemizedOverlay.boundCenter(OverlayItem)</a> <div class="block"><i>: <a href="com/baidu/mapapi/map/OverlayItem.html#setAnchor(int)"><code>OverlayItem.setAnchor(int)</code></a></i></div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="com/baidu/mapapi/map/ItemizedOverlay.html#boundCenterBottom(com.baidu.mapapi.map.OverlayItem)">com.baidu.mapapi.map.ItemizedOverlay.boundCenterBottom(OverlayItem)</a> <div class="block"><i>: <a href="com/baidu/mapapi/map/OverlayItem.html#setAnchor(int)"><code>OverlayItem.setAnchor(int)</code></a></i></div> </td> </tr> <tr class="altColor"> <td class="colOne"><a href="com/baidu/mapapi/map/ItemizedOverlay.html#createItem(int)">com.baidu.mapapi.map.ItemizedOverlay.createItem(int)</a> <div class="block"><i>2.1.1<a href="com/baidu/mapapi/map/ItemizedOverlay.html#addItem(java.util.List)"><code>ItemizedOverlay.addItem(List)</code></a> <a href="com/baidu/mapapi/map/ItemizedOverlay.html#removeItem(com.baidu.mapapi.map.OverlayItem)"><code>ItemizedOverlay.removeItem(OverlayItem)</code></a>OverlayItem.</i></div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="com/baidu/mapapi/map/MapView.html#displayZoomControls(boolean)">com.baidu.mapapi.map.MapView.displayZoomControls(boolean)</a></td> </tr> <tr class="altColor"> <td class="colOne"><a href="com/baidu/mapapi/map/MapView.html#getZoomControls()">com.baidu.mapapi.map.MapView.getZoomControls()</a></td> </tr> </tbody> </table> </li> </ul> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title=""></a><a name="<API key>"> </a> <ul class="navList" title=""> <li><a href="overview-summary.html"></a></li> <li></li> <li></li> <li></li> <li><a href="overview-tree.html"></a></li> <li class="navBarCell1Rev"></li> <li><a href="index-files/index-1.html"></a></li> <li><a href="help-doc.html"></a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li></li> <li></li> </ul> <ul class="navList"> <li><a href="index.html?deprecated-list.html" target="_top"></a></li> <li><a href="deprecated-list.html" target="_top"></a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="allclasses-noframe.html"></a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
import numpy as np from .kern import CombinationKernel from paramz.caching import Cache_this import itertools from functools import reduce def <API key>(func): """ A decorator that allows catching numpy invalid operations as exceptions (the default behaviour is raising warnings). """ def func_wrapper(*args, **kwargs): np.seterr(invalid='raise') result = func(*args, **kwargs) np.seterr(invalid='warn') return result return func_wrapper class Prod(CombinationKernel): """ Computes the product of 2 kernels :param k1, k2: the kernels to multiply :type k1, k2: Kern :rtype: kernel object """ def __init__(self, kernels, name='mul'): _newkerns = [] for kern in kernels: if isinstance(kern, Prod): for part in kern.parts: #kern.unlink_parameter(part) _newkerns.append(part.copy()) else: _newkerns.append(kern.copy()) super(Prod, self).__init__(_newkerns, name) def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ input_dict = super(Prod, self)._save_to_input_dict() input_dict["class"] = str("GPy.kern.Prod") return input_dict @Cache_this(limit=3, force_kwargs=['which_parts']) def K(self, X, X2=None, which_parts=None): if which_parts is None: which_parts = self.parts elif not isinstance(which_parts, (list, tuple)): # if only one part is given which_parts = [which_parts] return reduce(np.multiply, (p.K(X, X2) for p in which_parts)) @Cache_this(limit=3, force_kwargs=['which_parts']) def Kdiag(self, X, which_parts=None): if which_parts is None: which_parts = self.parts return reduce(np.multiply, (p.Kdiag(X) for p in which_parts)) def <API key>(self, dL_dK, X, X2=None): if len(self.parts)==2: self.parts[0].<API key>(dL_dK*self.parts[1].K(X,X2), X, X2) self.parts[1].<API key>(dL_dK*self.parts[0].K(X,X2), X, X2) else: for combination in itertools.combinations(self.parts, len(self.parts) - 1): prod = reduce(np.multiply, [p.K(X, X2) for p in combination]) to_update = list(set(self.parts) - set(combination))[0] to_update.<API key>(dL_dK * prod, X, X2) def <API key>(self, dL_dKdiag, X): if len(self.parts)==2: self.parts[0].<API key>(dL_dKdiag*self.parts[1].Kdiag(X), X) self.parts[1].<API key>(dL_dKdiag*self.parts[0].Kdiag(X), X) else: for combination in itertools.combinations(self.parts, len(self.parts) - 1): prod = reduce(np.multiply, [p.Kdiag(X) for p in combination]) to_update = list(set(self.parts) - set(combination))[0] to_update.<API key>(dL_dKdiag * prod, X) def gradients_X(self, dL_dK, X, X2=None): target = np.zeros(X.shape) if len(self.parts)==2: target += self.parts[0].gradients_X(dL_dK*self.parts[1].K(X, X2), X, X2) target += self.parts[1].gradients_X(dL_dK*self.parts[0].K(X, X2), X, X2) else: for combination in itertools.combinations(self.parts, len(self.parts) - 1): prod = reduce(np.multiply, [p.K(X, X2) for p in combination]) to_update = list(set(self.parts) - set(combination))[0] target += to_update.gradients_X(dL_dK * prod, X, X2) return target def gradients_X_diag(self, dL_dKdiag, X): target = np.zeros(X.shape) if len(self.parts)==2: target += self.parts[0].gradients_X_diag(dL_dKdiag*self.parts[1].Kdiag(X), X) target += self.parts[1].gradients_X_diag(dL_dKdiag*self.parts[0].Kdiag(X), X) else: k = self.Kdiag(X)*dL_dKdiag for p in self.parts: target += p.gradients_X_diag(k/p.Kdiag(X),X) return target def input_sensitivity(self, summarize=True): if summarize: i_s = np.ones((self.input_dim)) for k in self.parts: i_s[k._all_dims_active] *= k.input_sensitivity(summarize) return i_s else: return super(Prod, self).input_sensitivity(summarize) def <API key>(self, gradients): """ Update gradient in the order in which parameters are represented in the kernel """ <API key> = 0 for p in self.parts: if not p.is_fixed: part_param_num = len(p.param_array) # number of parameters in the part p.<API key>(gradients[<API key>:(<API key>+part_param_num)]) <API key> += part_param_num def sde(self): F = np.array((0,), ndmin=2) L = np.array((1,), ndmin=2) Qc = np.array((1,), ndmin=2) H = np.array((1,), ndmin=2) Pinf = np.array((1,), ndmin=2) P0 = np.array((1,), ndmin=2) dF = None dQc = None dPinf = None dP0 = None # Assign models for p in self.parts: (Ft,Lt,Qct,Ht,P_inft, P0t, dFt,dQct,dP_inft,dP0t) = p.sde() # check derivative dimensions -> <API key> = len(p.param_array) assert dFt.shape[2] == <API key>, "Dynamic matrix derivative shape is wrong" assert dQct.shape[2] == <API key>, "Diffusion matrix derivative shape is wrong" assert dP_inft.shape[2] == <API key>, "Infinite covariance matrix derivative shape is wrong" # check derivative dimensions <- # exception for periodic kernel if (p.name == 'std_periodic'): Qct = P_inft dQct = dP_inft dF = dkron(F,dF,Ft,dFt,'sum') dQc = dkron(Qc,dQc,Qct,dQct,'prod') dPinf = dkron(Pinf,dPinf,P_inft,dP_inft,'prod') dP0 = dkron(P0,dP0,P0t,dP0t,'prod') F = np.kron(F,np.eye(Ft.shape[0])) + np.kron(np.eye(F.shape[0]),Ft) L = np.kron(L,Lt) Qc = np.kron(Qc,Qct) Pinf = np.kron(Pinf,P_inft) P0 = np.kron(P0,P_inft) H = np.kron(H,Ht) return (F,L,Qc,H,Pinf,P0,dF,dQc,dPinf,dP0) def dkron(A,dA,B,dB, operation='prod'): if dA is None: dA_param_num = 0 dA = np.zeros((A.shape[0], A.shape[1],1)) else: dA_param_num = dA.shape[2] if dB is None: dB_param_num = 0 dB = np.zeros((B.shape[0], B.shape[1],1)) else: dB_param_num = dB.shape[2] # Space allocation for derivative matrix dC = np.zeros((A.shape[0]*B.shape[0], A.shape[1]*B.shape[1], dA_param_num + dB_param_num)) for k in range(dA_param_num): if operation == 'prod': dC[:,:,k] = np.kron(dA[:,:,k],B); else: dC[:,:,k] = np.kron(dA[:,:,k],np.eye( B.shape[0] )) for k in range(dB_param_num): if operation == 'prod': dC[:,:,dA_param_num+k] = np.kron(A,dB[:,:,k]) else: dC[:,:,dA_param_num+k] = np.kron(np.eye( A.shape[0] ),dB[:,:,k]) return dC
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Web; using ServiceStack.Common; using ServiceStack.Html; using ServiceStack.Logging; using ServiceStack.Markdown; using ServiceStack.Text; namespace ServiceStack.WebHost.Endpoints.Support.Markdown { public class PageContext { public PageContext() { } public PageContext(MarkdownPage markdownPage, Dictionary<string, object> scopeArgs, bool renderHtml) { MarkdownPage = markdownPage; ScopeArgs = scopeArgs ?? new Dictionary<string, object>(); RenderHtml = renderHtml; } public MarkdownPage MarkdownPage { get; set; } public Dictionary<string, object> ScopeArgs { get; set; } public bool RenderHtml { get; set; } public PageContext Create(MarkdownPage markdownPage, bool renderHtml) { return new PageContext(markdownPage, ScopeArgs, renderHtml); } } public abstract class TemplateBlock : ITemplateWriter { protected MarkdownPage Page { get; set; } protected Evaluator Evaluator { get; set; } public bool IsNested { get; set; } protected bool WriteRawHtml { get; set; } protected bool RenderHtml { get; set; } //protected PageContext PageContext { get; set; } protected Dictionary<string, object> ScopeArgs { get; set; } protected PageContext CreatePageContext() { return new PageContext(Page, ScopeArgs, RenderHtml); } public void DoFirstRun(PageContext pageContext) { //this.PageContext = pageContext; this.Page = pageContext.MarkdownPage; this.RenderHtml = pageContext.RenderHtml; this.ScopeArgs = pageContext.ScopeArgs; OnFirstRun(); } public void AfterFirstRun(Evaluator evaluator) { this.Evaluator = evaluator; OnAfterFirstRun(); } protected virtual void OnFirstRun() { } protected virtual void OnAfterFirstRun() { } public void AddEvalItem(EvaluatorItem evalItem) { this.Page.ExecutionContext.Items.Add(evalItem); } private const string <API key> = "<p>^"; public string TransformHtml(string markdownText) { var html = Page.Markdown.Transform(markdownText); return CleanHtml(html); } public static string CleanHtml(string html) { // ^ is added before ^<html></html> tags to trick Markdown into not thinking its a HTML // Start tag so it doesn't skip it and encodes the inner body as normal. // We need to Un markdown encode the result i.e. <p>^<div id="searchresults"></p> var pos = 0; var hasEscapedTags = false; while ((pos = html.IndexOf(<API key>, pos, StringComparison.CurrentCulture)) != -1) { hasEscapedTags = true; var endPos = html.IndexOf("</p>", pos, StringComparison.CurrentCulture); if (endPos == -1) return html; //Unexpected Error so skip html = html.Substring(0, endPos) + html.Substring(endPos + 4); pos = endPos; } if (hasEscapedTags) html = html.Replace(<API key>, ""); return html; } public string Transform(string markdownText) { return this.RenderHtml ? TransformHtml(markdownText) : markdownText; } public abstract void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs); } public class TextBlock : TemplateBlock { public TextBlock(string content) { Content = CleanHtml(content); } public string Content { get; set; } public override void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { textWriter.Write(Content); } } public class VarReferenceBlock : TemplateBlock { private readonly string varName; public VarReferenceBlock(string varName) { this.varName = varName; } public override void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { object value = null; scopeArgs.TryGetValue(varName, out value); if (value == null) return; textWriter.Write(value); } } public class MemberExprBlock : TemplateBlock { private static ILog Log = LogManager.GetLogger(typeof(MemberExprBlock)); private string memberExpr; private readonly string modelMemberExpr; private readonly string varName; private bool ReferencesSelf { get { return this.modelMemberExpr == null; } } public MemberExprBlock(string memberExpr) { try { this.memberExpr = memberExpr; this.varName = memberExpr.GetVarName(); this.modelMemberExpr = varName != memberExpr ? memberExpr.Substring(this.varName.Length + 1) : null; } catch (Exception ex) { throw ex; } } private Func<object, string> valueFn; private Func<string> staticValueFn; protected override void OnFirstRun() { base.OnFirstRun(); object memberExprValue; if (ScopeArgs.TryGetValue(this.varName, out memberExprValue)) { InitializeValueFn(memberExprValue); } else { staticValueFn = DataBinder.<API key>(memberExpr); } } private void InitializeValueFn(object memberExprValue) { valueFn = this.ReferencesSelf ? Convert.ToString : DataBinder.CompileToString(memberExprValue.GetType(), modelMemberExpr); } public override void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { object memberExprValue; if (!scopeArgs.TryGetValue(this.varName, out memberExprValue)) { if (staticValueFn != null) { var strValue = this.staticValueFn(); textWriter.Write(HttpUtility.HtmlEncode(strValue)); } else { textWriter.Write(this.memberExpr); } return; } if (memberExprValue == null) return; try { if (memberExprValue is MvcHtmlString) { textWriter.Write(memberExprValue); return; } if (valueFn == null) { InitializeValueFn(memberExprValue); } var strValue = this.ReferencesSelf ? Convert.ToString(memberExprValue) : valueFn(memberExprValue); textWriter.Write(HttpUtility.HtmlEncode(strValue)); } catch (Exception ex) { Log.Error("MemberExprBlock: " + ex.Message, ex); } } } public class StatementExprBlock : TemplateBlock { public StatementExprBlock(string condition, string statement) { this.Condition = condition; this.Statement = statement; this.ChildBlocks = new TemplateBlock[0]; } public string Condition { get; set; } public string Statement { get; set; } public TemplateBlock[] ChildBlocks { get; set; } protected virtual void Prepare(List<StatementExprBlock> allStatements) { if (this.Statement.IsNullOrEmpty()) return; var parsedStatement = Extract(this.Statement, allStatements); var childBlocks = parsedStatement.<API key>(allStatements); childBlocks.ForEach(x => x.IsNested = true); <API key>(childBlocks); this.ChildBlocks = childBlocks.ToArray(); } internal static void <API key>(List<TemplateBlock> childBlocks) { if (childBlocks.Count < 2) return; var lastIndex = childBlocks.Count - 1; if (!(childBlocks[lastIndex - 1] is StatementExprBlock)) return; var textBlock = childBlocks[lastIndex] as TextBlock; if (textBlock == null) return; if (textBlock.Content == "\r\n") { childBlocks.RemoveAt(lastIndex); } } public int Id { get; set; } protected void OnFirstRun(bool applyToChildren) { if (applyToChildren) this.OnFirstRun(); else base.OnFirstRun(); } protected override void OnFirstRun() { base.OnFirstRun(); this.Id = Page.GetNextId(); var pageContext = CreatePageContext(); foreach (var templateBlock in ChildBlocks) { templateBlock.DoFirstRun(pageContext); } } protected override void OnAfterFirstRun() { base.OnAfterFirstRun(); foreach (var templateBlock in ChildBlocks) { templateBlock.AfterFirstRun(this.Evaluator); } } public override void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { WriteInternal(instance, textWriter, scopeArgs); } private void WriteInternal(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { foreach (var templateBlock in ChildBlocks) { templateBlock.Write(instance, textWriter, scopeArgs); } } public static string Extract(string content, List<StatementExprBlock> allStatements) { var sb = new StringBuilder(); var initialCount = allStatements.Count; int pos; var lastPos = 0; while ((pos = content.IndexOf('@', lastPos)) != -1) { var peekChar = content.Substring(pos + 1, 1); var isComment = peekChar == "*"; if (isComment) { var endPos = content.IndexOf("*@", pos); if (endPos == -1) throw new <API key>("Unterminated Comment at charIndex: " + pos); lastPos = endPos + 2; continue; } if (peekChar == "@") { sb.Append('@'); pos += 2; lastPos = pos; continue; } var contentBlock = content.Substring(lastPos, pos - lastPos); var startPos = pos; pos++; var statementExpr = content.<API key>(ref pos); if (statementExpr != null) { contentBlock = contentBlock.<API key>(); sb.Append(contentBlock); if (statementExpr is <API key>) sb.Append(' '); //ensure a spacer between method blocks statementExpr.Prepare(allStatements); allStatements.Add(statementExpr); var placeholder = "@" + TemplateExtensions.<API key> + allStatements.Count; sb.Append(placeholder); lastPos = pos; } else { sb.Append(contentBlock); sb.Append('@'); lastPos = startPos + 1; } } if (lastPos != content.Length - 1) { var lastBlock = lastPos == 0 ? content : content.Substring(lastPos); sb.Append(lastBlock); } return allStatements.Count > initialCount ? sb.ToString() : content; } protected void WriteStatement(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { if (IsNested) { //Write Markdown WriteInternal(instance, textWriter, scopeArgs); } else { //Buffer Markdown output before converting and writing HTML var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { WriteInternal(instance, sw, scopeArgs); } var markdown = sb.ToString(); var html = Transform(markdown); textWriter.Write(html); } } } public class DirectiveBlock : StatementExprBlock { public Type BaseType { get; set; } public Type[] GenericArgs { get; set; } public Dictionary<string, Type> Helpers { get; set; } public string TemplatePath { get; set; } protected Dictionary<string, Func<object, object>> VarDeclarations { get; set; } public Type GetType(string typeName) { var type = Evaluator.FindType(typeName) ?? AssemblyUtils.FindType(typeName); if (type == null) { var parts = typeName.Split(new[] { '<', '>' }); if (parts.Length > 1) { var genericTypeName = parts[0]; var genericArgNames = parts[1].Split(','); var <API key> = genericTypeName + "`" + genericArgNames.Length; var genericDefinition = Type.GetType(<API key>); var argTypes = genericArgNames.Select(AssemblyUtils.FindType).ToArray(); var concreteType = genericDefinition.MakeGenericType(argTypes); type = concreteType; } else { throw new TypeLoadException("Could not load type: " + typeName); } } return type; } public DirectiveBlock(string directive, string line) : base(directive, null) { if (directive == null) throw new <API key>("directive"); if (line == null) throw new <API key>("line"); directive = directive.ToLower(); line = line.Trim(); if (directive == "model") { this.BaseType = typeof(MarkdownViewBase<>); this.GenericArgs = new[] { GetType(line) }; } else if (directive == "inherits") { var parts = line.Split(new[] { '<', '>' }) .Where(x => !x.IsNullOrEmpty()).ToArray(); var isGenericType = parts.Length >= 2; this.BaseType = isGenericType ? GetType(parts[0] + "`1") : GetType(parts[0]); if (isGenericType) { this.GenericArgs = new[] { GetType(parts[1]) }; } } else if (directive == "helper") { var helpers = line.Split(','); this.Helpers = new Dictionary<string, Type>(); foreach (var helper in helpers) { var parts = helper.Split(':'); if (parts.Length != 2) throw new <API key>( "Invalid helper directive, should be 'TagName: Helper.Namespace.And.Type'"); var tagName = parts[0].Trim(); var typeName = parts[1].Trim(); var helperType = GetType(typeName); if (helperType == null) throw new <API key>("Unable to resolve helper type: " + typeName); this.Helpers[tagName] = helperType; } } else if (directive == "template" || directive == "layout") { this.TemplatePath = line.Trim().Trim('"'); } } protected override void OnFirstRun() { base.OnFirstRun(); if (this.BaseType != null) Page.ExecutionContext.BaseType = this.BaseType; Page.ExecutionContext.GenericArgs = this.GenericArgs; if (this.Helpers != null) { foreach (var helper in this.Helpers) { Page.ExecutionContext.TypeProperties[helper.Key] = helper.Value; } } } public override void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { } } public class <API key> : StatementExprBlock { public <API key>(string condition, string statement) : base(condition, statement) { Prepare(); } public string EnumeratorName { get; set; } public string MemberExpr { get; set; } public string MemberVarName { get; set; } private void Prepare() { var parts = Condition.SplitOnWhiteSpace(); if (parts.Length < 3) throw new <API key>("Invalid foreach condition: " + Condition); var i = parts[0] == "var" ? 1 : 0; this.EnumeratorName = parts[i++]; if (parts[i++] != "in") throw new <API key>("Invalid foreach 'in' condition: " + Condition); this.MemberExpr = parts[i++]; this.MemberVarName = this.MemberExpr.GetVarName(); } private object GetModel(Dictionary<string, object> scopeArgs) { object model; if (!scopeArgs.TryGetValue(this.MemberVarName, out model)) throw new ArgumentException(this.MemberVarName + " does not exist"); return model; } private IEnumerable <API key>(object model) { var <API key> = getMemberFn(model) as IEnumerable; if (<API key> == null) throw new ArgumentException(this.MemberExpr + " is not an IEnumerable"); return <API key>; } private Func<object, object> getMemberFn; protected override void OnFirstRun() { base.OnFirstRun(false); var model = GetModel(ScopeArgs); getMemberFn = DataBinder.Compile(model.GetType(), MemberExpr); var <API key> = <API key>(model); var pageContext = CreatePageContext(); foreach (var item in <API key>) { ScopeArgs[this.EnumeratorName] = item; foreach (var templateBlock in ChildBlocks) { templateBlock.DoFirstRun(pageContext); } } } public override void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { var model = GetModel(scopeArgs); var <API key> = <API key>(model); if (IsNested) { //Write Markdown foreach (var item in <API key>) { scopeArgs[this.EnumeratorName] = item; base.Write(instance, textWriter, scopeArgs); } } else { //Buffer Markdown output before converting and writing HTML var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { foreach (var item in <API key>) { scopeArgs[this.EnumeratorName] = item; base.Write(instance, sw, scopeArgs); } } var markdown = sb.ToString(); var renderedMarkup = Transform(markdown); textWriter.Write(renderedMarkup); } } } public class <API key> : StatementExprBlock { public string SectionName { get; set; } public <API key>(string condition, string statement) : base(condition, statement) { Prepare(); } public void Prepare() { this.SectionName = Condition.Trim(); } public override void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { //Don't output anything, capture all output and store it in scopeArgs[SectionName] var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { base.Write(instance, sw, scopeArgs); } var markdown = sb.ToString(); var renderedMarkup = Transform(markdown); scopeArgs[SectionName] = MvcHtmlString.Create(renderedMarkup); } } public abstract class <API key> : StatementExprBlock { protected <API key>(string condition, string statement) : base(condition, statement) { } protected Type ReturnType = typeof(string); private string[] paramNames; protected string CodeGenMethodName { get; set; } public string[] GetParamNames(Dictionary<string, object> scopeArgs) { return this.paramNames ?? (this.paramNames = scopeArgs.Keys.ToArray()); } protected override void OnFirstRun() { base.OnFirstRun(); CodeGenMethodName = "EvalExpr_" + this.Id; var exprParams = GetExprParams(); var evalItem = new EvaluatorItem(ReturnType, CodeGenMethodName, Condition, exprParams); AddEvalItem(evalItem); } protected Dictionary<string, Type> GetExprParams() { var exprParams = new Dictionary<string, Type>(); paramNames = GetParamNames(ScopeArgs); var paramValues = GetParamValues(ScopeArgs); for (var i = 0; i < paramNames.Length; i++) { var paramName = paramNames[i]; var paramValue = paramValues[i]; exprParams[paramName] = paramValue != null ? paramValue.GetType() : typeof(object); } return exprParams; } protected List<object> GetParamValues(IDictionary<string, object> scopeArgs, bool defaultToNullValues) { var results = new List<object>(); foreach (var paramName in paramNames) { object paramValue; if (!scopeArgs.TryGetValue(paramName, out paramValue) && !defaultToNullValues) throw new ArgumentException("Unresolved param " + paramName + " in " + Condition); results.Add(paramValue); } return results; } protected List<object> GetParamValues(IDictionary<string, object> scopeArgs) { return GetParamValues(scopeArgs, false); } public T Evaluate<T>(Dictionary<string, object> scopeArgs, bool defaultToNullValues) { var paramValues = GetParamValues(scopeArgs, defaultToNullValues); return (T)Evaluator.Evaluate(CodeGenMethodName, paramValues.ToArray()); } public T Evaluate<T>(Dictionary<string, object> scopeArgs) { return Evaluate<T>(scopeArgs, true); } } public class <API key> : <API key> { private string varName; private string memberExpr; public <API key>(string directive, string line) : base(line, null) { if (directive != "var") throw new ArgumentException("Expected 'var' got: " + directive); this.ReturnType = typeof(object); } protected override void OnFirstRun() { if (varName != null) return; var declaration = Condition.TrimEnd().TrimEnd(';'); var parts = declaration.Split('='); if (parts.Length != 2) throw new <API key>( "Invalid var declaration, should be '@var varName = {MemberExpression} [, {VarDeclaration}]' was: " + declaration); varName = parts[0].Trim(); memberExpr = parts[1].Trim(); this.Condition = memberExpr; const string methodName = "resolveVarType"; var exprParams = GetExprParams(); var evaluator = new Evaluator(ReturnType, Condition, methodName, exprParams); var result = evaluator.Evaluate(methodName, GetParamValues(ScopeArgs).ToArray()); ScopeArgs[varName] = result; if (result != null) this.ReturnType = result.GetType(); base.OnFirstRun(); } public override void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { //Resolve and add to ScopeArgs var resultCondition = Evaluate<object>(scopeArgs, true); scopeArgs[varName] = resultCondition; } } public class <API key> : <API key> { public string ElseStatement { get; set; } public <API key>(string condition, string statement, string elseStatement) : base(condition, statement) { this.ReturnType = typeof(bool); this.ElseStatement = elseStatement; this.ElseChildBlocks = new TemplateBlock[0]; } public TemplateBlock[] ElseChildBlocks { get; set; } protected override void Prepare(List<StatementExprBlock> allStatements) { base.Prepare(allStatements); if (this.ElseStatement.IsNullOrEmpty()) return; var parsedStatement = Extract(this.ElseStatement, allStatements); var elseChildBlocks = parsedStatement.<API key>(allStatements); elseChildBlocks.ForEach(x => x.IsNested = true); <API key>(elseChildBlocks); this.ElseChildBlocks = elseChildBlocks.ToArray(); } public override void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { var resultCondition = Evaluate<bool>(scopeArgs); if (resultCondition) { WriteStatement(instance, textWriter, scopeArgs); } else { if (ElseStatement != null && this.ElseChildBlocks.Length > 0) { WriteElseStatement(instance, textWriter, scopeArgs); } } } protected override void OnFirstRun() { base.OnFirstRun(); var pageContext = CreatePageContext(); foreach (var templateBlock in ElseChildBlocks) { templateBlock.DoFirstRun(pageContext); } } //TODO: DRY IT protected void WriteElseStatement(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { if (IsNested) { //Write Markdown foreach (var templateBlock in ElseChildBlocks) { templateBlock.Write(instance, textWriter, scopeArgs); } } else { //Buffer Markdown output before converting and writing HTML var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { foreach (var templateBlock in ElseChildBlocks) { templateBlock.Write(instance, sw, scopeArgs); } } var markdown = sb.ToString(); var html = Transform(markdown); textWriter.Write(html); } } } public class <API key> : <API key> { public <API key>(string methodExpr, string condition, string statement) : base(condition, statement) { this.methodExpr = methodExpr; } private readonly string methodExpr; protected override void OnFirstRun() { Prepare(Page); base.OnFirstRun(); } public string DependentPageName { get; private set; } private void Prepare(MarkdownPage markdownPage) { var rawMethodExpr = methodExpr.Replace("Html.", ""); if (rawMethodExpr == "Partial") { this.DependentPageName = this.Condition.ExtractContents("\"", "\""); } this.WriteRawHtml = rawMethodExpr == "Raw"; var parts = methodExpr.Split('.'); if (parts.Length > 2) throw new ArgumentException("Unable to resolve method: " + methodExpr); var usesBaseType = parts.Length == 1; var typePropertyName = parts[0]; var methodName = usesBaseType ? parts[0] : parts[1]; Type type = null; if (typePropertyName == "Html") { type = markdownPage.ExecutionContext.BaseType.HasGenericType() ? typeof(HtmlHelper<>) : typeof(HtmlHelper); } if (type == null) { type = usesBaseType ? markdownPage.ExecutionContext.BaseType : markdownPage.Markdown.<API key>.TryGetValue(typePropertyName, out type) ? type : null; } if (type == null) throw new <API key>(string.Format( "Unable to resolve type '{0}'. Check type exists in Config.MarkdownBaseType or Page.Markdown.<API key>", typePropertyName)); try { var mi = methodName == "Partial" ? type.GetMethods(BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(m => m.GetParameters().Length == 2 && m.Name == methodName) : type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance); if (mi == null) { mi = HtmlHelper.GetMethod(methodName); if (mi == null) throw new ArgumentException("Unable to resolve method '" + methodExpr + "' on type " + type.Name); } base.ReturnType = mi.ReturnType; } catch (Exception ex) { throw; } var isMemberExpr = Condition.IndexOf('(') != -1; if (!isMemberExpr || this.WriteRawHtml) { base.Condition = methodExpr + "(" + Condition + ")"; } } public override void Write(MarkdownViewBase instance, TextWriter textWriter, Dictionary<string, object> scopeArgs) { var paramValues = GetParamValues(scopeArgs); var result = Evaluator.Evaluate(instance, CodeGenMethodName, paramValues.ToArray()); if (result == null) return; string strResult; var mvcString = result as MvcHtmlString; if (mvcString != null) { WriteRawHtml = true; strResult = mvcString.ToHtmlString(); } else { strResult = result as string ?? Convert.ToString(result); } if (!WriteRawHtml) strResult = HttpUtility.HtmlEncode(strResult); textWriter.Write(strResult); } } }
<?php namespace System\Form\User; use Home\Form\FormBase; use Home\Model\DateBase; use Zend\Form\Element\Text; use Zend\Form\Element\Hidden; use Zend\Form\Element\Textarea; use Zend\Form\Element\Select; use Zend\Form\Element\Date; use ZendX\Form\Element\DisplayGroup; use Zend\Validator\StringLength; use Zend\Uri\UriFactory; use Zend\Form\Element\Password; class Add extends FormBase{ /** * @param null|string $name */ public function __construct($serviceLocator, $options=null){ parent::__construct('fUserAdd'); $this->setServiceLocator($serviceLocator); $this->setAttribute('method', 'post'); $filter = $this->getInputFilter(); $groupBasic = new DisplayGroup('groupBasic'); $groupBasic->setLabel('Thông tin cơ bản'); $this->add($groupBasic); $username = new Text('username'); $username->setLabel('Tên đăng nhập:'); $username->setAttributes([ 'maxlength' => 50, 'autocomplete' => 'off' ]); $this->add($username); $groupBasic->addElement($username); $filter->add(array( 'name' => 'username', 'required' => true, 'filters' => array( array('name' => 'StringTrim'), array('name' => 'StringToLower') ), 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa nhập tên đăng nhập' ) ) ), array( 'name' => 'StringLength', '<API key>' => true, 'options' => array( 'max' => 50, 'min' => 4, 'messages' => array( StringLength::TOO_LONG => 'Tên đăng nhập giới hạn 4-50 kí tự', StringLength::TOO_SHORT => 'Tên đăng nhập giới hạn 4-50 kí tự' ) ) ), array( 'name' => 'Regex', '<API key>' => true, 'options' => array( 'pattern' => "/^[a-z0-9_-]{4,32}$/", 'messages' => array( 'regexNotMatch' => 'Chỉ chấp nhận các kí tự là chữ, chữ số, dấu - và dấu _' ) ), ), array( 'name' => 'Db\NoRecordExists', 'options' => array( 'table' => 'users', 'field' => 'username', 'adapter' => \Zend\Db\TableGateway\Feature\<API key>::getStaticAdapter(), 'messages' => array( 'recordFound' => "Tên đăng nhập này đã được sử dụng" ) ), ), ), )); $fulName = new Text('fullName'); $fulName->setLabel('Họ tên:'); $fulName->setAttributes([ 'maxlength' => 255, 'autocomplete' => 'off' ]); $this->add($fulName); $groupBasic->addElement($fulName); $filter->add(array( 'name' => 'fullName', 'required' => true, 'filters' => array( array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa nhập họ tên' ) ) ), array( 'name' => 'StringLength', '<API key>' => true, 'options' => array( 'max' => 255, 'min' => 4, 'messages' => array( StringLength::TOO_LONG => 'Tên đăng nhập giới hạn 4-250 kí tự', StringLength::TOO_SHORT => 'Tên đăng nhập giới hạn 4-250 kí tự' ) ) ), ), )); $email = new Text('email'); $email->setLabel('Email:'); $email->setAttributes([ 'maxlength' => 255, 'autocomplete' => 'off' ]); $this->add($email); $groupBasic->addElement($email); $filter->add(array( 'name' => 'email', 'required' => true, 'filters' => array( array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa nhập email' ) ) ), array( 'name' => 'StringLength', '<API key>' => true, 'options' => array( 'max' => 50, 'min' => 4, 'messages' => array( StringLength::TOO_LONG => 'Tên đăng nhập giới hạn 4-50 kí tự', StringLength::TOO_SHORT => 'Tên đăng nhập giới hạn 4-50 kí tự' ) ) ), array( 'name' => 'EmailAddress', '<API key>' => true, 'options' => array( 'messages' => array( '<API key>' => 'Địa chỉ email không hợp lệ' ) ) ), array( 'name' => 'Db\NoRecordExists', 'options' => array( 'table' => 'users', 'field' => 'email', 'adapter' => \Zend\Db\TableGateway\Feature\<API key>::getStaticAdapter(), 'messages' => array( 'recordFound' => "Email này đã được sử dụng" ) ), ), ), )); $user = new \User\Model\User(); $role = new Select('role'); $role->setLabel('Phân quyền:'); $role->setValueOptions(['' => '- Phân quyền -'] + $user->getRoleDisplays()); $this->add($role); $groupBasic->addElement($role); $filter->add(array( 'name' => 'role', 'required' => true, 'filters' => array( array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa chọn Phân quyền' ) ) ), ), )); $password = new Password('password'); $password->setLabel('Mật khẩu:'); $password->setAttributes([ 'maxlength' => 32, 'autocomplete' => 'off' ]); $this->add($password); $groupBasic->addElement($password); $filter->add(array( 'name' => 'password', 'required' => true, 'filters' => array( array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa nhập Mật khẩu' ) ) ), array( 'name' => 'StringLength', '<API key>' => true, 'options' => array( 'max' => 32, 'min' => 6, 'messages' => array( StringLength::TOO_LONG => 'Mật khẩu giới hạn 6-32 kí tự', StringLength::TOO_SHORT => 'Mật khẩu giới hạn 6-32 kí tự' ) ) ), ), )); $rePassword = new Password('rePassword'); $rePassword->setLabel('Nhập lại Mật khẩu:'); $rePassword->setAttributes([ 'maxlength' => 32, 'autocomplete' => 'off' ]); $this->add($rePassword); $groupBasic->addElement($rePassword); $filter->add(array( 'name' => 'rePassword', 'required' => true, 'filters' => array( array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa nhập lại Mật khẩu' ) ) ), array( 'name' => 'StringLength', '<API key>' => true, 'options' => array( 'max' => 32, 'min' => 6, 'messages' => array( StringLength::TOO_LONG => 'Mật khẩu giới hạn 6-32 kí tự', StringLength::TOO_SHORT => 'Mật khẩu giới hạn 6-32 kí tự' ) ) ), array( 'name' => 'Identical', '<API key>' => true, 'options' => array( 'token' => 'password', 'messages' => array( 'notSame' => 'Xác nhận mật khẩu không chính xác' ) ), ), ), )); $mobile = new Text('mobile'); $mobile->setLabel('Mobile:'); $mobile->setAttributes([ 'maxlength' => 15 ]); $mobile->setOptions([ 'leftIcon' => 'fa fa-mobile' ]); $this->add($mobile); $groupBasic->addElement($mobile); $filter->add(array( 'name' => 'mobile', 'required' => false, 'filters' => array( array('name' => 'StringTrim'), array('name' => 'Digits') ), 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa nhập Mobile' ) ) ), array( 'name' => 'StringLength', '<API key>' => true, 'options' => array( 'min' => 10, 'max' => 11, 'messages' => array( StringLength::INVALID => 'Mobile phải là dạng 10 hoặc 11 chữ số', StringLength::TOO_SHORT => 'Mobile phải là dạng 10 hoặc 11 chữ số', StringLength::TOO_LONG => 'Mobile phải là dạng 10 hoặc 11 chữ số' ) ) ), ), )); // group additional $groupAdditional = new DisplayGroup('groupAdditional'); $groupAdditional->setLabel('Thông tin cá nhân'); $this->add($groupAdditional); $gender = new Select('gender'); $this->add($gender); $groupAdditional->addElement($gender); $gender->setLabel('Giới tính:'); $gender->setValueOptions(array( '' => '- Giới tính -', \Home\Model\Consts::GENDER_MALE => 'Nam', \Home\Model\Consts::GENDER_FEMALE => 'Nữ', )); $filter->add(array( 'name' => 'gender', 'required' => false, 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa nhập Giới tính' ) ) ), ), )); $birthdate = new Text('birthdate'); $birthdate->setLabel('Ngày sinh:'); $birthdate->setAttributes([ 'class' => 'datetimepicker', 'data-date-format'=>"DD/MM/YYYY" ]); $birthdate->setOptions([ 'leftIcon' => 'fa fa-calendar' ]); $this->add($birthdate); $groupAdditional->addElement($birthdate); $filter->add(array( 'name' => 'birthdate', 'required' => false, 'filters' => array( array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'Date', '<API key>' => true, 'options' => array( 'format' => DateBase::<API key>(), 'messages' => array( 'dateInvalid' => 'Ngày sinh không hợp lệ', 'dateInvalidDate' => 'Ngày sinh không hợp lệ', 'dateFalseFormat' => 'Ngày sinh không hợp lệ' ) ) ), ), )); $cityId = new Select('cityId'); $cityId->setLabel('Thành phố:'); $cityId->setValueOptions(array( '' => '- Thành phố -' )); $this->add($cityId); $groupAdditional->addElement($cityId); $filter->add(array( 'name' => 'cityId', 'required' => false, 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa nhập thành phố' ) ) ), array( 'name' => 'StringLength', '<API key>' => true, 'options' => array( 'max' => 250, 'messages' => array( StringLength::INVALID => 'Địa chỉ chỉ giới hạn nhỏ hơn 250 kí tự', ) ) ), ), )); $districtId = new Select('districtId'); $districtId->setLabel('Quận huyện:'); $districtId->setValueOptions(array( '' => '- Quận huyện -' )); $this->add($districtId); $groupAdditional->addElement($districtId); $filter->add(array( 'name' => 'districtId', 'required' => false, 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa nhập thành phố' ) ) ), ), )); $address = new Text('address'); $address->setLabel('Địa chỉ:'); $address->setAttributes([ 'maxlength' => 255 ]); $this->add($address); $groupAdditional->addElement($address); $filter->add(array( 'name' => 'address', 'required' => false, 'filters' => array( array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'NotEmpty', '<API key>' => true, 'options' => array( 'messages' => array( 'isEmpty' => 'Bạn chưa nhập địa chỉ' ) ) ), ), )); $this->add(array( 'name' => 'afterSubmit', 'type' => 'radio', 'attributes' => array( 'value' => '/system/user/add', ), 'options' => array( 'layout' => 'fluid', 'clearBefore' => true, 'label' => 'Sau khi lưu dữ liệu:', 'value_options' => array( '/system/user/add' => 'Tiếp tục nhập người dùng', '/system/user/index' => 'Hiện danh sách người dùng', ), ), )); $this->add(array( 'name' => 'submit', 'options' => array( 'clearBefore' => true ), 'attributes' => array( 'type' => 'submit', 'value' => 'Lưu', 'id' => 'btnSaveCrmContact', 'class' => 'btn btn-primary' ), )); } public function setCities($arr) { $this->get('cityId')->setValueOptions(['' => '- Thành phố -'] + $arr); } public function setDistricts($arr) { $this->get('districtId')->setValueOptions(['' => '- Quận huyện -'] + $arr); } public function isValid(){ $isVaild = parent::isValid(); if($isVaild){ $user = new \User\Model\User(); $user->exchangeArray($this->getData()); $userMapper = $this->getServiceLocator()->get('\User\Model\UserMapper'); if($userMapper->isExisted($user)){ $this->get('username')->setMessages(['Tên tài khoản hoặc email này đã được sử dụng']); $isVaild = false; } } return $isVaild; } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.c Label Definition File: <API key>.label.xml Template File: sources-sinks-22a.tmpl.c */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated * BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources. * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifndef OMITBAD /* The global variable below is used to drive control flow in the sink function */ int <API key> = 0; void <API key>(size_t data); void <API key>() { size_t data; /* Initialize data */ data = 0; /* POTENTIAL FLAW: Read data from the console using fscanf() */ fscanf(stdin, "%zu", &data); <API key> = 1; /* true */ <API key>(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* The global variables below are used to drive control flow in the sink functions. */ int <API key> = 0; int <API key> = 0; int <API key> = 0; /* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ void <API key>(size_t data); static void goodB2G1() { size_t data; /* Initialize data */ data = 0; /* POTENTIAL FLAW: Read data from the console using fscanf() */ fscanf(stdin, "%zu", &data); <API key> = 0; /* false */ <API key>(data); } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */ void <API key>(size_t data); static void goodB2G2() { size_t data; /* Initialize data */ data = 0; /* POTENTIAL FLAW: Read data from the console using fscanf() */ fscanf(stdin, "%zu", &data); <API key> = 1; /* true */ <API key>(data); } /* goodG2B() - use goodsource and badsink */ void <API key>(size_t data); static void goodG2B() { size_t data; /* Initialize data */ data = 0; /* FIX: Use a relatively small number for memory allocation */ data = 20; <API key> = 1; /* true */ <API key>(data); } void <API key>() { goodB2G1(); goodB2G2(); goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); <API key>(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); <API key>(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
<!DOCTYPE html> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="<API key>+<API key>" crossorigin="anonymous"> <html lang="pt-br"> <head> <title>Editar Modelo</title> <meta charset="UTF-8"> </head> <body> <h2>Novo Modelo</h2> <form action="Modelo.html"> <label>Nome do Modelo: </label> <input type="text" placeholder="Digite o nome do modelo"></input> <label>Marca: </label> <select> <option>Marca 01</option> <option>Marca 02</option> <option>Marca 03</option> <option>Marca 04</option> </select> <input type="submit" class="btn btn-primary" value="Salvar" /> <input type="submit" class="btn btn-primary" value="Cancelar" /> </form> </body> </html>
#ifndef <API key> #ifdef __cplusplus #define <API key> extern "C" #else #define <API key> #endif #ifdef _WIN32 #ifdef <API key> #define <API key> <API key> __declspec(dllexport) #else #define <API key> <API key> __declspec(dllimport) #endif #else #define <API key> <API key> #endif #endif
<?php ?> <style type="text/css"> .form-control{ width: 30%; } </style> <link href="css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" media="all" href="css/daterangepicker-bs3.css"/> <div class="row wrapper border-bottom white-bg page-heading title"> <div class="col-lg-10"> <h2>-</h2> </div> </div> <div class="row"> <div class="col-lg-12 animated fadeInRight"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5></h5> </div> <div class="ibox-content"> <form method="post" class="form-horizontal" id="signupForm" > <input type="hidden" class="id_data" value="<?=$user['id']?>"> <div class="form-group"> <label class="col-sm-2 control-label"></label> <div class="col-sm-10"> <input type="text" class="form-control name_data" value="<?=$user['name']?>" name="name" > </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"></label> <div class="col-sm-9"> <label class="radio-inline"><input type="radio" class="sex_data" <?=$user['sex'] == 1 ? "checked" : ""?> value="1" name="sex"></label> <label class="radio-inline"><input type="radio" class="sex_data" <?=$user['sex'] != 1 ? "checked" : ""?> value="2" name="sex"></label> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"></label> <div class="col-sm-10"> <input type="text" class="form-control phone_data" value="<?=$user['phone']?>" name="phone" > </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"></label> <div class="col-sm-10"> <input type="text" class="form-control passport_data" value="<?=$user['passport']?>" name="passport" > </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"></label> <div class="col-sm-10"> <input type="text" class="form-control date birth_data" value="<?=date("m/d/Y",$user['birth'])?>" name="birth" > </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">(HN)</label> <div class="col-sm-10"> <input type="text" class="form-control cases_data" value="<?=$user['cases_code']?>" name="hn" > </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"></label> <select style="width: 90px;float: left;" class="form-control m-b brand_data" name="brand"> <option value="0"></option> <?php if(isset($brands) && $brands) foreach($brands as $v):?> <option <?php if($user['brand_id'] == $v['id']) echo "selected=selected";?> value="<?=$v['id']?>"><?=$v['name']?></option> <?php endforeach;?> </select> </div> <div class="form-group"> <label class="col-sm-2 control-label"></label> <div class="col-sm-10" > <select style="width: 90px;float: left;" class="form-control m-b area_data" name=""> <option value="0"></option> <?php if($area_higher) foreach ($area_higher as $higher):?> <option <?=$higher['id'] == $user['area_higher_id'] ? 'selected=true' : ''?> value="<?=$higher['id']?>"><?=$higher['name']?></option> <?php endforeach;?> </select> <select style="width: 90px;float: left;margin-left: 10px;" class="form-control m-b area_lower_data" name="area_id"> <?php if($area_lower) foreach ($area_lower as $lower):?> <option <?=$lower['id'] == $user['area_id'] ? 'selected=true' : ''?> value="<?=$lower['id']?>"><?=$lower['name']?></option> <?php endforeach;?> </select> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" ></label> <div class="col-sm-10"> <input disabled type="text" class="form-control date" value="<?=date("m/d/Y",$user['start_time_mgu'])?>" name="star_time" > </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"></label> <div class="col-sm-10"> <input disabled type="text" class="form-control date" value="<?=date("m/d/Y",$user['end_time_mgu'])?>" name="end_time" > </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"></label> <div class="col-sm-10"> <input disabled type="text" class="form-control" value="<?php if($user['end_time_mgu'] < time()) echo ""; else if($user['start_time_mgu'] > time()) echo ""; else echo ""; ?>" name="status" > </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <div class="col-sm-4 col-sm-offset-3"> <a href="<?=\yii\helpers\Url::toRoute("users/list")?>" class="btn btn-primary" type="submit"></a> <button class="btn btn-primary form_commit"></button> <?php if($user['last_mgu']):?> <a href="<?=\yii\helpers\Url::toRoute("mgu/mgu_detail") . "&mgu_id=" . $user['last_mgu']?>" class="btn btn-primary" ></a> <?php endif;?> <a <a href="<?=\yii\helpers\Url::toRoute("mgu/user_join_group") . "&user_id=" . $user['id']?>" class="btn btn-primary" ></a> </div> </div> </form> </div> </div> </div> </div> <!-- jQuery Validation plugin javascript--> <script src="js/plugins/validate/jquery.validate.min.js"></script> <script src="js/plugins/validate/messages_zh.min.js"></script> <script type="text/javascript" src="js/moment.min.js"></script> <script type="text/javascript" src="js/daterangepicker.js"></script> <script type="text/javascript"> //jQuery ValidationBootstrap $.validator.setDefaults({ highlight: function (element) { $(element).closest('.form-group').removeClass('has-success').addClass('has-error'); }, success: function (element) { element.closest('.form-group').removeClass('has-error').addClass('has-success'); }, errorElement: "span", errorClass: "help-block m-b-none", validClass: "help-block m-b-none" }); $().ready(function () { // validate the comment form when it is submitted // validate signup form on keyup and submit $("#signupForm").validate({ rules: { name: "required", phone: { required:true, phone:true }, passport: { passport:true }, birth: { mydate:true }, brand: { required:true }, area:{ myarea:true, } }, messages: { name: "", age: "", birth: { required: "", }, }, submitHandler:function(){ add_commit() } }); }); $(document).ready(function() { var mydate = new Date('01/01/1980'); var str = "" + (mydate.getMonth()+1) + "/"; str += mydate.getDate() + "/"; str += mydate.getFullYear(); $('.date').daterangepicker({ singleDatePicker: true, startDate: str, }, function(start, end, label) { }); }); $("body").on("change",".area_data",function(){ var area_id = $(this).val(); var url = "<?=\yii\helpers\Url::toRoute("area/area_select")?>"; var data = { id : area_id }; if(data.id != 0){ $.get(url,data,function(msg){ $(".area_lower_data").val(0); $(".area_lower_data").empty(); $(".area_lower_data").html(msg); }) }else{ $(".area_lower_data").val(0); $(".area_lower_data").empty(); } }); function add_commit(){ var url = "<?=\yii\helpers\Url::toRoute("users/save")?>"; var data = { id : $(".id_data").val(), name : $(".name_data").val(), sex : $(".sex_data:checked").val(), phone : $(".phone_data").val(), passport : $(".passport_data").val(), birth : $(".birth_data").val(), cases_code : $(".cases_data").val(), brand_id : $(".brand_data").val(), area_id : $(".area_lower_data").val(), }; console.log(data); $.post(url,data,function(msg){ if(msg.status){ alert(""); location.href = "<?=\yii\helpers\Url::toRoute("users/list")?>"; }else{ alert(msg.error); } },'json') } </script>
package edu.wpi.first.wpilibj.templates.commands; /** * * @author bradmiller */ public class TelopDriveCommand extends CommandBase { public TelopDriveCommand() { requires(DriveSubsystem); } // Called just before this Command runs the first time protected void initialize() { DriveSubsystem.init(); } // Called repeatedly when this Command is scheduled to run protected void execute() { DriveSubsystem.telopDrive(); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
package rogue.creature; import java.util.Collection; import jade.fov.RayCaster; import jade.fov.ViewField; import jade.ui.Camera; import jade.ui.Terminal; import jade.util.datatype.ColoredChar; import jade.util.datatype.Coordinate; import jade.util.datatype.Direction; public class Player extends Creature implements Camera { private Terminal term; private ViewField fov; public Player(Terminal term) { super(ColoredChar.create('@')); this.term = term; fov = new RayCaster(); } @Override public void act() { try { char key; key = term.getKey(); switch(key) { case 'q': expire(); break; case 'l': System.out.println("<API key>"); // Do not break; here, otherwise we can't move left! default: Direction dir = Direction.keyToDir(key); if(dir != null) move(dir); System.out.println("Softwarepraktikum"); break; } } catch(<API key> e) { e.printStackTrace(); } } @Override public Collection<Coordinate> getViewField() { return fov.getViewField(world(), pos(), 5); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the project nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Windows.Threading; namespace Vacuum.Core { public interface IDispatchHandler { void Delegate (Action call); } internal class DispatchHandler : IDispatchHandler { #region Fields private readonly Dispatcher _dispatcher; #endregion #region Constructors public DispatchHandler (Dispatcher dispatcher) { _dispatcher = dispatcher; } #endregion #region IDispatchHandler Members public void Delegate (Action call) { if (_dispatcher.CheckAccess ()) { call (); } else { _dispatcher.Invoke (call); } } #endregion } }
package com.groupon.lex.metrics.timeseries; import com.groupon.lex.metrics.GroupName; import com.groupon.lex.metrics.Histogram; import com.groupon.lex.metrics.Histogram.RangeWithCount; import com.groupon.lex.metrics.MetricName; import com.groupon.lex.metrics.MetricValue; import com.groupon.lex.metrics.SimpleGroupPath; import java.util.Arrays; import static java.util.Collections.EMPTY_LIST; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import java.util.Optional; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Duration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import static org.mockito.Mockito.when; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class InterpolatedTSCTest { @Mock private TimeSeriesValue pastValue, futureValue, presentValue; private static final GroupName TESTGROUP = GroupName.valueOf("test"); private static final MetricName TESTMETRIC = MetricName.valueOf("metric"); private final DateTime pastDate = new DateTime(1970, 1, 1, 0, 0, DateTimeZone.UTC); private final DateTime futureDate = new DateTime(1970, 1, 1, 1, 0, DateTimeZone.UTC); /** * One quarter after pastDate, three quarters before futureDate. */ private final DateTime midDate = new DateTime(1970, 1, 1, 0, 15, DateTimeZone.UTC); private <API key> past, future; @Before public void setup() { when(pastValue.getGroup()).thenReturn(TESTGROUP); when(futureValue.getGroup()).thenReturn(TESTGROUP); when(presentValue.getGroup()).thenReturn(TESTGROUP); when(pastValue.getTags()).thenReturn(TESTGROUP.getTags()); when(futureValue.getTags()).thenReturn(TESTGROUP.getTags()); when(pastValue.findMetric(Mockito.any())).thenCallRealMethod(); when(futureValue.findMetric(Mockito.any())).thenCallRealMethod(); past = new <API key>(pastDate, singletonList(pastValue)); future = new <API key>(futureDate, singletonList(futureValue)); } @Test public void interpolateBoolean() { when(pastValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromBoolean(false))); when(futureValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromBoolean(true))); InterpolatedTSC interpolatedTSC = new InterpolatedTSC(new <API key>(midDate), singletonList(past), singletonList(future)); assertTrue(interpolatedTSC.get(TESTGROUP).isPresent()); assertEquals(TESTGROUP, interpolatedTSC.get(TESTGROUP).get().getGroup()); assertEquals(Optional.of(MetricValue.fromDblValue(0.25)), interpolatedTSC.get(TESTGROUP).get().findMetric(TESTMETRIC)); } @Test public void interpolateInteger() { when(pastValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromIntValue(4))); when(futureValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromIntValue(8))); InterpolatedTSC interpolatedTSC = new InterpolatedTSC(new <API key>(midDate), singletonList(past), singletonList(future)); assertTrue(interpolatedTSC.get(TESTGROUP).isPresent()); assertEquals(TESTGROUP, interpolatedTSC.get(TESTGROUP).get().getGroup()); assertEquals(Optional.of(MetricValue.fromDblValue(5)), interpolatedTSC.get(TESTGROUP).get().findMetric(TESTMETRIC)); } @Test public void <API key>() { when(pastValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromDblValue(4.9))); when(futureValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromDblValue(8.9))); InterpolatedTSC interpolatedTSC = new InterpolatedTSC(new <API key>(midDate), singletonList(past), singletonList(future)); assertTrue(interpolatedTSC.get(TESTGROUP).isPresent()); assertEquals(TESTGROUP, interpolatedTSC.get(TESTGROUP).get().getGroup()); assertEquals(Optional.of(MetricValue.fromDblValue(5.9)), interpolatedTSC.get(TESTGROUP).get().findMetric(TESTMETRIC)); } @Test public void interpolateString() { when(pastValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromStrValue("foo"))); when(futureValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromStrValue("bar"))); InterpolatedTSC interpolatedTSC = new InterpolatedTSC(new <API key>(midDate), singletonList(past), singletonList(future)); assertTrue(interpolatedTSC.get(TESTGROUP).isPresent()); assertEquals(TESTGROUP, interpolatedTSC.get(TESTGROUP).get().getGroup()); assertEquals(Optional.of(MetricValue.fromStrValue("foo")), interpolatedTSC.get(TESTGROUP).get().findMetric(TESTMETRIC)); } @Test public void <API key>() { when(pastValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromHistValue(new Histogram(new RangeWithCount(0, 10, 4))))); when(futureValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromHistValue(new Histogram(new RangeWithCount(0, 10, 8))))); InterpolatedTSC interpolatedTSC = new InterpolatedTSC(new <API key>(midDate), singletonList(past), singletonList(future)); assertTrue(interpolatedTSC.get(TESTGROUP).isPresent()); assertEquals(TESTGROUP, interpolatedTSC.get(TESTGROUP).get().getGroup()); assertEquals(Optional.of(MetricValue.fromHistValue(new Histogram(new RangeWithCount(0, 10, 5)))), interpolatedTSC.get(TESTGROUP).get().findMetric(TESTMETRIC)); } @Test public void <API key>() { <API key> present = new <API key>(midDate, singletonList(new <API key>(GroupName.valueOf("mid", "point"), emptyMap()))); InterpolatedTSC interpolatedTSC = new InterpolatedTSC(present, singletonList(past), singletonList(future)); assertThat(interpolatedTSC.getGroups(x -> true), containsInAnyOrder(TESTGROUP, GroupName.valueOf("mid", "point"))); assertThat(interpolatedTSC.getGroupPaths(x -> true), containsInAnyOrder(TESTGROUP.getPath(), SimpleGroupPath.valueOf("mid", "point"))); } @Test public void <API key>() { <API key> present = new <API key>(midDate, singletonList(presentValue)); InterpolatedTSC interpolatedTSC = new InterpolatedTSC(present, singletonList(past), singletonList(future)); assertThat(interpolatedTSC.getGroups(x -> true), contains(TESTGROUP)); assertThat(interpolatedTSC.getGroupPaths(x -> true), contains(TESTGROUP.getPath())); assertSame(presentValue, interpolatedTSC.get(TESTGROUP).get()); } @Test(expected = <API key>.class) public void <API key>() { new InterpolatedTSC(new <API key>(pastDate.minus(Duration.standardDays(1))), singletonList(past), singletonList(future)); } @Test(expected = <API key>.class) public void <API key>() { new InterpolatedTSC(new <API key>(futureDate.plus(Duration.standardDays(1))), singletonList(past), singletonList(future)); } @Test(expected = <API key>.class) public void <API key>() { new InterpolatedTSC(new <API key>(futureDate.plus(Duration.standardDays(1))), Arrays.asList(past, future), EMPTY_LIST); } @Test(expected = <API key>.class) public void <API key>() { new InterpolatedTSC(new <API key>(pastDate.minus(Duration.standardDays(1))), EMPTY_LIST, Arrays.asList(future, past)); } @Test public void equality() { when(pastValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromIntValue(4))); when(futureValue.getMetrics()).thenReturn(singletonMap(TESTMETRIC, MetricValue.fromIntValue(8))); final <API key> expected = new <API key>(midDate, singletonList(new <API key>(TESTGROUP, singletonMap(TESTMETRIC, MetricValue.fromDblValue(5))))); InterpolatedTSC interpolatedTSC = new InterpolatedTSC(new <API key>(midDate), singletonList(past), singletonList(future)); assertEquals(expected.hashCode(), interpolatedTSC.hashCode()); assertTrue(interpolatedTSC.equals(expected)); assertTrue(expected.equals(interpolatedTSC)); } }
package gov.hhs.fha.nhinc.redactionengine.adapter; import gov.hhs.fha.nhinc.common.nhinccommonadapter.<API key>; import gov.hhs.fha.nhinc.policyengine.adapter.pip.CDAConstants; import gov.hhs.fha.nhinc.util.HomeCommunityMap; import gov.hhs.fha.nhinc.util.format.PatientIdFormatUtil; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest; import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryResponse; import oasis.names.tc.ebxml_regrep.xsd.rim._3.AdhocQueryType; import oasis.names.tc.ebxml_regrep.xsd.rim._3.ClassificationType; import oasis.names.tc.ebxml_regrep.xsd.rim._3.<API key>; import oasis.names.tc.ebxml_regrep.xsd.rim._3.ExtrinsicObjectType; import oasis.names.tc.ebxml_regrep.xsd.rim._3.IdentifiableType; import oasis.names.tc.ebxml_regrep.xsd.rim._3.<API key>; import oasis.names.tc.ebxml_regrep.xsd.rim._3.SlotType1; import oasis.names.tc.ebxml_regrep.xsd.rim._3.ValueListType; import oasis.names.tc.ebxml_regrep.xsd.rim._3.ObjectFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author Neil Webb */ public class <API key> { private static final String <API key> = "$<API key>"; private static final String <API key> = "urn:uuid:<API key>"; private Log log = null; private String patientId; private String <API key>; private String homeCommunityId; public <API key>() { log = createLogger(); } protected Log createLogger() { return LogFactory.getLog(getClass()); } protected <API key> <API key>() { return new <API key>(); } protected void setPatientId(String patientId) { this.patientId = patientId; } protected String getPatientId() { return patientId; } protected void <API key>(String <API key>) { this.<API key> = <API key>; } protected String <API key>() { return <API key>; } protected void setHomeCommunityId(String homeCommunityId) { this.homeCommunityId = homeCommunityId; } protected String getHomeCommunityId() { return homeCommunityId; } public AdhocQueryResponse <API key>(AdhocQueryRequest adhocQueryRequest, AdhocQueryResponse adhocQueryResponse) { log.debug("Begin <API key>"); AdhocQueryResponse response = null; if (adhocQueryRequest == null) { log.warn("AdhocQueryRequest was null."); } else if (adhocQueryResponse == null) { log.warn("AdhocQueryResponse was null."); } else { extractIdentifiers(adhocQueryRequest); if ((patientId != null) && (!patientId.isEmpty())) { <API key> <API key> = <API key>(); if (<API key> == null) { log.warn("<API key> was null."); } else { <API key> patientPreferences = <API key>.<API key>( patientId, <API key>); if (patientPreferences == null) { log.warn("PatientPreferences was null."); } else { response = filterResults(adhocQueryResponse, patientPreferences); } } } else { log.info("Not a patient-centric query."); response = <API key>(adhocQueryResponse); } } log.debug("End <API key>"); return response; } protected void extractIdentifiers(AdhocQueryRequest adhocQueryRequest) { log.debug("Begin extractIdentifiers"); if (adhocQueryRequest == null) { log.warn("AdhocQueryRequest was null."); } else { AdhocQueryType adhocQuery = adhocQueryRequest.getAdhocQuery(); if (adhocQuery != null) { homeCommunityId = HomeCommunityMap.<API key>(adhocQuery); List<SlotType1> slots = null; if (adhocQuery != null) { slots = adhocQuery.getSlot(); List<String> slotValues = extractSlotValues(slots, <API key>); if ((slotValues != null) && (!slotValues.isEmpty())) { String formattedPatientId = slotValues.get(0); patientId = PatientIdFormatUtil.parsePatientId(formattedPatientId); <API key> = PatientIdFormatUtil.parseCommunityId(formattedPatientId); } } } } log.debug("End extractIdentifiers"); } protected List<String> extractSlotValues(List<SlotType1> slots, String slotName) { log.debug("Begin extractSlotValues"); List<String> returnValues = null; if (slots != null) { for (SlotType1 slot : slots) { if ((slot.getName() != null) && (slot.getName().length() > 0) && (slot.getValueList() != null) && (slot.getValueList().getValue() != null) && (slot.getValueList().getValue().size() > 0)) { if (slot.getName().equals(slotName)) { ValueListType valueListType = slot.getValueList(); List<String> slotValues = valueListType.getValue(); returnValues = new ArrayList<String>(); for (String slotValue : slotValues) { returnValues.add(slotValue); } } } } } log.debug("End extractSlotValues"); return returnValues; } protected AdhocQueryResponse <API key>(AdhocQueryResponse adhocQueryResponse) { log.debug("In <API key>"); return filterResults(adhocQueryResponse, null); } protected AdhocQueryResponse filterResults(AdhocQueryResponse adhocQueryResponse, <API key> patientPreferences) { log.debug("Begin filterResults"); AdhocQueryResponse response = null; if (adhocQueryResponse == null) { log.warn("AdhocQueryResponse was null."); } else { ObjectFactory rimObjectFactory = new ObjectFactory(); response = new AdhocQueryResponse(); response.<API key>(adhocQueryResponse.<API key>()); response.setStatus(adhocQueryResponse.getStatus()); <API key> registryObjectList = null; long docCount = 0; <API key> <API key> = adhocQueryResponse.<API key>(); if (<API key> != null) { List<JAXBElement<? extends IdentifiableType>> olRegObjs = <API key>.getIdentifiable(); for (JAXBElement<? extends IdentifiableType> oJAXBObj : olRegObjs) { if ((oJAXBObj != null) && (oJAXBObj.getDeclaredType() != null) && (oJAXBObj.getDeclaredType().getCanonicalName() != null) && (oJAXBObj.getDeclaredType().getCanonicalName() .equals("oasis.names.tc.ebxml_regrep.xsd.rim._3.ExtrinsicObjectType")) && (oJAXBObj.getValue() != null)) { ExtrinsicObjectType oExtObj = (ExtrinsicObjectType) oJAXBObj.getValue(); <API key> <API key> = null; if (patientPreferences == null) { <API key> = <API key>(oExtObj); } else { <API key> = patientPreferences; } if (documentAllowed(oExtObj, <API key>)) { log.debug("Adding document query response to the list."); if (registryObjectList == null) { registryObjectList = new <API key>(); response.<API key>(registryObjectList); } registryObjectList.getIdentifiable().add(rimObjectFactory.<API key>(oExtObj)); docCount++; } else { log.debug("Skipping document"); } } } response.setTotalResultCount(BigInteger.valueOf(docCount)); } else { log.info("RegistryObjectList was null."); } } log.debug("End filterResults"); return response; } protected <API key> <API key>(ExtrinsicObjectType oExtObj) { <API key> patientPreferences = null; if (oExtObj == null) { log.error("Extrinsic Object was null."); } else { String documentId = extractDocumentId(oExtObj); String repositoryId = extractRepositoryId(oExtObj); patientPreferences = <API key>().<API key>(homeCommunityId, repositoryId, documentId); } return patientPreferences; } protected String extractDocumentId(ExtrinsicObjectType oExtObj) { log.debug("Begin extractDocumentId"); String documentId = null; if (!oExtObj.<API key>().isEmpty()) { List<<API key>> olExtId = oExtObj.<API key>(); for (<API key> oExtId : olExtId) { if ((oExtId.<API key>() != null) && (oExtId.<API key>().equals(CDAConstants.<API key>)) && (oExtId.getValue() != null) && (oExtId.getValue().length() > 0)) { documentId = oExtId.getValue().trim(); } } } log.debug("End extractDocumentId - returning: " + documentId); return documentId; } protected String extractRepositoryId(ExtrinsicObjectType oExtObj) { log.debug("Begin extractRepositoryId"); String repositoryId = null; if (!oExtObj.getSlot().isEmpty()) { List<SlotType1> slots = oExtObj.getSlot(); for (SlotType1 slot : slots) { if ((slot != null) && (CDAConstants.<API key>.equals(slot.getName())) && (slot.getValueList() != null) && (!slot.getValueList().getValue().isEmpty())) { repositoryId = slot.getValueList().getValue().get(0); if (repositoryId != null) { repositoryId = repositoryId.trim(); break; } } } } log.debug("End extractRepositoryId - returning: " + repositoryId); return repositoryId; } protected String extractDocumentType(ExtrinsicObjectType oExtObj) { log.debug("Begin extractDocumentType"); String documentType = null; if (!oExtObj.getClassification().isEmpty()) { List<ClassificationType> classifications = oExtObj.getClassification(); for (ClassificationType classification : classifications) { if ((classification != null) && (<API key>.equals(classification.<API key>()))) { documentType = classification.<API key>(); break; } } } log.debug("End extractDocumentType - returning: " + documentType); return documentType; } protected boolean documentAllowed(ExtrinsicObjectType extObject, <API key> patientPreferences) { log.debug("Begin documentAllowed"); boolean allowed = false; String documentTypeCode = extractDocumentType(extObject); allowed = <API key>().<API key>(documentTypeCode, patientPreferences); log.debug("End documentAllowed - response: " + allowed); return allowed; } }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_26) on Sun Jan 22 14:18:58 CET 2012 --> <TITLE> Uses of Class soot.PatchingChain (Soot API) </TITLE> <META NAME="date" CONTENT="2012-01-22"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class soot.PatchingChain (Soot API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../soot/PatchingChain.html" title="class in soot"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?soot//<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PatchingChain.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Class<br>soot.PatchingChain</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#soot"><B>soot</B></A></TD> <TD>Base Soot classes, shared by different intermediate representations.&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#soot.jbco.bafTransformations"><B>soot.jbco.bafTransformations</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#soot.jbco.util"><B>soot.jbco.util</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#soot.jimple.toolkits.thread.synchronization"><B>soot.jimple.toolkits.thread.synchronization</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#soot.shimple.internal"><B>soot.shimple.internal</B></A></TD> <TD>Shimple internal messy stuff.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="soot"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A> in <A HREF="../../soot/package-summary.html">soot</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../soot/package-summary.html">soot</A> declared as <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&lt;<A HREF="../../soot/Unit.html" title="interface in soot">Unit</A>&gt;</CODE></FONT></TD> <TD><CODE><B>Body.</B><B><A HREF="../../soot/Body.html#unitChain">unitChain</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The chain of units for this Body.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&lt;<A HREF="../../soot/Unit.html" title="interface in soot">Unit</A>&gt;</CODE></FONT></TD> <TD><CODE><B>Body.</B><B><A HREF="../../soot/Body.html#unitChain">unitChain</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The chain of units for this Body.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../soot/package-summary.html">soot</A> that return <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&lt;<A HREF="../../soot/Unit.html" title="interface in soot">Unit</A>&gt;</CODE></FONT></TD> <TD><CODE><B>Body.</B><B><A HREF="../../soot/Body.html#getUnits()">getUnits</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the Chain of Units that make up this body.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&lt;<A HREF="../../soot/Unit.html" title="interface in soot">Unit</A>&gt;</CODE></FONT></TD> <TD><CODE><B>Body.</B><B><A HREF="../../soot/Body.html#getUnits()">getUnits</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the Chain of Units that make up this body.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="soot.jbco.bafTransformations"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A> in <A HREF="../../soot/jbco/bafTransformations/package-summary.html">soot.jbco.bafTransformations</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../soot/jbco/bafTransformations/package-summary.html">soot.jbco.bafTransformations</A> with parameters of type <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B><API key>.</B><B><A HREF="../../soot/jbco/bafTransformations/<API key>.html#printStack(soot.PatchingChain, java.util.HashMap, boolean)">printStack</A></B>(<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&nbsp;units, <A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/util/HashMap.html?is-external=true" title="class or interface in java.util">HashMap</A>&nbsp;stacks, boolean&nbsp;before)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B><API key>.</B><B><A HREF="../../soot/jbco/bafTransformations/<API key>.html#printStack(soot.PatchingChain, java.util.HashMap, boolean)">printStack</A></B>(<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&nbsp;units, <A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/util/HashMap.html?is-external=true" title="class or interface in java.util">HashMap</A>&nbsp;stacks, boolean&nbsp;before)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="soot.jbco.util"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A> in <A HREF="../../soot/jbco/util/package-summary.html">soot.jbco.util</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../soot/jbco/util/package-summary.html">soot.jbco.util</A> with parameters of type <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/util/ArrayList.html?is-external=true" title="class or interface in java.util">ArrayList</A></CODE></FONT></TD> <TD><CODE><B>BodyBuilder.</B><B><A HREF="../../soot/jbco/util/BodyBuilder.html#<API key>(soot.PatchingChain, soot.util.Chain, java.util.List)"><API key></A></B>(<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&nbsp;units, <A HREF="../../soot/util/Chain.html" title="interface in soot.util">Chain</A>&nbsp;locals, <A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</A>&nbsp;paramTypes)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/util/ArrayList.html?is-external=true" title="class or interface in java.util">ArrayList</A></CODE></FONT></TD> <TD><CODE><B>BodyBuilder.</B><B><A HREF="../../soot/jbco/util/BodyBuilder.html#<API key>(soot.PatchingChain, soot.util.Chain, java.util.List)"><API key></A></B>(<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&nbsp;units, <A HREF="../../soot/util/Chain.html" title="interface in soot.util">Chain</A>&nbsp;locals, <A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</A>&nbsp;paramTypes)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../soot/Local.html" title="interface in soot">Local</A></CODE></FONT></TD> <TD><CODE><B>BodyBuilder.</B><B><A HREF="../../soot/jbco/util/BodyBuilder.html#buildThisLocal(soot.PatchingChain, soot.jimple.ThisRef, soot.util.Chain)">buildThisLocal</A></B>(<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&nbsp;units, <A HREF="../../soot/jimple/ThisRef.html" title="class in soot.jimple">ThisRef</A>&nbsp;tr, <A HREF="../../soot/util/Chain.html" title="interface in soot.util">Chain</A>&nbsp;locals)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../soot/Local.html" title="interface in soot">Local</A></CODE></FONT></TD> <TD><CODE><B>BodyBuilder.</B><B><A HREF="../../soot/jbco/util/BodyBuilder.html#buildThisLocal(soot.PatchingChain, soot.jimple.ThisRef, soot.util.Chain)">buildThisLocal</A></B>(<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&nbsp;units, <A HREF="../../soot/jimple/ThisRef.html" title="class in soot.jimple">ThisRef</A>&nbsp;tr, <A HREF="../../soot/util/Chain.html" title="interface in soot.util">Chain</A>&nbsp;locals)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B>Debugger.</B><B><A HREF="../../soot/jbco/util/Debugger.html#printUnits(soot.PatchingChain, java.lang.String)">printUnits</A></B>(<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&nbsp;u, <A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;msg)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B>Debugger.</B><B><A HREF="../../soot/jbco/util/Debugger.html#printUnits(soot.PatchingChain, java.lang.String)">printUnits</A></B>(<A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&nbsp;u, <A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;msg)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="soot.jimple.toolkits.thread.synchronization"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A> in <A HREF="../../soot/jimple/toolkits/thread/synchronization/package-summary.html">soot.jimple.toolkits.thread.synchronization</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../soot/jimple/toolkits/thread/synchronization/package-summary.html">soot.jimple.toolkits.thread.synchronization</A> with parameters of type <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../soot/jimple/InstanceFieldRef.html" title="interface in soot.jimple">InstanceFieldRef</A></CODE></FONT></TD> <TD><CODE><B><API key>.</B><B><A HREF="../../soot/jimple/toolkits/thread/synchronization/<API key>.html#reconstruct(soot.Body, soot.PatchingChain, soot.jimple.InstanceFieldRef, soot.jimple.Stmt, boolean)">reconstruct</A></B>(<A HREF="../../soot/Body.html" title="class in soot">Body</A>&nbsp;b, <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&lt;<A HREF="../../soot/Unit.html" title="interface in soot">Unit</A>&gt;&nbsp;units, <A HREF="../../soot/jimple/InstanceFieldRef.html" title="interface in soot.jimple">InstanceFieldRef</A>&nbsp;lock, <A HREF="../../soot/jimple/Stmt.html" title="interface in soot.jimple">Stmt</A>&nbsp;insertBefore, boolean&nbsp;redirect)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../soot/jimple/InstanceFieldRef.html" title="interface in soot.jimple">InstanceFieldRef</A></CODE></FONT></TD> <TD><CODE><B><API key>.</B><B><A HREF="../../soot/jimple/toolkits/thread/synchronization/<API key>.html#reconstruct(soot.Body, soot.PatchingChain, soot.jimple.InstanceFieldRef, soot.jimple.Stmt, boolean)">reconstruct</A></B>(<A HREF="../../soot/Body.html" title="class in soot">Body</A>&nbsp;b, <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A>&lt;<A HREF="../../soot/Unit.html" title="interface in soot">Unit</A>&gt;&nbsp;units, <A HREF="../../soot/jimple/InstanceFieldRef.html" title="interface in soot.jimple">InstanceFieldRef</A>&nbsp;lock, <A HREF="../../soot/jimple/Stmt.html" title="interface in soot.jimple">Stmt</A>&nbsp;insertBefore, boolean&nbsp;redirect)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="soot.shimple.internal"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A> in <A HREF="../../soot/shimple/internal/package-summary.html">soot.shimple.internal</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../soot/PatchingChain.html" title="class in soot">PatchingChain</A> in <A HREF="../../soot/shimple/internal/package-summary.html">soot.shimple.internal</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../soot/shimple/internal/SPatchingChain.html" title="class in soot.shimple.internal">SPatchingChain</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Internal Shimple extension of PatchingChain.</TD> </TR> </TABLE> &nbsp; <P> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../soot/PatchingChain.html" title="class in soot"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?soot//<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PatchingChain.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> </BODY> </HTML>
package edu.duke.cabig.c3pr.webservice.iso21090; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DSET_SC complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DSET_SC"> * &lt;complexContent> * &lt;extension base="{uri:iso.org:21090}COLL_SC"> * &lt;sequence> * &lt;element name="item" type="{uri:iso.org:21090}SC" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DSET_SC", propOrder = { "item" }) public class DSETSC extends COLLSC { protected List<SC> item; /** * Gets the value of the item property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the item property. * * <p> * For example, to add a new item, do as follows: * <pre> * getItem().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SC } * * */ public List<SC> getItem() { if (item == null) { item = new ArrayList<SC>(); } return this.item; } }
module Signal.Wavelet.Eval2Bench where import Signal.Wavelet.Eval2 {-# INLINE benchDwt #-} benchDwt :: ([Double], [Double]) -> [Double] benchDwt (ls, sig) = dwt ls sig {-# INLINE benchIdwt #-} benchIdwt :: ([Double], [Double]) -> [Double] benchIdwt (ls, sig) = idwt ls sig
namespace Cuyahoga.Web.Manager.Model.ViewModels { public class AjaxMessageViewData { public string Message { get; set; } public string Error { get; set; } } }
#include "<API key>.h" #include "<API key>.h" #include "<API key>.h" #include "<API key>.h" #include "berryPlatform.h" #include <QFileDialog> #include <QLabel> #include <QPushButton> #include <QLineEdit> #include <QGridLayout> #include <QMessageBox> #include <QApplication> #include <QMap> #include "ctkXnatSession.h" #include "ctkXnatLoginProfile.h" #include "ctkXnatException.h" #include <mitkIOUtil.h> using namespace berry; <API key>::<API key>() : m_Control(0) { } void <API key>::Init(berry::IWorkbench::Pointer) { } void <API key>::CreateQtControl(QWidget* parent) { IPreferencesService* prefService = Platform::<API key>(); berry::IPreferences::Pointer <API key> = prefService-><API key>()->Node(<API key>::VIEW_ID); <API key> = <API key>; m_Controls.setupUi(parent); m_Control = new QWidget(parent); m_Control->setLayout(m_Controls.gridLayout); ctkXnatSession* session; try { session = mitk::<API key>::<API key>()->GetService( mitk::<API key>::<API key>()->GetServiceReference<ctkXnatSession>()); } catch (std::invalid_argument) { session = nullptr; } if (session != nullptr) { if (session->isOpen()) { m_Controls.<API key>->setText("Disconnect"); } else { m_Controls.<API key>->setText("Connect"); } } const QIntValidator *portV = new QIntValidator(0, 65535, parent); m_Controls.inXnatPort->setValidator(portV); const QRegExp hostRx("^(https?): const QRegExpValidator *hostV = new QRegExpValidator(hostRx, parent); m_Controls.inXnatHostAddress->setValidator(hostV); connect(m_Controls.<API key>, SIGNAL(clicked()), this, SLOT(ToggleConnection())); connect(m_Controls.inXnatHostAddress, SIGNAL(editingFinished()), this, SLOT(UrlChanged())); connect(m_Controls.inXnatDownloadPath, SIGNAL(editingFinished()), this, SLOT(DownloadPathChanged())); connect(m_Controls.cbUseNetworkProxy, SIGNAL(toggled(bool)), this, SLOT(onUseNetworkProxy(bool))); connect(m_Controls.btnDownloadPath, SIGNAL(clicked()), this, SLOT(<API key>())); m_Controls.<API key>->setVisible(m_Controls.cbUseNetworkProxy->isChecked()); this->Update(); } QWidget* <API key>::GetQtControl() const { return m_Control; } bool <API key>::PerformOk() { if (!<API key>()) { IPreferences::Pointer <API key> = <API key>.Lock(); if (<API key>.IsNotNull()) { <API key>->Put(m_Controls.<API key>->text(), m_Controls.inXnatHostAddress->text()); <API key>->Put(m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text()); <API key>->Put(m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text()); <API key>->Put(m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text()); <API key>->Put(m_Controls.<API key>->text(), m_Controls.inXnatDownloadPath->text()); // Network proxy settings <API key>->PutBool(m_Controls.cbUseNetworkProxy->text(), m_Controls.cbUseNetworkProxy->isChecked()); <API key>->Put(m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text()); <API key>->Put(m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text()); <API key>->Put(m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text()); <API key>->Put(m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text()); <API key>->Flush(); return true; } } else { QMessageBox::critical(QApplication::activeWindow(), "Saving Preferences failed", "The connection parameters in XNAT Preferences were empty.\nPlease use the 'Connect' button to validate the connection parameters."); } return false; } void <API key>::PerformCancel() { } bool <API key>::<API key>() { // To check empty QLineEdits in the following QString errString; if (m_Controls.inXnatHostAddress->text().isEmpty()) { errString += "Server Address is empty.\n"; } if (m_Controls.inXnatUsername->text().isEmpty()) { errString += "Username is empty.\n"; } if (m_Controls.inXnatPassword->text().isEmpty()) { errString += "Password is empty.\n"; } // if something is empty if (!errString.isEmpty()) { m_Controls.<API key>->setStyleSheet("QLabel { color: red; }"); m_Controls.<API key>->setText("Connecting failed.\n" + errString); return true; } else { return false; } } void <API key>::Update() { IPreferences::Pointer <API key> = <API key>.Lock(); if (<API key>.IsNotNull()) { m_Controls.inXnatHostAddress->setText(<API key>->Get( m_Controls.<API key>->text(), m_Controls.inXnatHostAddress->text())); m_Controls.inXnatPort->setText(<API key>->Get( m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text())); m_Controls.inXnatUsername->setText(<API key>->Get( m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text())); m_Controls.inXnatPassword->setText(<API key>->Get( m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text())); m_Controls.inXnatDownloadPath->setText(<API key>->Get( m_Controls.<API key>->text(), m_Controls.inXnatDownloadPath->text())); // Network proxy settings m_Controls.cbUseNetworkProxy->setChecked(<API key>->GetBool( m_Controls.cbUseNetworkProxy->text(), false)); m_Controls.inProxyAddress->setText(<API key>->Get( m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text())); m_Controls.inProxyPort->setText(<API key>->Get( m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text())); m_Controls.inProxyUsername->setText(<API key>->Get( m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text())); m_Controls.inProxyPassword->setText(<API key>->Get( m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text())); } } void <API key>::UrlChanged() { m_Controls.inXnatHostAddress->setStyleSheet("QLineEdit { background-color: white; }"); QString str = m_Controls.inXnatHostAddress->text(); while (str.endsWith("/")) { str = str.left(str.length() - 1); } m_Controls.inXnatHostAddress->setText(str); QUrl url(m_Controls.inXnatHostAddress->text()); if (!url.isValid()) { m_Controls.inXnatHostAddress->setStyleSheet("QLineEdit { background-color: red; }"); } } void <API key>::DownloadPathChanged() { m_Controls.inXnatDownloadPath->setStyleSheet("QLineEdit { background-color: white; }"); QString downloadPath = m_Controls.inXnatDownloadPath->text(); if (!downloadPath.isEmpty()) { if (downloadPath.lastIndexOf("/") != downloadPath.size() - 1) { downloadPath.append("/"); m_Controls.inXnatDownloadPath->setText(downloadPath); } QFileInfo path(m_Controls.inXnatDownloadPath->text()); if (!path.isDir()) { m_Controls.inXnatDownloadPath->setStyleSheet("QLineEdit { background-color: red; }"); } } } void <API key>::onUseNetworkProxy(bool status) { m_Controls.<API key>->setVisible(status); } void <API key>::<API key>() { QString dir = QFileDialog::<API key>(); if (!dir.endsWith("/") || !dir.endsWith("\\")) dir.append("/"); m_Controls.inXnatDownloadPath->setText(dir); } void <API key>::ToggleConnection() { ctkXnatSession* session = 0; try { session = mitk::<API key>::<API key>()->GetService( mitk::<API key>::<API key>()->GetServiceReference<ctkXnatSession>()); } catch (std::invalid_argument) { if (!<API key>()) { PerformOk(); mitk::<API key>::<API key>()->CreateXnatSession(); session = mitk::<API key>::<API key>()->GetService( mitk::<API key>::<API key>()->GetServiceReference<ctkXnatSession>()); } } if (session != 0 && session->isOpen()) { mitk::<API key>::<API key>()->CloseXnatSession(); m_Controls.<API key>->setText("Connect"); m_Controls.<API key>->clear(); } else if (session != 0 && !session->isOpen()) { m_Controls.<API key>->setEnabled(false); try { mitk::<API key>::<API key>()->OpenXnatSession(); m_Controls.<API key>->setText("Disconnect"); m_Controls.<API key>->setStyleSheet("QLabel { color: green; }"); m_Controls.<API key>->setText("Connecting successful."); } catch (const ctkXnat<API key>& auth) { m_Controls.<API key>->setStyleSheet("QLabel { color: red; }"); m_Controls.<API key>->setText("Connecting failed:\nAuthentication error."); MITK_INFO << auth.message().toStdString(); mitk::<API key>::<API key>()->CloseXnatSession(); } catch (const ctkException& e) { m_Controls.<API key>->setStyleSheet("QLabel { color: red; }"); m_Controls.<API key>->setText("Connecting failed:\nInvalid Server Adress"); MITK_INFO << e.message().toStdString(); mitk::<API key>::<API key>()->CloseXnatSession(); } m_Controls.<API key>->setEnabled(true); } }
#include "f2c.h" #include "blaswrap.h" /* Table of constant values */ static integer c__1 = 1; /* Subroutine */ int zpbcon_(char *uplo, integer *n, integer *kd, doublecomplex *ab, integer *ldab, doublereal *anorm, doublereal * rcond, doublecomplex *work, doublereal *rwork, integer *info) { /* System generated locals */ integer ab_dim1, ab_offset, i__1; doublereal d__1, d__2; /* Local variables */ integer ix, kase; doublereal scale; integer isave[3]; logical upper; doublereal scalel, scaleu; doublereal ainvnm; char normin[1]; doublereal smlnum; /* -- LAPACK routine (version 3.2) -- */ /* November 2006 */ /* Modified to call ZLACN2 in place of ZLACON, 10 Feb 03, SJH. */ /* Purpose */ /* ZPBCON estimates the reciprocal of the condition number (in the */ /* 1-norm) of a complex Hermitian positive definite band matrix using */ /* the Cholesky factorization A = U**H*U or A = L*L**H computed by */ /* ZPBTRF. */ /* An estimate is obtained for norm(inv(A)), and the reciprocal of the */ /* condition number is computed as RCOND = 1 / (ANORM * norm(inv(A))). */ /* Arguments */ /* UPLO (input) CHARACTER*1 */ /* = 'U': Upper triangular factor stored in AB; */ /* = 'L': Lower triangular factor stored in AB. */ /* N (input) INTEGER */ /* The order of the matrix A. N >= 0. */ /* KD (input) INTEGER */ /* The number of superdiagonals of the matrix A if UPLO = 'U', */ /* or the number of sub-diagonals if UPLO = 'L'. KD >= 0. */ /* AB (input) COMPLEX*16 array, dimension (LDAB,N) */ /* The triangular factor U or L from the Cholesky factorization */ /* A = U**H*U or A = L*L**H of the band matrix A, stored in the */ /* first KD+1 rows of the array. The j-th column of U or L is */ /* stored in the j-th column of the array AB as follows: */ /* if UPLO ='U', AB(kd+1+i-j,j) = U(i,j) for max(1,j-kd)<=i<=j; */ /* if UPLO ='L', AB(1+i-j,j) = L(i,j) for j<=i<=min(n,j+kd). */ /* LDAB (input) INTEGER */ /* The leading dimension of the array AB. LDAB >= KD+1. */ /* ANORM (input) DOUBLE PRECISION */ /* The 1-norm (or infinity-norm) of the Hermitian band matrix A. */ /* RCOND (output) DOUBLE PRECISION */ /* The reciprocal of the condition number of the matrix A, */ /* computed as RCOND = 1/(ANORM * AINVNM), where AINVNM is an */ /* estimate of the 1-norm of inv(A) computed in this routine. */ /* WORK (workspace) COMPLEX*16 array, dimension (2*N) */ /* RWORK (workspace) DOUBLE PRECISION array, dimension (N) */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* Test the input parameters. */ /* Parameter adjustments */ ab_dim1 = *ldab; ab_offset = 1 + ab_dim1; ab -= ab_offset; --work; --rwork; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*kd < 0) { *info = -3; } else if (*ldab < *kd + 1) { *info = -5; } else if (*anorm < 0.) { *info = -6; } if (*info != 0) { i__1 = -(*info); xerbla_("ZPBCON", &i__1); return 0; } /* Quick return if possible */ *rcond = 0.; if (*n == 0) { *rcond = 1.; return 0; } else if (*anorm == 0.) { return 0; } smlnum = dlamch_("Safe minimum"); /* Estimate the 1-norm of the inverse. */ kase = 0; *(unsigned char *)normin = 'N'; L10: zlacn2_(n, &work[*n + 1], &work[1], &ainvnm, &kase, isave); if (kase != 0) { if (upper) { /* Multiply by inv(U'). */ zlatbs_("Upper", "Conjugate transpose", "Non-unit", normin, n, kd, &ab[ab_offset], ldab, &work[1], &scalel, &rwork[1], info); *(unsigned char *)normin = 'Y'; /* Multiply by inv(U). */ zlatbs_("Upper", "No transpose", "Non-unit", normin, n, kd, &ab[ ab_offset], ldab, &work[1], &scaleu, &rwork[1], info); } else { /* Multiply by inv(L). */ zlatbs_("Lower", "No transpose", "Non-unit", normin, n, kd, &ab[ ab_offset], ldab, &work[1], &scalel, &rwork[1], info); *(unsigned char *)normin = 'Y'; /* Multiply by inv(L'). */ zlatbs_("Lower", "Conjugate transpose", "Non-unit", normin, n, kd, &ab[ab_offset], ldab, &work[1], &scaleu, &rwork[1], info); } /* Multiply by 1/SCALE if doing so will not cause overflow. */ scale = scalel * scaleu; if (scale != 1.) { ix = izamax_(n, &work[1], &c__1); i__1 = ix; if (scale < ((d__1 = work[i__1].r, abs(d__1)) + (d__2 = d_imag(& work[ix]), abs(d__2))) * smlnum || scale == 0.) { goto L20; } zdrscl_(n, &scale, &work[1], &c__1); } goto L10; } /* Compute the estimate of the reciprocal condition number. */ if (ainvnm != 0.) { *rcond = 1. / ainvnm / *anorm; } L20: return 0; /* End of ZPBCON */ } /* zpbcon_ */
#include "webkit/compositor_bindings/<API key>.h" #include "base/debug/trace_event.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop_proxy.h" #include "cc/thread_impl.h" #include "webkit/compositor_bindings/web_animation_impl.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/compositor_bindings/web_layer_impl.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/compositor_bindings/<API key>.h" #include "webkit/glue/webthread_impl.h" using WebKit::WebAnimation; using WebKit::WebAnimationCurve; using WebKit::WebContentLayer; using WebKit::<API key>; using WebKit::<API key>; using WebKit::<API key>; using WebKit::<API key>; using WebKit::<API key>; using WebKit::WebIOSurfaceLayer; using WebKit::WebImageLayer; using WebKit::WebImageLayer; using WebKit::WebLayer; using WebKit::WebLayerTreeView; using WebKit::<API key>; using WebKit::WebScrollbar; using WebKit::WebScrollbarLayer; using WebKit::<API key>; using WebKit::<API key>; using WebKit::WebSolidColorLayer; using WebKit::<API key>; using WebKit::<API key>; using WebKit::WebVideoLayer; namespace webkit { <API key>::<API key>() : initialized_(false) { } <API key>::~<API key>() { } void <API key>::initialize(WebKit::WebThread* impl_thread) { DCHECK(!initialized_); initialized_ = true; if (impl_thread) { <API key>("test_gpu", "<API key>"); <API key> = static_cast<webkit_glue::WebThreadImpl*>(impl_thread)-> message_loop()->message_loop_proxy(); } else { <API key> = NULL; } } bool <API key>::isThreadingEnabled() { return <API key>; } void <API key>::shutdown() { DCHECK(initialized_); initialized_ = false; <API key> = NULL; } WebLayerTreeView* <API key>::createLayerTreeView( <API key>* client, const WebLayer& root, const WebLayerTreeView::Settings& settings) { DCHECK(initialized_); scoped_ptr<WebKit::<API key>> layerTreeViewImpl( new WebKit::<API key>(client)); scoped_ptr<cc::Thread> impl_thread; if (<API key>) impl_thread = cc::ThreadImpl::<API key>( <API key>); if (!layerTreeViewImpl->initialize(settings, impl_thread.Pass())) return NULL; layerTreeViewImpl->setRootLayer(root); return layerTreeViewImpl.release(); } WebLayer* <API key>::createLayer() { return new WebKit::WebLayerImpl(); } WebContentLayer* <API key>::createContentLayer( <API key>* client) { return new WebKit::WebContentLayerImpl(client); } <API key>* <API key>::<API key>() { return new WebKit::<API key>(); } <API key>* <API key>::<API key>( <API key>* client) { return new WebKit::<API key>(client); } WebKit::WebIOSurfaceLayer* <API key>::<API key>() { return new WebKit::<API key>(); } WebKit::WebImageLayer* <API key>::createImageLayer() { return new WebKit::WebImageLayerImpl(); } WebSolidColorLayer* <API key>::<API key>() { return new WebKit::<API key>(); } WebVideoLayer* <API key>::createVideoLayer( WebKit::<API key>* provider) { return new WebKit::WebVideoLayerImpl(provider); } WebScrollbarLayer* <API key>::<API key>( WebScrollbar* scrollbar, <API key> painter, <API key>* geometry) { return new WebKit::<API key>(scrollbar, painter, geometry); } WebAnimation* <API key>::createAnimation( const WebKit::WebAnimationCurve& curve, WebKit::WebAnimation::TargetProperty target, int animationId) { return new WebKit::WebAnimationImpl(curve, target, animationId); } <API key>* <API key>::<API key>() { return new WebKit::<API key>(); } <API key>* <API key>::<API key>() { return new WebKit::<API key>(); } } // namespace webkit
package za.org.grassroot.core.repository; import org.springframework.data.jpa.repository.JpaRepository; import za.org.grassroot.core.domain.task.EventRequest; public interface <API key> extends JpaRepository<EventRequest, Long> { EventRequest findOneByUid(String uid); }
<?php namespace common\library; class BEncoderException extends \Exception { } /** * Class for Bencoding encode/decode * Bencoding is a way to specify and organize data in a terse format. * It supports the following types: byte strings, integers, * lists, and dictionaries. */ class BEncoder { /** * Decoded data * @var mixed */ public $source; /** * Encoded data * @var string */ public $encoded; private $_offset = 0; private $_len = 0; /** * Bencode format decoding. Result of the decoding will be saved in the $source field. * Some examples: * <code> * $bencoder = new bencoder_t; * $bencoder->decode ('i12345e'); * print_r ($bencoder->source); * </code> * Or * <code> * $bencoder = new bencoder_t; * $bencoder->encode (array ('fruit' => 'Banana', 'quantity' => 100)); * echo $bencoder->encoded; * $bencoder->decode (); * print_r ($bencoder->source); * </code> * @param string $str Encoded string. If omitted, contents of the $encoded field will be used */ public function decode($str = null) { $this->source = array(); if (!is_null($str)) $this->encoded = $str; $this->_offset = 0; $this->_len = strlen($this->encoded); $this->source = $this->_decode(); return $this->source; } /** * Encoding to Bencode format. Result of the encoding will be saved in the $encoded field. * Some examples: * <code> * $bencoder = new bencoder_t; * $bencoder->encode (array ('fruit' => 'Banana', 'quantity' => 100)); * echo $bencoder->encoded; * </code> * or * <code> * $bencoder = new bencoder_t; * $bencoder->encode (array ('fruit' => 'Banana', 'quantity' => 100)); * $bencoder->source ['color'] = 'yellow'; * $bencoder->encode (); * echo $bencoder->encoded; * </code> * @param mixed $str Data to encode. If omitted, contents of the $source field will be used */ public function encode($value = null) { $this->encoded = ''; if (!is_null($value)) $this->source = $value; $this->encoded = $this->_encode($this->source); return $this->encoded; } private function _decodeInt() { $end = strpos($this->encoded, 'e', $this->_offset); if ($end === false) { throw new BEncoderException('Decoding error at: ' . $this->_offset); } $result = (double)substr($this->encoded, $this->_offset + 1, $end - $this->_offset - 1); $this->_offset = $end + 1; return $result; } private function _decodeString() { $divider = strpos($this->encoded, ':', $this->_offset); if ($divider === false) throw new BEncoderException ('Decoding error at: ' . $this->_offset); $len = (int)substr($this->encoded, $this->_offset, $divider - $this->_offset); $result = substr($this->encoded, $divider + 1, $len); $this->_offset = $divider + $len + 1; return $result; } private function _decodeDictionary() { $result = array(); $this->_offset++; while ($this->encoded [$this->_offset] != 'e' && $this->_offset < $this->_len) $result [$this->_decodeString()] = $this->_decode(); $this->_offset++; return $result; } private function _decodeList() { $result = array(); $this->_offset++; while ($this->encoded [$this->_offset] != 'e' && $this->_offset < $this->_len) $result [] = $this->_decode(); $this->_offset++; return $result; } private function _decode() { switch ($this->encoded [$this->_offset]) { case 'd': return $this->_decodeDictionary(); case 'i': return $this->_decodeInt(); case 'l': return $this->_decodeList(); } if (is_numeric($this->encoded [$this->_offset])) return $this->_decodeString(); throw new BEncoderException ('Undefined data type at: ' . $this->_offset . ' while decoding'); } private function _encodeString($value) { return strlen($value) . ':' . $value; } private function _encodeArray($value) { $count = count($value); $list = true; for ($i = 0; $i < $count; $i++) if (!isset ($value [$i])) { $list = false; break; } ksort($value); return $list ? $this->_encodeList($value) : $this->_encodeDictionary($value); } private function _encodeList($value) { $result = 'l'; foreach ($value as $item) $result .= $this->_encode($item); return $result . 'e'; } private function _encodeDictionary($value) { $result = 'd'; foreach ($value as $key => $item) $result .= $this->_encodeString($key) . $this->_encode($item); return $result . 'e'; } private function _encodeInt($value) { return 'i' . ($value < 0 ? ceil($value) : floor($value)) . 'e'; } private function _encode($value) { switch (gettype($value)) { case 'NULL': return '0:'; case 'string': return $this->_encodeString($value); case 'array': return $this->_encodeArray($value); case 'object': return $this->_encodeArray(get_object_vars($value)); case 'boolean': return $this->_encodeInt((int)$value); case 'integer': case 'double': case 'float': return $this->_encodeInt($value); default: throw new BEncoderException ('Unknown datatype while encoding'); } } } ?>
#include <stdlib.h> #include <assert.h> #include <stdbool.h> #include <complex.h> #include <stdio.h> #include "num/flpmath.h" #include "num/init.h" #include "misc/mmio.h" #include "misc/misc.h" #ifndef DIMS #define DIMS 16 #endif static const char usage_str[] = "<input> <output>"; static const char help_str[] = "Compute complex conjugate.\n"; int main_conj(int argc, char* argv[]) { mini_cmdline(argc, argv, 2, usage_str, help_str); num_init(); const int N = 16; long dims[N]; complex float* idata = load_cfl(argv[1], N, dims); complex float* odata = create_cfl(argv[2], N, dims); md_zconj(N, dims, odata, idata); unmap_cfl(N, dims, idata); unmap_cfl(N, dims, odata); exit(0); }
#include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "gcc.h" /* Filter argc and argv before processing by the gcc driver proper. */ void <API key> (int *in_argc ATTRIBUTE_UNUSED, const char *const **in_argv ATTRIBUTE_UNUSED, int *in_added_libraries ATTRIBUTE_UNUSED) { /* Systems which use the NeXT runtime by default should arrange for the shared libgcc to be used when -fgnu-runtime is passed through specs. */ #if defined(<API key>) && ! defined(NEXT_OBJC_RUNTIME) int i; /* The new argument list will be contained in this. */ const char **arglist; /* True if we should add -shared-libgcc to the command-line. */ int shared_libgcc = 0; /* The total number of arguments with the new stuff. */ int argc; /* The argument list. */ const char *const *argv; argc = *in_argc; argv = *in_argv; for (i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (strcmp (argv[i], "-static-libgcc") == 0 || strcmp (argv[i], "-static") == 0) return; } else { int len; /* If the filename ends in .m or .mi, we are compiling ObjC and want to pass -shared-libgcc. */ len = strlen (argv[i]); if ((len > 2 && argv[i][len - 2] == '.' && argv[i][len - 1] == 'm') || (len > 3 && argv[i][len - 3] == '.' && argv[i][len - 2] == 'm' && argv[i][len - 1] == 'i')) shared_libgcc = 1; } } if (shared_libgcc) { /* Make sure to have room for the trailing NULL argument. */ arglist = XNEWVEC (const char *, argc + 2); i = 0; do { arglist[i] = argv[i]; i++; } while (i < argc); arglist[i++] = "-shared-libgcc"; arglist[i] = NULL; *in_argc = i; *in_argv = arglist; } #endif } /* Called before linking. Returns 0 on success and -1 on failure. */ int <API key> (void) { return 0; /* Not used for C. */ } /* Number of extra output files that <API key> may generate. */ int <API key> = 0; /* Not used for C. */
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use yii\web\JsExpression; use kartik\widgets\Select2; use kartik\popover\PopoverX; use yii\bootstrap\Modal; ?> <div class="<API key>"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model3, 'placas')->textInput(['maxlength' => 145]) ?> <?= $form->field($model3, 'modelo')->textInput(['maxlength' => 145]) ?> <?= $form->field($model3, 'numero_serie')->textInput(['maxlength' => 145]) ?> <?php ActiveForm::end(); ?> </div>
C+ cal_fact_type2 C subroutine cal_fact_type2( sf_lun, num_vis, vis_list, vis, * mod_vis, merge_type, gains, s ) C C Sets up gain corrections for the given sample file. C C Given: C Logical unit number of sample file integer sf_lun C Number of visibilities in visibility buffer. integer num_vis C Visibility list integer vis_list(num_vis) C Visibility buffer and model visibility buffer. complex vis(num_vis), mod_vis(num_vis) C Merge type - must be aerial_merge or hut_merge integer merge_type C Returned: C Gain correction buffer. complex gains(num_vis) C Status variable - must be zero on entry - otherwise error integer s C *- C Global includes include '/mrao/post/include/global_constants.inc' include '/mrao/post/include/cal_solution.inc' include '/mrao/post/include/cal_ae_matrix.inc' include '/mrao/post/include/merge_types.inc' include '/mrao/post/include/calib_errors.inc' C C Local variables, equivilances and commons C Loop control variables and counters integer i, ii, n, nn, grp_num integer iv, il, il1, iv_list(max_vis) integer iae1, iae2 C Aerial Matrix integer*2 ia(2,max_aes) C Merge control spacing list integer merge_list( 2*max_vis ) C Number of groups and size of each group in merge list. integer num_grps, grp_size( max_vis ) C Merged visibility buffers complex grp_vis(max_vis) C Gains for each logical aerial complex actual_gains(max_aes) C Telescope description integer nae, nsp, nsb, nch, isp, isb, ich, isb0, ich0 integer logical_ae, actual_ae C Check for non zero entry status if ( s .ne. 0 ) return C enquire structure of the telescope call enq_obsdef ( sf_lun, nae, nsp, nsb, nch, s ) C set up merge call set_merge( sf_lun, vis_list, num_vis, merge_type, * merge_list, num_grps, grp_size, s ) C initialise the visibility gain corrections and normalise to a point source do i = 1, num_vis gains(i) = (1.0,0.0) vis(i) = vis(i)/mod_vis(i) end do do i = 1, max_vis vis_gains(i) = (1.0,0.0) end do C merge the visibilities call merge_vis_buffer( vis, num_vis, merge_list, * num_grps, grp_size, grp_vis, s ) C set the number of logical aerials to solve for depending on merge type if (merge_type.eq.no_merge) then logical_ae = nsb*nch else if (merge_type.eq.channel_merge) then logical_ae = nsb elseif (merge_type.eq.subband_merge) then logical_ae = 1 end if C initialise the solution do n = 1,max_RT_aes do i = 1,max_subb do ii=1,max_channel ae_gains(ii,i,n) = cmplx(1.0,0.0) end do end do end do C loop for each logical aerial do il=1,logical_ae C define the telescope array ii = 1 iv = 0 do grp_num = 1,num_grps if (grp_vis(grp_num).ne.(0.0,0.0)) then nn = vis_list(merge_list(ii)) call enq_ae_vis( sf_lun, nn, iae1, iae2, s ) isp = ((nn-1)/(nch*nsb)) + 1 isb = (nn - (isp-1)*nsb*nch - 1)/nch + 1 ich = (nn - (isp-1)*nsb*nch - (isb-1)*nch) if (merge_type.eq.no_merge) then il1 = (isb-1)*nch + ich else if (merge_type.eq.channel_merge) then il1 = isb else il1 = 1 end if if (il1.eq.il) then iv = iv + 1 ia(1,iv) = iae1 ia(2,iv) = iae2 iv_list(iv) = grp_num end if end if ii = ii + grp_size(grp_num) end do if (iv.ge.1) then call cal_init_soln( iv, max_RT_aes, ia, actual_ae, s ) C ... find the solution for this logical aerial if (merge_type.eq.no_merge) then isb = (il-1)/nch + 1 ich = il - (isb-1)*nch call enq_iba_code( sf_lun, isb, isb0, s) call enq_ich_code( sf_lun, ich, ich0, s) call cal_set_logical( isb0, ich0, s ) else if (merge_type.eq.channel_merge) then call enq_iba_code( sf_lun, il, isb0, s) call cal_set_logical( isb0, 0, s ) else call cal_set_logical( 0, 0, s ) end if call cal_calc_soln2( iv, iv_list, grp_vis, * actual_ae, actual_gains, s ) C ... save solution for this logical aerial do n = 1,actual_ae if (merge_type.eq.no_merge) then ae_gains(ich0,isb0,ae_list(n)) = actual_gains(n) else if (merge_type.eq.channel_merge) then do ich = 1,nch call enq_ich_code(sf_lun,ich,ich0,s) ae_gains(ich0,isb0,ae_list(n)) = actual_gains(n) end do else do isb = 1,nsb call enq_iba_code(sf_lun,isb,isb0,s) do ich = 1,nch call enq_ich_code(sf_lun,ich,ich0,s) ae_gains(ich0,isb0,ae_list(n)) = actual_gains(n) end do end do end if end do end if end do C determine the gains for each visibility do iv=1,num_vis call enq_vis_desig( sf_lun, vis_list(iv), isp, isb, ich, s) call enq_ae_vis( sf_lun, vis_list(iv), iae1, iae2, s ) gains(iv) = * ae_gains(ich,isb,iae1)*conjg(ae_gains(ich,isb,iae2)) end do C record the solution being found for this sample file current_solution = .true. C error Handling 999 continue if (s.ne.0) then call cal_wrerr( s, 'in subroutine cal_fact_type2' ) end if end
#include "libraryinfo.h" #include <QStandardPaths> static QString storageLocation(QStandardPaths::StandardLocation type) { QString location = QStandardPaths::writableLocation(type); return location.isEmpty() ? QString("/tmp") : location; } QString LibraryInfo::dataPath() { return storageLocation(QStandardPaths::DataLocation); } QString LibraryInfo::tempPath() { return storageLocation(QStandardPaths::TempLocation); } QString LibraryInfo::logPath() { return storageLocation(QStandardPaths::TempLocation); }
// Use of this source code is governed by a BSD-style // Package filepath implements utility routines for manipulating filename paths // in a way compatible with the target operating system-defined file paths. // The filepath package uses either forward slashes or backslashes, // depending on the operating system. To process paths such as URLs // that always use forward slashes regardless of the operating // system, see the path package. package filepath import ( "errors" "os" "sort" "strings" ) // A lazybuf is a lazily constructed path buffer. // It supports append, reading previously appended bytes, // and retrieving the final string. It does not allocate a buffer // to hold the output until that output diverges from s. type lazybuf struct { path string buf []byte w int volAndPath string volLen int } func (b *lazybuf) index(i int) byte { if b.buf != nil { return b.buf[i] } return b.path[i] } func (b *lazybuf) append(c byte) { if b.buf == nil { if b.w < len(b.path) && b.path[b.w] == c { b.w++ return } b.buf = make([]byte, len(b.path)) copy(b.buf, b.path[:b.w]) } b.buf[b.w] = c b.w++ } func (b *lazybuf) string() string { if b.buf == nil { return b.volAndPath[:b.volLen+b.w] } return b.volAndPath[:b.volLen] + string(b.buf[:b.w]) } const ( Separator = os.PathSeparator ListSeparator = os.PathListSeparator ) // Clean returns the shortest path name equivalent to path // by purely lexical processing. It applies the following rules // iteratively until no further processing can be done: // 1. Replace multiple Separator elements with a single one. // 2. Eliminate each . path name element (the current directory). // 3. Eliminate each inner .. path name element (the parent directory) // along with the non-.. element that precedes it. // 4. Eliminate .. elements that begin a rooted path: // that is, replace "/.." by "/" at the beginning of a path, // assuming Separator is '/'. // The returned path ends in a slash only if it represents a root directory, // such as "/" on Unix or `C:\` on Windows. // Finally, any occurrences of slash are replaced by Separator. // If the result of this process is an empty string, Clean // returns the string ".". // See also Rob Pike, ``Lexical File Names in Plan 9 or // Getting Dot-Dot Right,'' func Clean(path string) string { originalPath := path volLen := volumeNameLen(path) path = path[volLen:] if path == "" { if volLen > 1 && originalPath[1] != ':' { // should be UNC return FromSlash(originalPath) } return originalPath + "." } rooted := os.IsPathSeparator(path[0]) // Invariants: // reading from path; r is index of next byte to process. // writing to buf; w is index of next byte to write. // dotdot is index in buf where .. must stop, either because // it is the leading slash or it is a leading ../../.. prefix. n := len(path) out := lazybuf{path: path, volAndPath: originalPath, volLen: volLen} r, dotdot := 0, 0 if rooted { out.append(Separator) r, dotdot = 1, 1 } for r < n { switch { case os.IsPathSeparator(path[r]): // empty path element r++ case path[r] == '.' && (r+1 == n || os.IsPathSeparator(path[r+1])): // . element r++ case path[r] == '.' && path[r+1] == '.' && (r+2 == n || os.IsPathSeparator(path[r+2])): // .. element: remove to last separator r += 2 switch { case out.w > dotdot: // can backtrack out.w for out.w > dotdot && !os.IsPathSeparator(out.index(out.w)) { out.w } case !rooted: // cannot backtrack, but not rooted, so append .. element. if out.w > 0 { out.append(Separator) } out.append('.') out.append('.') dotdot = out.w } default: // real path element. // add slash if needed if rooted && out.w != 1 || !rooted && out.w != 0 { out.append(Separator) } // copy element for ; r < n && !os.IsPathSeparator(path[r]); r++ { out.append(path[r]) } } } // Turn empty string into "." if out.w == 0 { out.append('.') } return FromSlash(out.string()) } // ToSlash returns the result of replacing each separator character // in path with a slash ('/') character. Multiple separators are // replaced by multiple slashes. func ToSlash(path string) string { if Separator == '/' { return path } return strings.Replace(path, string(Separator), "/", -1) } // FromSlash returns the result of replacing each slash ('/') character // in path with a separator character. Multiple slashes are replaced // by multiple separators. func FromSlash(path string) string { if Separator == '/' { return path } return strings.Replace(path, "/", string(Separator), -1) } // SplitList splits a list of paths joined by the OS-specific ListSeparator, // usually found in PATH or GOPATH environment variables. // Unlike strings.Split, SplitList returns an empty slice when passed an empty // string. func SplitList(path string) []string { return splitList(path) } // Split splits path immediately following the final Separator, // separating it into a directory and file name component. // If there is no Separator in path, Split returns an empty dir // and file set to path. // The returned values have the property that path = dir+file. func Split(path string) (dir, file string) { vol := VolumeName(path) i := len(path) - 1 for i >= len(vol) && !os.IsPathSeparator(path[i]) { i } return path[:i+1], path[i+1:] } // Join joins any number of path elements into a single path, adding // a Separator if necessary. Join calls Clean on the result; in particular, // all empty strings are ignored. // On Windows, the result is a UNC path if and only if the first path // element is a UNC path. func Join(elem ...string) string { return join(elem) } // Ext returns the file name extension used by path. // The extension is the suffix beginning at the final dot // in the final element of path; it is empty if there is // no dot. func Ext(path string) string { for i := len(path) - 1; i >= 0 && !os.IsPathSeparator(path[i]); i if path[i] == '.' { return path[i:] } } return "" } // EvalSymlinks returns the path name after the evaluation of any symbolic // links. // If path is relative the result will be relative to the current directory, // unless one of the components is an absolute symbolic link. // EvalSymlinks calls Clean on the result. func EvalSymlinks(path string) (string, error) { return evalSymlinks(path) } // Abs returns an absolute representation of path. // If the path is not absolute it will be joined with the current // working directory to turn it into an absolute path. The absolute // path name for a given file is not guaranteed to be unique. // Abs calls Clean on the result. func Abs(path string) (string, error) { return abs(path) } func unixAbs(path string) (string, error) { if IsAbs(path) { return Clean(path), nil } wd, err := os.Getwd() if err != nil { return "", err } return Join(wd, path), nil } // Rel returns a relative path that is lexically equivalent to targpath when // joined to basepath with an intervening separator. That is, // Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. // On success, the returned path will always be relative to basepath, // even if basepath and targpath share no elements. // An error is returned if targpath can't be made relative to basepath or if // knowing the current working directory would be necessary to compute it. // Rel calls Clean on the result. func Rel(basepath, targpath string) (string, error) { baseVol := VolumeName(basepath) targVol := VolumeName(targpath) base := Clean(basepath) targ := Clean(targpath) if sameWord(targ, base) { return ".", nil } base = base[len(baseVol):] targ = targ[len(targVol):] if base == "." { base = "" } // Can't use IsAbs - `\a` and `a` are both relative in Windows. baseSlashed := len(base) > 0 && base[0] == Separator targSlashed := len(targ) > 0 && targ[0] == Separator if baseSlashed != targSlashed || !sameWord(baseVol, targVol) { return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath) } // Position base[b0:bi] and targ[t0:ti] at the first differing elements. bl := len(base) tl := len(targ) var b0, bi, t0, ti int for { for bi < bl && base[bi] != Separator { bi++ } for ti < tl && targ[ti] != Separator { ti++ } if !sameWord(targ[t0:ti], base[b0:bi]) { break } if bi < bl { bi++ } if ti < tl { ti++ } b0 = bi t0 = ti } if base[b0:bi] == ".." { return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath) } if b0 != bl { // Base elements left. Must go up before going down. seps := strings.Count(base[b0:bl], string(Separator)) size := 2 + seps*3 if tl != t0 { size += 1 + tl - t0 } buf := make([]byte, size) n := copy(buf, "..") for i := 0; i < seps; i++ { buf[n] = Separator copy(buf[n+1:], "..") n += 3 } if t0 != tl { buf[n] = Separator copy(buf[n+1:], targ[t0:]) } return string(buf), nil } return targ[t0:], nil } // SkipDir is used as a return value from WalkFuncs to indicate that // the directory named in the call is to be skipped. It is not returned // as an error by any function. var SkipDir = errors.New("skip this directory") // WalkFunc is the type of the function called for each file or directory // visited by Walk. The path argument contains the argument to Walk as a // prefix; that is, if Walk is called with "dir", which is a directory // containing the file "a", the walk function will be called with argument // "dir/a". The info argument is the os.FileInfo for the named path. // If there was a problem walking to the file or directory named by path, the // incoming error will describe the problem and the function can decide how // to handle that error (and Walk will not descend into that directory). If // an error is returned, processing stops. The sole exception is when the function // returns the special value SkipDir. If the function returns SkipDir when invoked // on a directory, Walk skips the directory's contents entirely. // If the function returns SkipDir when invoked on a non-directory file, // Walk skips the remaining files in the containing directory. type WalkFunc func(path string, info os.FileInfo, err error) error var lstat = os.Lstat // for testing // walk recursively descends path, calling w. func walk(path string, info os.FileInfo, walkFn WalkFunc) error { err := walkFn(path, info, nil) if err != nil { if info.IsDir() && err == SkipDir { return nil } return err } if !info.IsDir() { return nil } names, err := readDirNames(path) if err != nil { return walkFn(path, info, err) } for _, name := range names { filename := Join(path, name) fileInfo, err := lstat(filename) if err != nil { if err := walkFn(filename, fileInfo, err); err != nil && err != SkipDir { return err } } else { err = walk(filename, fileInfo, walkFn) if err != nil { if !fileInfo.IsDir() || err != SkipDir { return err } } } } return nil } // Walk walks the file tree rooted at root, calling walkFn for each file or // directory in the tree, including root. All errors that arise visiting files // and directories are filtered by walkFn. The files are walked in lexical // order, which makes the output deterministic but means that for very // large directories Walk can be inefficient. // Walk does not follow symbolic links. func Walk(root string, walkFn WalkFunc) error { info, err := os.Lstat(root) if err != nil { err = walkFn(root, nil, err) } else { err = walk(root, info, walkFn) } if err == SkipDir { return nil } return err } // readDirNames reads the directory named by dirname and returns // a sorted list of directory entries. func readDirNames(dirname string) ([]string, error) { f, err := os.Open(dirname) if err != nil { return nil, err } names, err := f.Readdirnames(-1) f.Close() if err != nil { return nil, err } sort.Strings(names) return names, nil } // Base returns the last element of path. // Trailing path separators are removed before extracting the last element. // If the path is empty, Base returns ".". // If the path consists entirely of separators, Base returns a single separator. func Base(path string) string { if path == "" { return "." } // Strip trailing slashes. for len(path) > 0 && os.IsPathSeparator(path[len(path)-1]) { path = path[0 : len(path)-1] } // Throw away volume name path = path[len(VolumeName(path)):] // Find the last element i := len(path) - 1 for i >= 0 && !os.IsPathSeparator(path[i]) { i } if i >= 0 { path = path[i+1:] } // If empty now, it had only slashes. if path == "" { return string(Separator) } return path } // Dir returns all but the last element of path, typically the path's directory. // After dropping the final element, Dir calls Clean on the path and trailing // slashes are removed. // If the path is empty, Dir returns ".". // If the path consists entirely of separators, Dir returns a single separator. // The returned path does not end in a separator unless it is the root directory. func Dir(path string) string { vol := VolumeName(path) i := len(path) - 1 for i >= len(vol) && !os.IsPathSeparator(path[i]) { i } dir := Clean(path[len(vol) : i+1]) if dir == "." && len(vol) > 2 { // must be UNC return vol } return vol + dir } // VolumeName returns leading volume name. // Given "C:\foo\bar" it returns "C:" on Windows. // Given "\\host\share\foo" it returns "\\host\share". // On other platforms it returns "". func VolumeName(path string) string { return path[:volumeNameLen(path)] }
package edu.cornell.mannlib.vitro.webapp.rdfservice.adapters; import org.apache.jena.graph.Graph; import org.apache.jena.graph.compose.MultiUnion; import java.util.List; final public class GraphUtils { public static Graph unwrapUnionGraphs(Graph graph) { if (graph != null && graph instanceof MultiUnion) { List<Graph> subGraphs = ((MultiUnion)graph).getSubGraphs(); if (subGraphs == null || subGraphs.isEmpty()) { return ((MultiUnion)graph).getBaseGraph(); } } return graph; } }
<?php namespace Phalcon\Flash { /** * Phalcon\Flash\Direct * * This is a variant of the Phalcon\Flash that inmediately outputs any message passed to it */ class Direct extends \Phalcon\Flash implements \Phalcon\FlashInterface { /** * Outputs a message * * @param string $type * @param string $message * * @return string */ public function message($type, $message) { return $this->outputMessage($type, $message); } } }
package apps.mtdesktop.messages; import java.util.List; import synergynetframework.appsystem.services.net.localpresence.TableIdentity; import synergynetframework.appsystem.services.net.objectmessaging.messages.UDPMessage; import synergynetframework.appsystem.services.net.tablecomms.messages.application.<API key>; import apps.mtdesktop.messages.util.MouseEventInfo; /** * The Class MouseEventsMessage. */ public class MouseEventsMessage extends <API key> implements UDPMessage { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 832254747031925652L; /** The mouse events. */ private List<MouseEventInfo> mouseEvents; /** * Instantiates a new mouse events message. */ public MouseEventsMessage() { super(); } /** * Instantiates a new mouse events message. * * @param targetClass * the target class * @param targetTableId * the target table id * @param events * the events */ public MouseEventsMessage(Class<?> targetClass, TableIdentity targetTableId, List<MouseEventInfo> events) { super(targetClass); this.setRecipient(targetTableId); mouseEvents = events; } /** * Gets the mouse events. * * @return the mouse events */ public List<MouseEventInfo> getMouseEvents() { return mouseEvents; } /** * Sets the mouse events. * * @param mouseEvents * the new mouse events */ public void setMouseEvents(List<MouseEventInfo> mouseEvents) { this.mouseEvents = mouseEvents; } }