code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
// Copyright 2016 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package gitea import ( "bytes" "encoding/json" "fmt" "time" ) // StateType issue state type type StateType string const ( // StateOpen pr is opend StateOpen StateType = "open" // StateClosed pr is closed StateClosed StateType = "closed" ) // PullRequestMeta PR info if an issue is a PR type PullRequestMeta struct { HasMerged bool `json:"merged"` Merged *time.Time `json:"merged_at"` } // Issue represents an issue in a repository // swagger:model type Issue struct { ID int64 `json:"id"` URL string `json:"url"` Index int64 `json:"number"` Poster *User `json:"user"` Title string `json:"title"` Body string `json:"body"` Labels []*Label `json:"labels"` Milestone *Milestone `json:"milestone"` Assignee *User `json:"assignee"` Assignees []*User `json:"assignees"` // Whether the issue is open or closed // // type: string // enum: open,closed State StateType `json:"state"` Comments int `json:"comments"` // swagger:strfmt date-time Created time.Time `json:"created_at"` // swagger:strfmt date-time Updated time.Time `json:"updated_at"` // swagger:strfmt date-time Closed *time.Time `json:"closed_at"` // swagger:strfmt date-time Deadline *time.Time `json:"due_date"` PullRequest *PullRequestMeta `json:"pull_request"` } // ListIssueOption list issue options type ListIssueOption struct { Page int State string } // ListIssues returns all issues assigned the authenticated user func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, error) { issues := make([]*Issue, 0, 10) return issues, c.getParsedResponse("GET", fmt.Sprintf("/issues?page=%d", opt.Page), nil, nil, &issues) } // ListUserIssues returns all issues assigned to the authenticated user func (c *Client) ListUserIssues(opt ListIssueOption) ([]*Issue, error) { issues := make([]*Issue, 0, 10) return issues, c.getParsedResponse("GET", fmt.Sprintf("/user/issues?page=%d", opt.Page), nil, nil, &issues) } // ListRepoIssues returns all issues for a given repository func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Issue, error) { issues := make([]*Issue, 0, 10) return issues, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues?page=%d", owner, repo, opt.Page), nil, nil, &issues) } // GetIssue returns a single issue for a given repository func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, error) { issue := new(Issue) return issue, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), nil, nil, issue) } // CreateIssueOption options to create one issue type CreateIssueOption struct { // required:true Title string `json:"title" binding:"Required"` Body string `json:"body"` // username of assignee Assignee string `json:"assignee"` Assignees []string `json:"assignees"` // swagger:strfmt date-time Deadline *time.Time `json:"due_date"` // milestone id Milestone int64 `json:"milestone"` // list of label ids Labels []int64 `json:"labels"` Closed bool `json:"closed"` } // CreateIssue create a new issue for a given repository func (c *Client) CreateIssue(owner, repo string, opt CreateIssueOption) (*Issue, error) { body, err := json.Marshal(&opt) if err != nil { return nil, err } issue := new(Issue) return issue, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues", owner, repo), jsonHeader, bytes.NewReader(body), issue) } // EditIssueOption options for editing an issue type EditIssueOption struct { Title string `json:"title"` Body *string `json:"body"` Assignee *string `json:"assignee"` Assignees []string `json:"assignees"` Milestone *int64 `json:"milestone"` State *string `json:"state"` // swagger:strfmt date-time Deadline *time.Time `json:"due_date"` } // EditIssue modify an existing issue for a given repository func (c *Client) EditIssue(owner, repo string, index int64, opt EditIssueOption) (*Issue, error) { body, err := json.Marshal(&opt) if err != nil { return nil, err } issue := new(Issue) return issue, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), jsonHeader, bytes.NewReader(body), issue) } // EditDeadlineOption options for creating a deadline type EditDeadlineOption struct { // required:true // swagger:strfmt date-time Deadline *time.Time `json:"due_date"` } // IssueDeadline represents an issue deadline // swagger:model type IssueDeadline struct { // swagger:strfmt date-time Deadline *time.Time `json:"due_date"` }
tboerger/gitea
vendor/code.gitea.io/sdk/gitea/issue.go
GO
mit
4,741
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_AndroidManagement_ApplicationPolicy extends Google_Collection { protected $collection_key = 'permissionGrants'; public $defaultPermissionPolicy; public $delegatedScopes; public $installType; public $lockTaskAllowed; public $managedConfiguration; public $minimumVersionCode; public $packageName; protected $permissionGrantsType = 'Google_Service_AndroidManagement_PermissionGrant'; protected $permissionGrantsDataType = 'array'; public function setDefaultPermissionPolicy($defaultPermissionPolicy) { $this->defaultPermissionPolicy = $defaultPermissionPolicy; } public function getDefaultPermissionPolicy() { return $this->defaultPermissionPolicy; } public function setDelegatedScopes($delegatedScopes) { $this->delegatedScopes = $delegatedScopes; } public function getDelegatedScopes() { return $this->delegatedScopes; } public function setInstallType($installType) { $this->installType = $installType; } public function getInstallType() { return $this->installType; } public function setLockTaskAllowed($lockTaskAllowed) { $this->lockTaskAllowed = $lockTaskAllowed; } public function getLockTaskAllowed() { return $this->lockTaskAllowed; } public function setManagedConfiguration($managedConfiguration) { $this->managedConfiguration = $managedConfiguration; } public function getManagedConfiguration() { return $this->managedConfiguration; } public function setMinimumVersionCode($minimumVersionCode) { $this->minimumVersionCode = $minimumVersionCode; } public function getMinimumVersionCode() { return $this->minimumVersionCode; } public function setPackageName($packageName) { $this->packageName = $packageName; } public function getPackageName() { return $this->packageName; } /** * @param Google_Service_AndroidManagement_PermissionGrant */ public function setPermissionGrants($permissionGrants) { $this->permissionGrants = $permissionGrants; } /** * @return Google_Service_AndroidManagement_PermissionGrant */ public function getPermissionGrants() { return $this->permissionGrants; } }
githubmoros/myclinicsoft
vendor/google/apiclient-services/src/Google/Service/AndroidManagement/ApplicationPolicy.php
PHP
mit
2,807
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "nt\u0254\u0301ng\u0254\u0301", "mp\u00f3kwa" ], "DAY": [ "eyenga", "mok\u0254l\u0254 mwa yambo", "mok\u0254l\u0254 mwa m\u00edbal\u00e9", "mok\u0254l\u0254 mwa m\u00eds\u00e1to", "mok\u0254l\u0254 ya m\u00edn\u00e9i", "mok\u0254l\u0254 ya m\u00edt\u00e1no", "mp\u0254\u0301s\u0254" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "s\u00e1nz\u00e1 ya yambo", "s\u00e1nz\u00e1 ya m\u00edbal\u00e9", "s\u00e1nz\u00e1 ya m\u00eds\u00e1to", "s\u00e1nz\u00e1 ya m\u00ednei", "s\u00e1nz\u00e1 ya m\u00edt\u00e1no", "s\u00e1nz\u00e1 ya mot\u00f3b\u00e1", "s\u00e1nz\u00e1 ya nsambo", "s\u00e1nz\u00e1 ya mwambe", "s\u00e1nz\u00e1 ya libwa", "s\u00e1nz\u00e1 ya z\u00f3mi", "s\u00e1nz\u00e1 ya z\u00f3mi na m\u0254\u030ck\u0254\u0301", "s\u00e1nz\u00e1 ya z\u00f3mi na m\u00edbal\u00e9" ], "SHORTDAY": [ "eye", "ybo", "mbl", "mst", "min", "mtn", "mps" ], "SHORTMONTH": [ "yan", "fbl", "msi", "apl", "mai", "yun", "yul", "agt", "stb", "\u0254tb", "nvb", "dsb" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "d/M/y HH:mm", "shortDate": "d/M/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "FrCD", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "ln-cd", "pluralCat": function(n, opt_precision) { if (n >= 0 && n <= 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
ereddate/angular.js
src/ngLocale/angular-locale_ln-cd.js
JavaScript
mit
2,486
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Function store</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../program_options/reference.html#header.boost.program_options.variables_map_hpp" title="Header &lt;boost/program_options/variables_map.hpp&gt;"> <link rel="prev" href="store_idp63083776.html" title="Function store"> <link rel="next" href="notify.html" title="Function notify"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="store_idp63083776.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../program_options/reference.html#header.boost.program_options.variables_map_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="notify.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.program_options.store_idp123268064"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Function store</span></h2> <p>boost::program_options::store</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../program_options/reference.html#header.boost.program_options.variables_map_hpp" title="Header &lt;boost/program_options/variables_map.hpp&gt;">boost/program_options/variables_map.hpp</a>&gt; </span> <span class="identifier">BOOST_PROGRAM_OPTIONS_DECL</span> <span class="keyword">void</span> <span class="identifier">store</span><span class="special">(</span><span class="keyword">const</span> <a class="link" href="basic_parsed_options.html" title="Class template basic_parsed_options">basic_parsed_options</a><span class="special">&lt;</span> <span class="keyword">wchar_t</span> <span class="special">&gt;</span> <span class="special">&amp;</span> options<span class="special">,</span> <a class="link" href="variables_map.html" title="Class variables_map">variables_map</a> <span class="special">&amp;</span> m<span class="special">)</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp371141696"></a><h2>Description</h2> <p>Stores in 'm' all options that are defined in 'options'. If 'm' already has a non-defaulted value of an option, that value is not changed, even if 'options' specify some value. This is wide character variant. </p> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2002-2004 Vladimir Prus<p>Distributed under the Boost Software License, Version 1.0. (See accompanying file <code class="filename">LICENSE_1_0.txt</code> or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="store_idp63083776.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../program_options/reference.html#header.boost.program_options.variables_map_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="notify.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
yinchunlong/abelkhan-1
ext/c++/thirdpart/c++/boost/doc/html/boost/program_options/store_idp123268064.html
HTML
mit
4,667
package org.knowm.xchange.bity; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; import org.knowm.xchange.bity.dto.account.BityInputTransaction; import org.knowm.xchange.bity.dto.account.BityOrder; import org.knowm.xchange.bity.dto.account.BityOutputTransaction; import org.knowm.xchange.bity.dto.marketdata.BityPair; import org.knowm.xchange.bity.dto.marketdata.BityTicker; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trades.TradeSortType; import org.knowm.xchange.dto.meta.CurrencyMetaData; import org.knowm.xchange.dto.meta.CurrencyPairMetaData; import org.knowm.xchange.dto.meta.ExchangeMetaData; import org.knowm.xchange.dto.trade.UserTrade; import org.knowm.xchange.dto.trade.UserTrades; public final class BityAdapters { private BityAdapters() {} public static UserTrades adaptTrades(List<BityOrder> orders) { final List<UserTrade> trades = new ArrayList<>(); for (BityOrder order : orders) { if (order.getStatus().equals("EXEC")) { trades.add(adaptTrade(order)); } } return new UserTrades(trades, TradeSortType.SortByTimestamp); } public static UserTrade adaptTrade(BityOrder order) { BityInputTransaction inputT = order.getBityInputTransactions().get(0); BityOutputTransaction outputT = order.getBityOutputTransactions().get(0); BigDecimal fee = inputT.getPaymentProcessorFee(); BigDecimal price = inputT.getAmount().divide(outputT.getAmount(), 6, RoundingMode.HALF_UP); CurrencyPair currencyPair = new CurrencyPair(outputT.getCurrency(), inputT.getCurrency()); Order.OrderType orderType = order.getCategory().contains("BUY") ? Order.OrderType.BID : Order.OrderType.ASK; BigDecimal amount = outputT.getAmount(); Date date = order.getTimestampCreated(); String orderId = order.getResourceUri(); return new UserTrade.Builder() .type(orderType) .originalAmount(amount) .currencyPair(currencyPair) .price(price) .timestamp(date) .id(orderId) .orderId(orderId) .feeAmount(fee) .feeCurrency(currencyPair.counter) .build(); } public static ExchangeMetaData adaptMetaData( List<BityPair> rawSymbols, ExchangeMetaData metaData) { List<CurrencyPair> currencyPairs = BityAdapters.adaptCurrencyPairs(rawSymbols); Map<CurrencyPair, CurrencyPairMetaData> pairsMap = metaData.getCurrencyPairs(); Map<Currency, CurrencyMetaData> currenciesMap = metaData.getCurrencies(); for (CurrencyPair c : currencyPairs) { if (!pairsMap.containsKey(c)) { pairsMap.put(c, null); } if (!currenciesMap.containsKey(c.base)) { currenciesMap.put(c.base, null); } if (!currenciesMap.containsKey(c.counter)) { currenciesMap.put(c.counter, null); } } return metaData; } public static List<CurrencyPair> adaptCurrencyPairs(Collection<BityPair> bityPairs) { List<CurrencyPair> currencyPairs = new ArrayList<>(); for (BityPair symbol : bityPairs) { currencyPairs.add(adaptCurrencyPair(symbol)); } return currencyPairs; } public static CurrencyPair adaptCurrencyPair(BityPair bityPair) { return new CurrencyPair(bityPair.getOutput(), bityPair.getInput()); } public static List<Ticker> adaptTickers(Collection<BityTicker> bityTickers) { List<Ticker> tickers = new ArrayList<>(); for (BityTicker ticker : bityTickers) { tickers.add(adaptTicker(ticker)); } return tickers; } public static Ticker adaptTicker(BityTicker bityTicker) { CurrencyPair currencyPair = new CurrencyPair(bityTicker.getSource(), bityTicker.getTarget()); BigDecimal last = bityTicker.getRate(); BigDecimal bid = bityTicker.getRateWeBuy(); BigDecimal ask = bityTicker.getRateWeSell(); Date timestamp = bityTicker.getTimestamp(); return new Ticker.Builder() .currencyPair(currencyPair) .last(last) .bid(bid) .ask(ask) .timestamp(timestamp) .build(); } }
douggie/XChange
xchange-bity/src/main/java/org/knowm/xchange/bity/BityAdapters.java
Java
mit
4,222
/*! * jQuery JavaScript Library v@VERSION * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: @DATE */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //
curt-labs/GoSurvey
public/dist/js/vendor/jquery/src/intro.js
JavaScript
mit
1,392
require File.dirname(__FILE__) + '/../spec_helper' describe PagesHelper do it "has the right amount of greediness on parsing wiki links" do self.stub!(:wiki_link).and_return "MONKEYS" wikified_body("hello[[there]]whats[[up]]").should == "<p>helloMONKEYSwhatsMONKEYS</p>" wikified_body("hello[[there|hai]]whats[[up|doc]]").should == "<p>helloMONKEYSwhatsMONKEYS</p>" end it "parses wiki links" do self.should_receive(:wiki_link).with("up", nil).and_return("MONKEYS") self.should_receive(:wiki_link).with("there", "hai").and_return("MONKEYS") wikified_body("hello[[there|hai]]whats[[up]]").should == "<p>helloMONKEYSwhatsMONKEYS</p>" end end describe PagesHelper do before do @wiki_word = "o hai" @link_text = "test" @perma_link = {:permalink => "o-hai"} @class_str = "class=\"new_wiki_link\"" end it "links to wiki permalink if page exists" do Page.should_receive(:exists?).with(@perma_link).and_return true link = wiki_link(@wiki_word, @link_text) link.should include(@link_text) link.should_not include(@wiki_word) link.should_not include(@class_str) end it "links to wiki permalink with proper style if page doesnot exist" do Page.should_receive(:exists?).with(@perma_link).and_return false link = wiki_link(@wiki_word, @link_text) link.should include(@link_text) link.should_not include(@wiki_word) link.should include(@class_str) end end describe PagesHelper do before do @site = mock_model(Site) @form = mock_model(Object) @attr = :body self.should_receive(:site).and_return @site end it "should render textarea if site disable teh" do @site.should_receive(:disable_teh).and_return true @form.should_receive(:text_area) text_input(@form, @attr) end it "should render tech if site enable teh" do @site.should_receive(:disable_teh).and_return false @form.should_not_receive(:text_area) self.should_receive(:textile_editor) text_input(@form, @attr) end end describe PagesHelper do before do @id = 1 @page = mock_model(Page) @version = mock_model(Page) @version2 = mock_model(Page) end it "checks existing page with same version" do Page.should_receive(:find).with(@id).and_return @page @page.should_receive(:version).and_return @version current_revision(@id, @version).should == true end it "checks existing page with different version" do Page.should_receive(:find).with(@id).and_return @page @page.should_receive(:version).and_return @version2 current_revision(@id, @version).should == false end it "checks non-existing page version" do Page.should_receive(:find).with(@id).and_return nil current_revision(@id, @version).should == false end end
queso/signal-wiki
spec/helpers/pages_helper_spec.rb
Ruby
mit
2,868
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace UICatalog { [Register ("SegmentedControlViewController")] public class SegmentedControlViewController : UITableViewController { [Outlet] private UISegmentedControl DefaultSegmentedControl { get; set; } [Outlet] private UISegmentedControl TintedSegmentedControl { get; set; } [Outlet] private UISegmentedControl CustomSegmentsSegmentedControl { get; set; } [Outlet] private UISegmentedControl CustomBackgroundSegmentedControl { get; set; } public SegmentedControlViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); ConfigureDefaultSegmentedControl (); ConfigureTintedSegmentedControl (); ConfigureCustomSegmentsSegmentedControl (); ConfigureCustomBackgroundSegmentedControl (); } private void ConfigureDefaultSegmentedControl() { DefaultSegmentedControl.Momentary = true; DefaultSegmentedControl.SetEnabled (false, 0); DefaultSegmentedControl.ValueChanged += SelectedSegmentDidChange; } private void ConfigureTintedSegmentedControl() { TintedSegmentedControl.TintColor = ApplicationColors.Blue; TintedSegmentedControl.SelectedSegment = 1; TintedSegmentedControl.ValueChanged += SelectedSegmentDidChange; } private void ConfigureCustomSegmentsSegmentedControl() { var imageToAccessibilityLabelMappings = new Dictionary<string, string> { { "checkmark_icon", "Done".Localize () }, { "search_icon", "Search".Localize () }, { "tools_icon", "Settings".Localize () } }; // Guarantee that the segments show up in the same order. string[] sortedSegmentImageNames = imageToAccessibilityLabelMappings.Keys.ToArray (); Array.Sort (sortedSegmentImageNames); for (int i = 0; i < sortedSegmentImageNames.Length; i++) { string segmentImageName = sortedSegmentImageNames [i]; var image = UIImage.FromBundle (segmentImageName); image.AccessibilityLabel = imageToAccessibilityLabelMappings [segmentImageName]; CustomSegmentsSegmentedControl.SetImage (image, i); } CustomSegmentsSegmentedControl.SelectedSegment = 0; CustomSegmentsSegmentedControl.ValueChanged += SelectedSegmentDidChange; } private void ConfigureCustomBackgroundSegmentedControl() { CustomBackgroundSegmentedControl.SelectedSegment = 2; CustomBackgroundSegmentedControl.SetBackgroundImage (UIImage.FromBundle ("stepper_and_segment_background"), UIControlState.Normal, UIBarMetrics.Default); CustomBackgroundSegmentedControl.SetBackgroundImage (UIImage.FromBundle ("stepper_and_segment_background_disabled"), UIControlState.Disabled, UIBarMetrics.Default); CustomBackgroundSegmentedControl.SetBackgroundImage (UIImage.FromBundle ("stepper_and_segment_background_highlighted"), UIControlState.Highlighted, UIBarMetrics.Default); CustomBackgroundSegmentedControl.SetDividerImage (UIImage.FromBundle ("stepper_and_segment_divider"), UIControlState.Normal, UIControlState.Normal, UIBarMetrics.Default); var font = UIFont.FromDescriptor (UIFontDescriptor.PreferredCaption1, 0f); UITextAttributes normalTextAttributes = new UITextAttributes { TextColor = ApplicationColors.Purple, Font = font }; CustomBackgroundSegmentedControl.SetTitleTextAttributes (normalTextAttributes, UIControlState.Normal); UITextAttributes highlightedTextAttributes = new UITextAttributes { TextColor = ApplicationColors.Green, Font = font }; CustomBackgroundSegmentedControl.SetTitleTextAttributes (highlightedTextAttributes, UIControlState.Highlighted); CustomBackgroundSegmentedControl.ValueChanged += SelectedSegmentDidChange; } private void SelectedSegmentDidChange (object sender, EventArgs e) { Console.WriteLine ("The selected segment changed for: {0}", sender); } } }
nervevau2/monotouch-samples
ios8/UICatalog/UICatalog/ViewControllers/SegmentedControlViewController.cs
C#
mit
3,891
CoffeeScript.tmbundle --------------------- A **TextMate Bundle** for the **CoffeeScript** programming language. Installation: ------------- **TextMate 2:** You can install this bundle in TextMate by opening the preferences and going to the bundles tab. After installation it will be automatically updated for you. **TextMate 1.x:** [Use the original bundle](https://github.com/jashkenas/coffee-script-tmbundle). The bundle includes syntax highlighting, the ability to compile or evaluate CoffeeScript inline, convenient symbol listing for functions, and a number of expando snippets. Patches for additions are always welcome. ![screenshot](http://jashkenas.s3.amazonaws.com/images/coffeescript/textmate-highlighting.png)
msmiley/coffee-script.tmbundle
README.markdown
Markdown
mit
729
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example32-production</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.6/angular.min.js"></script> </head> <body ng-app=""> <input ng-keydown="count = count + 1" ng-init="count=0"> key down count: {{count}} </body> </html>
Eruant/angular-boilerplate
src/lib/docs/examples/example-example32/index-production.html
HTML
mit
355
'use strict'; const chalk = require('chalk'); const detect = require('detect-port-alt'); const getProcessForPort = require('./getProcessForPort'); function isRoot() { return process.getuid && process.getuid() === 0; } function checkDetectPort(port, host) { port = parseInt(port, 10) || 0; return new Promise((resolve, reject) => { detect(port, host, (err, _port) => { if (err) { reject(err); } else { if (port === _port) { resolve(port); } else { let message = `目前 ${chalk.bold(port)} 端口被占用`; if ( process.platform !== 'win32' && port < 1024 && !isRoot() ) { message = '`在1024以下的端口上运行服务器需要管理员权限`'; } const existingProcess = getProcessForPort(port); if (existingProcess) { message += `,该端口使用情况:\n ${existingProcess}`; } reject({ message: chalk.yellow(message), }); } } }); }); } module.exports = checkDetectPort;
kidney/guido
lib/utils/checkDetectPort.js
JavaScript
mit
1,014
<?php # Copyright (c) 2012 John Reese # Licensed under the MIT license form_security_validate( 'plugin_Source_repo_import_full' ); access_ensure_global_level( plugin_config_get( 'manage_threshold' ) ); $f_repo_id = gpc_get_string( 'id' ); $t_repo = SourceRepo::load( $f_repo_id ); $t_vcs = SourceVCS::repo( $t_repo ); helper_ensure_confirmed( plugin_lang_get( 'ensure_import_full' ), plugin_lang_get( 'import_full' ) ); helper_begin_long_process(); layout_page_header( plugin_lang_get( 'title' ) ); layout_page_begin(); # create a new, temporary repo $t_new_repo = SourceRepo::load( $f_repo_id ); $t_new_repo->id = 0; $t_new_repo->name = 'Import ' . date( 'Y-m-d H:i:s' ); $t_new_repo->save(); # Set the temp repo's name so it displays the correct value during import # and when saved at the end $t_new_repo->name = $t_repo->name; # keep checking for more changesets to import $t_error = false; while( true ) { # import the next batch of changesets $t_changesets = $t_vcs->import_full( $t_new_repo ); # check for errors if ( !is_array( $t_changesets ) ) { $t_error = true; break; } # if no more entries, we're done if ( count( $t_changesets ) < 1 ) { break; } Source_Process_Changesets( $t_changesets, $t_new_repo ); } # if we errored, delete the new repo and stop if ( $t_error ) { SourceRepo::delete( $t_new_repo->id ); echo '<br/><div class="center">'; echo plugin_lang_get( 'import_full_failed' ), '<br/>'; print_small_button( plugin_page( 'repo_manage_page' ) . '&id=' . $t_repo->id, plugin_lang_get( 'back_repo' ) ); echo '</div>'; # otherwise, rename and save the new repo, then delete the old } else { $t_new_repo->save(); SourceRepo::delete( $t_repo->id ); $t_stats = $t_new_repo->stats(); echo '<br/><div class="center">'; echo sprintf( plugin_lang_get( 'import_stats' ), $t_stats['changesets'], $t_stats['files'], $t_stats['bugs'] ), '<br/>'; print_small_button( plugin_page( 'repo_manage_page' ) . '&id=' . $t_new_repo->id, plugin_lang_get( 'back_repo' ) ); echo '</div>'; } form_security_purge( 'plugin_Source_repo_import_full' ); layout_page_end();
dregad/source-integration
Source/pages/repo_import_full.php
PHP
mit
2,111
using System.Collections.Generic; using System.Linq; using Windows.ApplicationModel.Resources; using Windows.Graphics.Display; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace AppStudio.Common.Actions { public class ActionsCommandBar : CommandBar { public static readonly DependencyProperty ActionsSourceProperty = DependencyProperty.Register("ActionsSource", typeof(List<ActionInfo>), typeof(ActionsCommandBar), new PropertyMetadata(null, ActionsSourcePropertyChanged)); public static readonly DependencyProperty HideOnLandscapeProperty = DependencyProperty.Register("HideOnLandscape", typeof(bool), typeof(ActionsCommandBar), new PropertyMetadata(false)); public static readonly DependencyProperty IsVisibleProperty = DependencyProperty.Register("IsVisible", typeof(bool), typeof(ActionsCommandBar), new PropertyMetadata(true, OnIsVisiblePropertyChanged)); private static void OnIsVisiblePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var self = d as ActionsCommandBar; bool isVisible = (bool)e.NewValue; if (isVisible) { self.Visibility = Visibility.Visible; } else { self.Visibility = Visibility.Collapsed; } } public ActionsCommandBar() { if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled) { DisplayInformation.GetForCurrentView().OrientationChanged += ((sender, args) => { UpdateVisibility(sender.CurrentOrientation); }); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Setter needed for binding.")] public List<ActionInfo> ActionsSource { get { return (List<ActionInfo>)GetValue(ActionsSourceProperty); } set { SetValue(ActionsSourceProperty, value); } } public bool HideOnLandscape { get { return (bool)GetValue(HideOnLandscapeProperty); } set { SetValue(HideOnLandscapeProperty, value); } } public bool IsVisible { get { return (bool)GetValue(IsVisibleProperty); } set { SetValue(IsVisibleProperty, value); } } private static void ActionsSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = d as ActionsCommandBar; if (control != null) { foreach (var action in control.ActionsSource) { var label = GetText(action); var button = FindButton(label, control); if (button == null) { button = new AppBarButton(); if (action.ActionType == ActionType.Primary) { control.PrimaryCommands.Add(button); } else if (action.ActionType == ActionType.Secondary) { control.SecondaryCommands.Add(button); } } button.Command = action.Command; button.CommandParameter = action.CommandParameter; button.Label = label; if (Application.Current.Resources.ContainsKey(action.Style)) { button.Style = Application.Current.Resources[action.Style] as Style; } } } } private static string GetText(ActionInfo action) { var resourceLoader = new ResourceLoader(); string text = null; if (!string.IsNullOrEmpty(action.Name)) { text = resourceLoader.GetString(string.Format("{0}/Label", action.Name)); } if (string.IsNullOrEmpty(text)) { text = action.Text; } return text; } private static AppBarButton FindButton(string label, ActionsCommandBar bar) { return bar.PrimaryCommands .OfType<AppBarButton>() .Union(bar.SecondaryCommands.OfType<AppBarButton>()) .FirstOrDefault(b => b.Label == label); } private void UpdateVisibility(DisplayOrientations orientation) { if (HideOnLandscape) { if (orientation == Windows.Graphics.Display.DisplayOrientations.Landscape || orientation == Windows.Graphics.Display.DisplayOrientations.LandscapeFlipped) { this.Visibility = Visibility.Collapsed; } else if (orientation == Windows.Graphics.Display.DisplayOrientations.Portrait || orientation == Windows.Graphics.Display.DisplayOrientations.PortraitFlipped) { this.Visibility = Visibility.Visible; } } } } }
pellea/waslibs
src/AppStudio.Common/Actions/ActionsCommandBar.cs
C#
mit
5,425
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="../test/css/main.css"> <script type="text/javascript" src="../test/bower_components/jquery/jquery.min.js"></script> <script type="text/javascript" src="../test/config.js"></script> </head> <body> <div id="container"> </div> <script type="text/javascript" src = "./housing-pano-fallback.js"></script> <script> DirectPano.show_fallback_pano(); </script> </body> </html>
gopinathkoteru/Housing_Panorama
lib/try.html
HTML
mit
530
using AllReady.Models; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Mvc.Rendering; using AllReady.Extensions; using System; using Microsoft.Data.Entity; using System.Threading.Tasks; namespace AllReady.Services { public class SelectListService : ISelectListService { private readonly AllReadyContext _context; public SelectListService(AllReadyContext context) { _context = context; } public IEnumerable<SelectListItem> GetOrganizations() { return _context.Organizations.Select(t => new SelectListItem {Value = t.Id.ToString(), Text = t.Name }); } public async Task<IEnumerable<SelectListItem>> GetOrganizationsAsync() { return await _context.Organizations .Select(t => new SelectListItem { Value = t.Id.ToString(), Text = t.Name }) .ToListAsync(); } public IEnumerable<Skill> GetSkills() { return _context.Skills.ToList() //Project HierarchicalName onto Name .Select(s => new Skill { Id = s.Id, Name = s.HierarchicalName, Description = s.Description }) .OrderBy(s => s.Name); } public async Task<IEnumerable<Skill>> GetSkillsAsync() { return await _context.Skills.AsNoTracking() //Project HierarchicalName onto Name .Select(s => new Skill { Id = s.Id, Name = s.HierarchicalName, Description = s.Description }) .OrderBy(s => s.Name) .ToListAsync(); } public IEnumerable<SelectListItem> GetCampaignImpactTypes() { return new List<SelectListItem> { new SelectListItem { Value = ((int)ImpactType.Text).ToString(), Text = ImpactType.Text.GetDisplayName() }, new SelectListItem { Value = ((int)ImpactType.Numeric).ToString(), Text = ImpactType.Numeric.GetDisplayName() } }; } public IEnumerable<SelectListItem> GetTimeZones() { return TimeZoneInfo.GetSystemTimeZones().Select(t => new SelectListItem { Value = t.Id, Text = t.DisplayName }); } } public static class SelectListExtensions { public static IEnumerable<SelectListItem> AddNullOptionToFront(this IEnumerable<SelectListItem> items, string text = "<None>", string value = "") { var list = items.ToList(); list.Insert(0, new SelectListItem() { Text = text, Value = value }); return list; } public static IEnumerable<SelectListItem> AddNullOptionToEnd(this IEnumerable<SelectListItem> items, string text = "<None>", string value = "") { var list = items.ToList(); list.Add(new SelectListItem() { Text = text, Value = value }); return list; } } }
aliiftikhar/allReady
AllReadyApp/Web-App/AllReady/Services/SelectListService.cs
C#
mit
3,030
/* * The MIT License (MIT) * * Copyright (c) 2014-2015 Umeng, Inc * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.tech.frontier.net.handlers; import org.json.JSONArray; import org.json.JSONObject; import org.tech.frontier.entities.Recommend; import java.util.ArrayList; import java.util.List; public class RecommendHandler implements RespHandler<List<Recommend>, JSONArray> { @Override public List<Recommend> parse(JSONArray data) { List<Recommend> recomendList = new ArrayList<Recommend>(); int length = data.length(); for (int i = 0; i < length; i++) { JSONObject jsonObject = data.optJSONObject(i); String title = jsonObject.optString("title"); String imgUrl = jsonObject.optString("img_url"); String url = jsonObject.optString("url"); recomendList.add(new Recommend(title, url, imgUrl)); } return recomendList; } }
Chanven/the-tech-frontier-app
src/org/tech/frontier/net/handlers/RecommendHandler.java
Java
mit
1,984
using System; using System.Collections.Generic; using System.Reflection; using Orleans.CodeGeneration; using Orleans.Utilities; namespace Orleans { /// <summary> /// Maintains a map between grain classes and corresponding interface-implementation mappings. /// </summary> internal class InterfaceToImplementationMappingCache { public struct Entry { public Entry(MethodInfo implementationMethod, MethodInfo interfaceMethod) { ImplementationMethod = implementationMethod; InterfaceMethod = interfaceMethod; } public MethodInfo ImplementationMethod { get; } public MethodInfo InterfaceMethod { get; } } /// <summary> /// The map from implementation types to interface ids to map of method ids to method infos. /// </summary> private readonly CachedReadConcurrentDictionary<Type, Dictionary<int, Dictionary<int, Entry>>> mappings = new CachedReadConcurrentDictionary<Type, Dictionary<int, Dictionary<int, Entry>>>(); /// <summary> /// Returns a mapping from method id to method info for the provided implementation and interface id. /// </summary> /// <param name="implementationType">The grain type.</param> /// <param name="interfaceId">The interface id.</param> /// <returns> /// A mapping from method id to method info. /// </returns> public Dictionary<int, Entry> GetOrCreate(Type implementationType, int interfaceId) { // Get or create the mapping between interfaceId and invoker for the provided type. if (!this.mappings.TryGetValue(implementationType, out var invokerMap)) { // Generate an the invoker mapping using the provided invoker. this.mappings[implementationType] = invokerMap = CreateInterfaceToImplementationMap(implementationType); } // Attempt to get the invoker for the provided interfaceId. if (!invokerMap.TryGetValue(interfaceId, out var interfaceToImplementationMap)) { throw new InvalidOperationException( $"Type {implementationType} does not implement interface with id {interfaceId} ({interfaceId:X})."); } return interfaceToImplementationMap; } /// <summary> /// Maps the interfaces of the provided <paramref name="implementationType"/>. /// </summary> /// <param name="implementationType">The implementation type.</param> /// <returns>The mapped interface.</returns> private static Dictionary<int, Dictionary<int, Entry>> CreateInterfaceToImplementationMap(Type implementationType) { if (implementationType.IsConstructedGenericType) return CreateMapForConstructedGeneric(implementationType); return CreateMapForNonGeneric(implementationType); } /// <summary> /// Creates and returns a map from interface id to map of method id to method info for the provided non-generic type. /// </summary> /// <param name="implementationType">The implementation type.</param> /// <returns>A map from interface id to map of method id to method info for the provided type.</returns> private static Dictionary<int, Dictionary<int, Entry>> CreateMapForNonGeneric(Type implementationType) { if (implementationType.IsConstructedGenericType) { throw new InvalidOperationException( $"Type {implementationType} passed to {nameof(CreateMapForNonGeneric)} is a constructed generic type."); } var interfaces = implementationType.GetInterfaces(); // Create an invoker for every interface on the provided type. var result = new Dictionary<int, Dictionary<int, Entry>>(interfaces.Length); foreach (var iface in interfaces) { var methods = GrainInterfaceUtils.GetMethods(iface); // Map every method on this interface from the definition interface onto the implementation class. var methodMap = new Dictionary<int, Entry>(methods.Length); var mapping = default(InterfaceMapping); foreach (var method in methods) { // If this method is not from the expected interface (eg, because it's from a parent interface), then // get the mapping for the interface which it does belong to. if (mapping.InterfaceType != method.DeclaringType) { mapping = implementationType.GetTypeInfo().GetRuntimeInterfaceMap(method.DeclaringType); } // Find the index of the interface method and then get the implementation method at that position. for (var k = 0; k < mapping.InterfaceMethods.Length; k++) { if (mapping.InterfaceMethods[k] != method) continue; methodMap[GrainInterfaceUtils.ComputeMethodId(method)] = new Entry(mapping.TargetMethods[k], method); break; } } // Add the resulting map of methodId -> method to the interface map. var interfaceId = GrainInterfaceUtils.GetGrainInterfaceId(iface); result[interfaceId] = methodMap; } return result; } /// <summary> /// Creates and returns a map from interface id to map of method id to method info for the provided constructed generic type. /// </summary> /// <param name="implementationType">The implementation type.</param> /// <returns>A map from interface id to map of method id to method info for the provided type.</returns> private static Dictionary<int, Dictionary<int, Entry>> CreateMapForConstructedGeneric(Type implementationType) { // It is important to note that the interfaceId and methodId are computed based upon the non-concrete // version of the implementation type. During code generation, the concrete type would not be available // and therefore the generic type definition is used. if (!implementationType.IsConstructedGenericType) { throw new InvalidOperationException( $"Type {implementationType} passed to {nameof(CreateMapForConstructedGeneric)} is not a constructed generic type"); } var genericClass = implementationType.GetGenericTypeDefinition(); var genericInterfaces = genericClass.GetInterfaces(); var concreteInterfaces = implementationType.GetInterfaces(); // Create an invoker for every interface on the provided type. var result = new Dictionary<int, Dictionary<int, Entry>>(genericInterfaces.Length); for (var i = 0; i < genericInterfaces.Length; i++) { // Because these methods are identical except for type parameters, their methods should also be identical except // for type parameters, including identical ordering. That is the assumption. var genericMethods = GrainInterfaceUtils.GetMethods(genericInterfaces[i]); var concreteInterfaceMethods = GrainInterfaceUtils.GetMethods(concreteInterfaces[i]); // Map every method on this interface from the definition interface onto the implementation class. var methodMap = new Dictionary<int, Entry>(genericMethods.Length); var genericMap = default(InterfaceMapping); var concreteMap = default(InterfaceMapping); for (var j = 0; j < genericMethods.Length; j++) { // If this method is not from the expected interface (eg, because it's from a parent interface), then // get the mapping for the interface which it does belong to. var genericInterfaceMethod = genericMethods[j]; if (genericMap.InterfaceType != genericInterfaceMethod.DeclaringType) { genericMap = genericClass.GetTypeInfo().GetRuntimeInterfaceMap(genericInterfaceMethod.DeclaringType); concreteMap = implementationType.GetTypeInfo().GetRuntimeInterfaceMap(concreteInterfaceMethods[j].DeclaringType); } // Determine the position in the definition's map which the target method belongs to and take the implementation // from the same position on the implementation's map. for (var k = 0; k < genericMap.InterfaceMethods.Length; k++) { if (genericMap.InterfaceMethods[k] != genericInterfaceMethod) continue; methodMap[GrainInterfaceUtils.ComputeMethodId(genericInterfaceMethod)] = new Entry(concreteMap.TargetMethods[k], concreteMap.InterfaceMethods[k]); break; } } // Add the resulting map of methodId -> method to the interface map. var interfaceId = GrainInterfaceUtils.GetGrainInterfaceId(genericInterfaces[i]); result[interfaceId] = methodMap; } return result; } } }
pherbel/orleans
src/Orleans.Core/Core/InterfaceToImplementationMappingCache.cs
C#
mit
9,603
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Ordinal rules. * * This file is autogenerated by script: * http://go/generate_pluralrules.py * File generated from CLDR ver. 24 * * Before check in, this file could have been manually edited. This is to * incorporate changes before we could fix CLDR. All manual modification must be * documented in this section, and should be removed after those changes land to * CLDR. */ goog.provide('goog.i18n.ordinalRules'); /** * Ordinal pattern keyword * @enum {string} */ goog.i18n.ordinalRules.Keyword = { ZERO: 'zero', ONE: 'one', TWO: 'two', FEW: 'few', MANY: 'many', OTHER: 'other' }; /** * Default Ordinal select rule. * @param {number} n The count of items. * @param {number=} opt_precision optional, precision. * @return {goog.i18n.ordinalRules.Keyword} Default value. * @private */ goog.i18n.ordinalRules.defaultSelect_ = function(n, opt_precision) { return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Returns the fractional part of a number (3.1416 => 1416) * @param {number} n The count of items. * @return {number} The fractional part. * @private */ goog.i18n.ordinalRules.decimals_ = function(n) { var str = n + ''; var result = str.indexOf('.'); return (result == -1) ? 0 : str.length - result - 1; }; /** * Calculates v and f as per CLDR plural rules. * @param {number} n The count of items. * @param {number=} opt_precision optional, precision. * @return {Object} The v and f. * @private */ goog.i18n.ordinalRules.get_vf_ = function(n, opt_precision) { var DEFAULT_DIGITS = 3; if (undefined === opt_precision) { var v = Math.min(goog.i18n.ordinalRules.decimals_(n), DEFAULT_DIGITS); } else { var v = opt_precision; } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {'v': v, 'f': f}; }; /** * Calculates w and t as per CLDR plural rules. * @param {number} v Calculated previously. * @param {number} f Calculated previously. * @return {Object} The w and t. * @private */ goog.i18n.ordinalRules.get_wt_ = function(v, f) { if (f === 0) { return {'w': 0, 't': 0}; } while ((f % 10) === 0) { f /= 10; v--; } return {'w': v, 't': f}; }; /** * Ordinal select rules for en locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.enSelect_ = function(n, opt_precision) { if (n % 10 == 1 && n % 100 != 11) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n % 10 == 2 && n % 100 != 12) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n % 10 == 3 && n % 100 != 13) { return goog.i18n.ordinalRules.Keyword.FEW; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for sv locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.svSelect_ = function(n, opt_precision) { if ((n % 10 == 1 || n % 10 == 2) && n % 100 != 11 && n % 100 != 12) { return goog.i18n.ordinalRules.Keyword.ONE; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for fr locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.frSelect_ = function(n, opt_precision) { if (n == 1) { return goog.i18n.ordinalRules.Keyword.ONE; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for hu locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.huSelect_ = function(n, opt_precision) { if (n == 1 || n == 5) { return goog.i18n.ordinalRules.Keyword.ONE; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for zu locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.zuSelect_ = function(n, opt_precision) { if (n == 1) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n >= 2 && n <= 9) { return goog.i18n.ordinalRules.Keyword.FEW; } if (n >= 10 && n <= 19 || n >= 100 && n <= 199 || n >= 1000 && n <= 1999) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for mr locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.mrSelect_ = function(n, opt_precision) { if (n == 1) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n == 2 || n == 3) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n == 4) { return goog.i18n.ordinalRules.Keyword.FEW; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for ca locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.caSelect_ = function(n, opt_precision) { if (n == 1 || n == 3) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n == 2) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n == 4) { return goog.i18n.ordinalRules.Keyword.FEW; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for bn locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.bnSelect_ = function(n, opt_precision) { if (n == 1 || n == 5 || n == 7 || n == 8 || n == 9 || n == 10) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n == 2 || n == 3) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n == 4) { return goog.i18n.ordinalRules.Keyword.FEW; } if (n == 6) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for it locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.itSelect_ = function(n, opt_precision) { if (n == 11 || n == 8 || n == 80 || n == 800) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for gu locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.guSelect_ = function(n, opt_precision) { if (n == 1) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n == 2 || n == 3) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n == 4) { return goog.i18n.ordinalRules.Keyword.FEW; } if (n == 6) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Selected Ordinal rules by locale. */ goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; if (goog.LOCALE == 'af') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'am') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ar') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'bg') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'bn') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.bnSelect_; } if (goog.LOCALE == 'br') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ca') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.caSelect_; } if (goog.LOCALE == 'chr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'cs') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'cy') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'da') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'de') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'de_AT' || goog.LOCALE == 'de-AT') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'de_CH' || goog.LOCALE == 'de-CH') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'el') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'en') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_AU' || goog.LOCALE == 'en-AU') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_GB' || goog.LOCALE == 'en-GB') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_IE' || goog.LOCALE == 'en-IE') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_IN' || goog.LOCALE == 'en-IN') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_ISO' || goog.LOCALE == 'en-ISO') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_SG' || goog.LOCALE == 'en-SG') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_US' || goog.LOCALE == 'en-US') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_ZA' || goog.LOCALE == 'en-ZA') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'es') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'es_419' || goog.LOCALE == 'es-419') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'es_ES' || goog.LOCALE == 'es-ES') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'et') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'eu') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'fa') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'fi') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'fil') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'fr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'fr_CA' || goog.LOCALE == 'fr-CA') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'gl') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'gsw') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'gu') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.guSelect_; } if (goog.LOCALE == 'haw') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'he') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'hi') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.guSelect_; } if (goog.LOCALE == 'hr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'hu') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.huSelect_; } if (goog.LOCALE == 'id') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'in') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'is') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'it') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.itSelect_; } if (goog.LOCALE == 'iw') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ja') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'kn') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ko') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ln') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'lt') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'lv') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ml') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'mo') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'mr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.mrSelect_; } if (goog.LOCALE == 'ms') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'mt') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'nb') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'nl') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'no') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'or') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'pl') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'pt') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'pt_BR' || goog.LOCALE == 'pt-BR') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'pt_PT' || goog.LOCALE == 'pt-PT') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ro') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'ru') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sk') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sl') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sq') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sv') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.svSelect_; } if (goog.LOCALE == 'sw') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ta') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'te') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'th') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'tl') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'tr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'uk') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ur') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'vi') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'zh') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'zh_CN' || goog.LOCALE == 'zh-CN') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'zh_HK' || goog.LOCALE == 'zh-HK') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'zh_TW' || goog.LOCALE == 'zh-TW') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'zu') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.zuSelect_; }
elynnlee/bright-bot
closure/library/closure/goog/i18n/ordinalrules.js
JavaScript
mit
17,909
////////////////////////////////////////////////////////////////////////////// // // Copyright (C) Microsoft Corporation. All Rights Reserved. // // File: d3dx9mesh.h // Content: D3DX mesh types and functions // ////////////////////////////////////////////////////////////////////////////// #include "d3dx9.h" #ifndef __D3DX9MESH_H__ #define __D3DX9MESH_H__ // {7ED943DD-52E8-40b5-A8D8-76685C406330} DEFINE_GUID(IID_ID3DXBaseMesh, 0x7ed943dd, 0x52e8, 0x40b5, 0xa8, 0xd8, 0x76, 0x68, 0x5c, 0x40, 0x63, 0x30); // {4020E5C2-1403-4929-883F-E2E849FAC195} DEFINE_GUID(IID_ID3DXMesh, 0x4020e5c2, 0x1403, 0x4929, 0x88, 0x3f, 0xe2, 0xe8, 0x49, 0xfa, 0xc1, 0x95); // {8875769A-D579-4088-AAEB-534D1AD84E96} DEFINE_GUID(IID_ID3DXPMesh, 0x8875769a, 0xd579, 0x4088, 0xaa, 0xeb, 0x53, 0x4d, 0x1a, 0xd8, 0x4e, 0x96); // {667EA4C7-F1CD-4386-B523-7C0290B83CC5} DEFINE_GUID(IID_ID3DXSPMesh, 0x667ea4c7, 0xf1cd, 0x4386, 0xb5, 0x23, 0x7c, 0x2, 0x90, 0xb8, 0x3c, 0xc5); // {11EAA540-F9A6-4d49-AE6A-E19221F70CC4} DEFINE_GUID(IID_ID3DXSkinInfo, 0x11eaa540, 0xf9a6, 0x4d49, 0xae, 0x6a, 0xe1, 0x92, 0x21, 0xf7, 0xc, 0xc4); // {3CE6CC22-DBF2-44f4-894D-F9C34A337139} DEFINE_GUID(IID_ID3DXPatchMesh, 0x3ce6cc22, 0xdbf2, 0x44f4, 0x89, 0x4d, 0xf9, 0xc3, 0x4a, 0x33, 0x71, 0x39); //patch mesh can be quads or tris typedef enum _D3DXPATCHMESHTYPE { D3DXPATCHMESH_RECT = 0x001, D3DXPATCHMESH_TRI = 0x002, D3DXPATCHMESH_NPATCH = 0x003, D3DXPATCHMESH_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ } D3DXPATCHMESHTYPE; // Mesh options - lower 3 bytes only, upper byte used by _D3DXMESHOPT option flags enum _D3DXMESH { D3DXMESH_32BIT = 0x001, // If set, then use 32 bit indices, if not set use 16 bit indices. D3DXMESH_DONOTCLIP = 0x002, // Use D3DUSAGE_DONOTCLIP for VB & IB. D3DXMESH_POINTS = 0x004, // Use D3DUSAGE_POINTS for VB & IB. D3DXMESH_RTPATCHES = 0x008, // Use D3DUSAGE_RTPATCHES for VB & IB. D3DXMESH_NPATCHES = 0x4000,// Use D3DUSAGE_NPATCHES for VB & IB. D3DXMESH_VB_SYSTEMMEM = 0x010, // Use D3DPOOL_SYSTEMMEM for VB. Overrides D3DXMESH_MANAGEDVERTEXBUFFER D3DXMESH_VB_MANAGED = 0x020, // Use D3DPOOL_MANAGED for VB. D3DXMESH_VB_WRITEONLY = 0x040, // Use D3DUSAGE_WRITEONLY for VB. D3DXMESH_VB_DYNAMIC = 0x080, // Use D3DUSAGE_DYNAMIC for VB. D3DXMESH_VB_SOFTWAREPROCESSING = 0x8000, // Use D3DUSAGE_SOFTWAREPROCESSING for VB. D3DXMESH_IB_SYSTEMMEM = 0x100, // Use D3DPOOL_SYSTEMMEM for IB. Overrides D3DXMESH_MANAGEDINDEXBUFFER D3DXMESH_IB_MANAGED = 0x200, // Use D3DPOOL_MANAGED for IB. D3DXMESH_IB_WRITEONLY = 0x400, // Use D3DUSAGE_WRITEONLY for IB. D3DXMESH_IB_DYNAMIC = 0x800, // Use D3DUSAGE_DYNAMIC for IB. D3DXMESH_IB_SOFTWAREPROCESSING= 0x10000, // Use D3DUSAGE_SOFTWAREPROCESSING for IB. D3DXMESH_VB_SHARE = 0x1000, // Valid for Clone* calls only, forces cloned mesh/pmesh to share vertex buffer D3DXMESH_USEHWONLY = 0x2000, // Valid for ID3DXSkinInfo::ConvertToBlendedMesh // Helper options D3DXMESH_SYSTEMMEM = 0x110, // D3DXMESH_VB_SYSTEMMEM | D3DXMESH_IB_SYSTEMMEM D3DXMESH_MANAGED = 0x220, // D3DXMESH_VB_MANAGED | D3DXMESH_IB_MANAGED D3DXMESH_WRITEONLY = 0x440, // D3DXMESH_VB_WRITEONLY | D3DXMESH_IB_WRITEONLY D3DXMESH_DYNAMIC = 0x880, // D3DXMESH_VB_DYNAMIC | D3DXMESH_IB_DYNAMIC D3DXMESH_SOFTWAREPROCESSING = 0x18000, // D3DXMESH_VB_SOFTWAREPROCESSING | D3DXMESH_IB_SOFTWAREPROCESSING }; //patch mesh options enum _D3DXPATCHMESH { D3DXPATCHMESH_DEFAULT = 000, }; // option field values for specifying min value in D3DXGeneratePMesh and D3DXSimplifyMesh enum _D3DXMESHSIMP { D3DXMESHSIMP_VERTEX = 0x1, D3DXMESHSIMP_FACE = 0x2, }; typedef enum _D3DXCLEANTYPE { D3DXCLEAN_BACKFACING = 0x00000001, D3DXCLEAN_BOWTIES = 0x00000002, // Helper options D3DXCLEAN_SKINNING = D3DXCLEAN_BACKFACING, // Bowtie cleaning modifies geometry and breaks skinning D3DXCLEAN_OPTIMIZATION = D3DXCLEAN_BACKFACING, D3DXCLEAN_SIMPLIFICATION= D3DXCLEAN_BACKFACING | D3DXCLEAN_BOWTIES, } D3DXCLEANTYPE; enum _MAX_FVF_DECL_SIZE { MAX_FVF_DECL_SIZE = MAXD3DDECLLENGTH + 1 // +1 for END }; typedef struct ID3DXBaseMesh *LPD3DXBASEMESH; typedef struct ID3DXMesh *LPD3DXMESH; typedef struct ID3DXPMesh *LPD3DXPMESH; typedef struct ID3DXSPMesh *LPD3DXSPMESH; typedef struct ID3DXSkinInfo *LPD3DXSKININFO; typedef struct ID3DXPatchMesh *LPD3DXPATCHMESH; typedef struct _D3DXATTRIBUTERANGE { DWORD AttribId; DWORD FaceStart; DWORD FaceCount; DWORD VertexStart; DWORD VertexCount; } D3DXATTRIBUTERANGE; typedef D3DXATTRIBUTERANGE* LPD3DXATTRIBUTERANGE; typedef struct _D3DXMATERIAL { D3DMATERIAL9 MatD3D; LPSTR pTextureFilename; } D3DXMATERIAL; typedef D3DXMATERIAL *LPD3DXMATERIAL; typedef enum _D3DXEFFECTDEFAULTTYPE { D3DXEDT_STRING = 0x1, // pValue points to a null terminated ASCII string D3DXEDT_FLOATS = 0x2, // pValue points to an array of floats - number of floats is NumBytes / sizeof(float) D3DXEDT_DWORD = 0x3, // pValue points to a DWORD D3DXEDT_FORCEDWORD = 0x7fffffff } D3DXEFFECTDEFAULTTYPE; typedef struct _D3DXEFFECTDEFAULT { LPSTR pParamName; D3DXEFFECTDEFAULTTYPE Type; // type of the data pointed to by pValue DWORD NumBytes; // size in bytes of the data pointed to by pValue LPVOID pValue; // data for the default of the effect } D3DXEFFECTDEFAULT, *LPD3DXEFFECTDEFAULT; typedef struct _D3DXEFFECTINSTANCE { LPSTR pEffectFilename; DWORD NumDefaults; LPD3DXEFFECTDEFAULT pDefaults; } D3DXEFFECTINSTANCE, *LPD3DXEFFECTINSTANCE; typedef struct _D3DXATTRIBUTEWEIGHTS { FLOAT Position; FLOAT Boundary; FLOAT Normal; FLOAT Diffuse; FLOAT Specular; FLOAT Texcoord[8]; FLOAT Tangent; FLOAT Binormal; } D3DXATTRIBUTEWEIGHTS, *LPD3DXATTRIBUTEWEIGHTS; enum _D3DXWELDEPSILONSFLAGS { D3DXWELDEPSILONS_WELDALL = 0x1, // weld all vertices marked by adjacency as being overlapping D3DXWELDEPSILONS_WELDPARTIALMATCHES = 0x2, // if a given vertex component is within epsilon, modify partial matched // vertices so that both components identical AND if all components "equal" // remove one of the vertices D3DXWELDEPSILONS_DONOTREMOVEVERTICES = 0x4, // instructs weld to only allow modifications to vertices and not removal // ONLY valid if D3DXWELDEPSILONS_WELDPARTIALMATCHES is set // useful to modify vertices to be equal, but not allow vertices to be removed D3DXWELDEPSILONS_DONOTSPLIT = 0x8, // instructs weld to specify the D3DXMESHOPT_DONOTSPLIT flag when doing an Optimize(ATTR_SORT) // if this flag is not set, all vertices that are in separate attribute groups // will remain split and not welded. Setting this flag can slow down software vertex processing }; typedef struct _D3DXWELDEPSILONS { FLOAT Position; // NOTE: This does NOT replace the epsilon in GenerateAdjacency // in general, it should be the same value or greater than the one passed to GeneratedAdjacency FLOAT BlendWeights; FLOAT Normal; FLOAT PSize; FLOAT Specular; FLOAT Diffuse; FLOAT Texcoord[8]; FLOAT Tangent; FLOAT Binormal; FLOAT TessFactor; } D3DXWELDEPSILONS; typedef D3DXWELDEPSILONS* LPD3DXWELDEPSILONS; #undef INTERFACE #define INTERFACE ID3DXBaseMesh DECLARE_INTERFACE_(ID3DXBaseMesh, IUnknown) { // IUnknown STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef)(THIS) PURE; STDMETHOD_(ULONG, Release)(THIS) PURE; // ID3DXBaseMesh STDMETHOD(DrawSubset)(THIS_ DWORD AttribId) PURE; STDMETHOD_(DWORD, GetNumFaces)(THIS) PURE; STDMETHOD_(DWORD, GetNumVertices)(THIS) PURE; STDMETHOD_(DWORD, GetFVF)(THIS) PURE; STDMETHOD(GetDeclaration)(THIS_ D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]) PURE; STDMETHOD_(DWORD, GetNumBytesPerVertex)(THIS) PURE; STDMETHOD_(DWORD, GetOptions)(THIS) PURE; STDMETHOD(GetDevice)(THIS_ LPDIRECT3DDEVICE9* ppDevice) PURE; STDMETHOD(CloneMeshFVF)(THIS_ DWORD Options, DWORD FVF, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXMESH* ppCloneMesh) PURE; STDMETHOD(CloneMesh)(THIS_ DWORD Options, CONST D3DVERTEXELEMENT9 *pDeclaration, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXMESH* ppCloneMesh) PURE; STDMETHOD(GetVertexBuffer)(THIS_ LPDIRECT3DVERTEXBUFFER9* ppVB) PURE; STDMETHOD(GetIndexBuffer)(THIS_ LPDIRECT3DINDEXBUFFER9* ppIB) PURE; STDMETHOD(LockVertexBuffer)(THIS_ DWORD Flags, LPVOID *ppData) PURE; STDMETHOD(UnlockVertexBuffer)(THIS) PURE; STDMETHOD(LockIndexBuffer)(THIS_ DWORD Flags, LPVOID *ppData) PURE; STDMETHOD(UnlockIndexBuffer)(THIS) PURE; STDMETHOD(GetAttributeTable)( THIS_ D3DXATTRIBUTERANGE *pAttribTable, DWORD* pAttribTableSize) PURE; STDMETHOD(ConvertPointRepsToAdjacency)(THIS_ CONST DWORD* pPRep, DWORD* pAdjacency) PURE; STDMETHOD(ConvertAdjacencyToPointReps)(THIS_ CONST DWORD* pAdjacency, DWORD* pPRep) PURE; STDMETHOD(GenerateAdjacency)(THIS_ FLOAT Epsilon, DWORD* pAdjacency) PURE; STDMETHOD(UpdateSemantics)(THIS_ D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]) PURE; }; #undef INTERFACE #define INTERFACE ID3DXMesh DECLARE_INTERFACE_(ID3DXMesh, ID3DXBaseMesh) { // IUnknown STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef)(THIS) PURE; STDMETHOD_(ULONG, Release)(THIS) PURE; // ID3DXBaseMesh STDMETHOD(DrawSubset)(THIS_ DWORD AttribId) PURE; STDMETHOD_(DWORD, GetNumFaces)(THIS) PURE; STDMETHOD_(DWORD, GetNumVertices)(THIS) PURE; STDMETHOD_(DWORD, GetFVF)(THIS) PURE; STDMETHOD(GetDeclaration)(THIS_ D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]) PURE; STDMETHOD_(DWORD, GetNumBytesPerVertex)(THIS) PURE; STDMETHOD_(DWORD, GetOptions)(THIS) PURE; STDMETHOD(GetDevice)(THIS_ LPDIRECT3DDEVICE9* ppDevice) PURE; STDMETHOD(CloneMeshFVF)(THIS_ DWORD Options, DWORD FVF, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXMESH* ppCloneMesh) PURE; STDMETHOD(CloneMesh)(THIS_ DWORD Options, CONST D3DVERTEXELEMENT9 *pDeclaration, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXMESH* ppCloneMesh) PURE; STDMETHOD(GetVertexBuffer)(THIS_ LPDIRECT3DVERTEXBUFFER9* ppVB) PURE; STDMETHOD(GetIndexBuffer)(THIS_ LPDIRECT3DINDEXBUFFER9* ppIB) PURE; STDMETHOD(LockVertexBuffer)(THIS_ DWORD Flags, LPVOID *ppData) PURE; STDMETHOD(UnlockVertexBuffer)(THIS) PURE; STDMETHOD(LockIndexBuffer)(THIS_ DWORD Flags, LPVOID *ppData) PURE; STDMETHOD(UnlockIndexBuffer)(THIS) PURE; STDMETHOD(GetAttributeTable)( THIS_ D3DXATTRIBUTERANGE *pAttribTable, DWORD* pAttribTableSize) PURE; STDMETHOD(ConvertPointRepsToAdjacency)(THIS_ CONST DWORD* pPRep, DWORD* pAdjacency) PURE; STDMETHOD(ConvertAdjacencyToPointReps)(THIS_ CONST DWORD* pAdjacency, DWORD* pPRep) PURE; STDMETHOD(GenerateAdjacency)(THIS_ FLOAT Epsilon, DWORD* pAdjacency) PURE; STDMETHOD(UpdateSemantics)(THIS_ D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]) PURE; // ID3DXMesh STDMETHOD(LockAttributeBuffer)(THIS_ DWORD Flags, DWORD** ppData) PURE; STDMETHOD(UnlockAttributeBuffer)(THIS) PURE; STDMETHOD(Optimize)(THIS_ DWORD Flags, CONST DWORD* pAdjacencyIn, DWORD* pAdjacencyOut, DWORD* pFaceRemap, LPD3DXBUFFER *ppVertexRemap, LPD3DXMESH* ppOptMesh) PURE; STDMETHOD(OptimizeInplace)(THIS_ DWORD Flags, CONST DWORD* pAdjacencyIn, DWORD* pAdjacencyOut, DWORD* pFaceRemap, LPD3DXBUFFER *ppVertexRemap) PURE; STDMETHOD(SetAttributeTable)(THIS_ CONST D3DXATTRIBUTERANGE *pAttribTable, DWORD cAttribTableSize) PURE; }; #undef INTERFACE #define INTERFACE ID3DXPMesh DECLARE_INTERFACE_(ID3DXPMesh, ID3DXBaseMesh) { // IUnknown STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef)(THIS) PURE; STDMETHOD_(ULONG, Release)(THIS) PURE; // ID3DXBaseMesh STDMETHOD(DrawSubset)(THIS_ DWORD AttribId) PURE; STDMETHOD_(DWORD, GetNumFaces)(THIS) PURE; STDMETHOD_(DWORD, GetNumVertices)(THIS) PURE; STDMETHOD_(DWORD, GetFVF)(THIS) PURE; STDMETHOD(GetDeclaration)(THIS_ D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]) PURE; STDMETHOD_(DWORD, GetNumBytesPerVertex)(THIS) PURE; STDMETHOD_(DWORD, GetOptions)(THIS) PURE; STDMETHOD(GetDevice)(THIS_ LPDIRECT3DDEVICE9* ppDevice) PURE; STDMETHOD(CloneMeshFVF)(THIS_ DWORD Options, DWORD FVF, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXMESH* ppCloneMesh) PURE; STDMETHOD(CloneMesh)(THIS_ DWORD Options, CONST D3DVERTEXELEMENT9 *pDeclaration, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXMESH* ppCloneMesh) PURE; STDMETHOD(GetVertexBuffer)(THIS_ LPDIRECT3DVERTEXBUFFER9* ppVB) PURE; STDMETHOD(GetIndexBuffer)(THIS_ LPDIRECT3DINDEXBUFFER9* ppIB) PURE; STDMETHOD(LockVertexBuffer)(THIS_ DWORD Flags, LPVOID *ppData) PURE; STDMETHOD(UnlockVertexBuffer)(THIS) PURE; STDMETHOD(LockIndexBuffer)(THIS_ DWORD Flags, LPVOID *ppData) PURE; STDMETHOD(UnlockIndexBuffer)(THIS) PURE; STDMETHOD(GetAttributeTable)( THIS_ D3DXATTRIBUTERANGE *pAttribTable, DWORD* pAttribTableSize) PURE; STDMETHOD(ConvertPointRepsToAdjacency)(THIS_ CONST DWORD* pPRep, DWORD* pAdjacency) PURE; STDMETHOD(ConvertAdjacencyToPointReps)(THIS_ CONST DWORD* pAdjacency, DWORD* pPRep) PURE; STDMETHOD(GenerateAdjacency)(THIS_ FLOAT Epsilon, DWORD* pAdjacency) PURE; STDMETHOD(UpdateSemantics)(THIS_ D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]) PURE; // ID3DXPMesh STDMETHOD(ClonePMeshFVF)(THIS_ DWORD Options, DWORD FVF, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXPMESH* ppCloneMesh) PURE; STDMETHOD(ClonePMesh)(THIS_ DWORD Options, CONST D3DVERTEXELEMENT9 *pDeclaration, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXPMESH* ppCloneMesh) PURE; STDMETHOD(SetNumFaces)(THIS_ DWORD Faces) PURE; STDMETHOD(SetNumVertices)(THIS_ DWORD Vertices) PURE; STDMETHOD_(DWORD, GetMaxFaces)(THIS) PURE; STDMETHOD_(DWORD, GetMinFaces)(THIS) PURE; STDMETHOD_(DWORD, GetMaxVertices)(THIS) PURE; STDMETHOD_(DWORD, GetMinVertices)(THIS) PURE; STDMETHOD(Save)(THIS_ IStream *pStream, CONST D3DXMATERIAL* pMaterials, CONST D3DXEFFECTINSTANCE* pEffectInstances, DWORD NumMaterials) PURE; STDMETHOD(Optimize)(THIS_ DWORD Flags, DWORD* pAdjacencyOut, DWORD* pFaceRemap, LPD3DXBUFFER *ppVertexRemap, LPD3DXMESH* ppOptMesh) PURE; STDMETHOD(OptimizeBaseLOD)(THIS_ DWORD Flags, DWORD* pFaceRemap) PURE; STDMETHOD(TrimByFaces)(THIS_ DWORD NewFacesMin, DWORD NewFacesMax, DWORD *rgiFaceRemap, DWORD *rgiVertRemap) PURE; STDMETHOD(TrimByVertices)(THIS_ DWORD NewVerticesMin, DWORD NewVerticesMax, DWORD *rgiFaceRemap, DWORD *rgiVertRemap) PURE; STDMETHOD(GetAdjacency)(THIS_ DWORD* pAdjacency) PURE; // Used to generate the immediate "ancestor" for each vertex when it is removed by a vsplit. Allows generation of geomorphs // Vertex buffer must be equal to or greater than the maximum number of vertices in the pmesh STDMETHOD(GenerateVertexHistory)(THIS_ DWORD* pVertexHistory) PURE; }; #undef INTERFACE #define INTERFACE ID3DXSPMesh DECLARE_INTERFACE_(ID3DXSPMesh, IUnknown) { // IUnknown STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef)(THIS) PURE; STDMETHOD_(ULONG, Release)(THIS) PURE; // ID3DXSPMesh STDMETHOD_(DWORD, GetNumFaces)(THIS) PURE; STDMETHOD_(DWORD, GetNumVertices)(THIS) PURE; STDMETHOD_(DWORD, GetFVF)(THIS) PURE; STDMETHOD(GetDeclaration)(THIS_ D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]) PURE; STDMETHOD_(DWORD, GetOptions)(THIS) PURE; STDMETHOD(GetDevice)(THIS_ LPDIRECT3DDEVICE9* ppDevice) PURE; STDMETHOD(CloneMeshFVF)(THIS_ DWORD Options, DWORD FVF, LPDIRECT3DDEVICE9 pD3DDevice, DWORD *pAdjacencyOut, DWORD *pVertexRemapOut, LPD3DXMESH* ppCloneMesh) PURE; STDMETHOD(CloneMesh)(THIS_ DWORD Options, CONST D3DVERTEXELEMENT9 *pDeclaration, LPDIRECT3DDEVICE9 pD3DDevice, DWORD *pAdjacencyOut, DWORD *pVertexRemapOut, LPD3DXMESH* ppCloneMesh) PURE; STDMETHOD(ClonePMeshFVF)(THIS_ DWORD Options, DWORD FVF, LPDIRECT3DDEVICE9 pD3DDevice, DWORD *pVertexRemapOut, FLOAT *pErrorsByFace, LPD3DXPMESH* ppCloneMesh) PURE; STDMETHOD(ClonePMesh)(THIS_ DWORD Options, CONST D3DVERTEXELEMENT9 *pDeclaration, LPDIRECT3DDEVICE9 pD3DDevice, DWORD *pVertexRemapOut, FLOAT *pErrorsbyFace, LPD3DXPMESH* ppCloneMesh) PURE; STDMETHOD(ReduceFaces)(THIS_ DWORD Faces) PURE; STDMETHOD(ReduceVertices)(THIS_ DWORD Vertices) PURE; STDMETHOD_(DWORD, GetMaxFaces)(THIS) PURE; STDMETHOD_(DWORD, GetMaxVertices)(THIS) PURE; STDMETHOD(GetVertexAttributeWeights)(THIS_ LPD3DXATTRIBUTEWEIGHTS pVertexAttributeWeights) PURE; STDMETHOD(GetVertexWeights)(THIS_ FLOAT *pVertexWeights) PURE; }; #define UNUSED16 (0xffff) #define UNUSED32 (0xffffffff) // ID3DXMesh::Optimize options - upper byte only, lower 3 bytes used from _D3DXMESH option flags enum _D3DXMESHOPT { D3DXMESHOPT_COMPACT = 0x01000000, D3DXMESHOPT_ATTRSORT = 0x02000000, D3DXMESHOPT_VERTEXCACHE = 0x04000000, D3DXMESHOPT_STRIPREORDER = 0x08000000, D3DXMESHOPT_IGNOREVERTS = 0x10000000, // optimize faces only, don't touch vertices D3DXMESHOPT_DONOTSPLIT = 0x20000000, // do not split vertices shared between attribute groups when attribute sorting D3DXMESHOPT_DEVICEINDEPENDENT = 0x00400000, // Only affects VCache. uses a static known good cache size for all cards // D3DXMESHOPT_SHAREVB has been removed, please use D3DXMESH_VB_SHARE instead }; // Subset of the mesh that has the same attribute and bone combination. // This subset can be rendered in a single draw call typedef struct _D3DXBONECOMBINATION { DWORD AttribId; DWORD FaceStart; DWORD FaceCount; DWORD VertexStart; DWORD VertexCount; DWORD* BoneId; } D3DXBONECOMBINATION, *LPD3DXBONECOMBINATION; // The following types of patch combinations are supported: // Patch type Basis Degree // Rect Bezier 2,3,5 // Rect B-Spline 2,3,5 // Rect Catmull-Rom 3 // Tri Bezier 2,3,5 // N-Patch N/A 3 typedef struct _D3DXPATCHINFO { D3DXPATCHMESHTYPE PatchType; D3DDEGREETYPE Degree; D3DBASISTYPE Basis; } D3DXPATCHINFO, *LPD3DXPATCHINFO; #undef INTERFACE #define INTERFACE ID3DXPatchMesh DECLARE_INTERFACE_(ID3DXPatchMesh, IUnknown) { // IUnknown STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef)(THIS) PURE; STDMETHOD_(ULONG, Release)(THIS) PURE; // ID3DXPatchMesh // Return creation parameters STDMETHOD_(DWORD, GetNumPatches)(THIS) PURE; STDMETHOD_(DWORD, GetNumVertices)(THIS) PURE; STDMETHOD(GetDeclaration)(THIS_ D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]) PURE; STDMETHOD_(DWORD, GetControlVerticesPerPatch)(THIS) PURE; STDMETHOD_(DWORD, GetOptions)(THIS) PURE; STDMETHOD(GetDevice)(THIS_ LPDIRECT3DDEVICE9 *ppDevice) PURE; STDMETHOD(GetPatchInfo)(THIS_ LPD3DXPATCHINFO PatchInfo) PURE; // Control mesh access STDMETHOD(GetVertexBuffer)(THIS_ LPDIRECT3DVERTEXBUFFER9* ppVB) PURE; STDMETHOD(GetIndexBuffer)(THIS_ LPDIRECT3DINDEXBUFFER9* ppIB) PURE; STDMETHOD(LockVertexBuffer)(THIS_ DWORD flags, LPVOID *ppData) PURE; STDMETHOD(UnlockVertexBuffer)(THIS) PURE; STDMETHOD(LockIndexBuffer)(THIS_ DWORD flags, LPVOID *ppData) PURE; STDMETHOD(UnlockIndexBuffer)(THIS) PURE; STDMETHOD(LockAttributeBuffer)(THIS_ DWORD flags, DWORD** ppData) PURE; STDMETHOD(UnlockAttributeBuffer)(THIS) PURE; // This function returns the size of the tessellated mesh given a tessellation level. // This assumes uniform tessellation. For adaptive tessellation the Adaptive parameter must // be set to TRUE and TessellationLevel should be the max tessellation. // This will result in the max mesh size necessary for adaptive tessellation. STDMETHOD(GetTessSize)(THIS_ FLOAT fTessLevel,DWORD Adaptive, DWORD *NumTriangles,DWORD *NumVertices) PURE; //GenerateAdjacency determines which patches are adjacent with provided tolerance //this information is used internally to optimize tessellation STDMETHOD(GenerateAdjacency)(THIS_ FLOAT Tolerance) PURE; //CloneMesh Creates a new patchmesh with the specified decl, and converts the vertex buffer //to the new decl. Entries in the new decl which are new are set to 0. If the current mesh //has adjacency, the new mesh will also have adjacency STDMETHOD(CloneMesh)(THIS_ DWORD Options, CONST D3DVERTEXELEMENT9 *pDecl, LPD3DXPATCHMESH *pMesh) PURE; // Optimizes the patchmesh for efficient tessellation. This function is designed // to perform one time optimization for patch meshes that need to be tessellated // repeatedly by calling the Tessellate() method. The optimization performed is // independent of the actual tessellation level used. // Currently Flags is unused. // If vertices are changed, Optimize must be called again STDMETHOD(Optimize)(THIS_ DWORD flags) PURE; //gets and sets displacement parameters //displacement maps can only be 2D textures MIP-MAPPING is ignored for non adapative tessellation STDMETHOD(SetDisplaceParam)(THIS_ LPDIRECT3DBASETEXTURE9 Texture, D3DTEXTUREFILTERTYPE MinFilter, D3DTEXTUREFILTERTYPE MagFilter, D3DTEXTUREFILTERTYPE MipFilter, D3DTEXTUREADDRESS Wrap, DWORD dwLODBias) PURE; STDMETHOD(GetDisplaceParam)(THIS_ LPDIRECT3DBASETEXTURE9 *Texture, D3DTEXTUREFILTERTYPE *MinFilter, D3DTEXTUREFILTERTYPE *MagFilter, D3DTEXTUREFILTERTYPE *MipFilter, D3DTEXTUREADDRESS *Wrap, DWORD *dwLODBias) PURE; // Performs the uniform tessellation based on the tessellation level. // This function will perform more efficiently if the patch mesh has been optimized using the Optimize() call. STDMETHOD(Tessellate)(THIS_ FLOAT fTessLevel,LPD3DXMESH pMesh) PURE; // Performs adaptive tessellation based on the Z based adaptive tessellation criterion. // pTrans specifies a 4D vector that is dotted with the vertices to get the per vertex // adaptive tessellation amount. Each edge is tessellated to the average of the criterion // at the 2 vertices it connects. // MaxTessLevel specifies the upper limit for adaptive tesselation. // This function will perform more efficiently if the patch mesh has been optimized using the Optimize() call. STDMETHOD(TessellateAdaptive)(THIS_ CONST D3DXVECTOR4 *pTrans, DWORD dwMaxTessLevel, DWORD dwMinTessLevel, LPD3DXMESH pMesh) PURE; }; #undef INTERFACE #define INTERFACE ID3DXSkinInfo DECLARE_INTERFACE_(ID3DXSkinInfo, IUnknown) { // IUnknown STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef)(THIS) PURE; STDMETHOD_(ULONG, Release)(THIS) PURE; // Specify the which vertices do each bones influence and by how much STDMETHOD(SetBoneInfluence)(THIS_ DWORD bone, DWORD numInfluences, CONST DWORD* vertices, CONST FLOAT* weights) PURE; STDMETHOD(SetBoneVertexInfluence)(THIS_ DWORD boneNum, DWORD influenceNum, float weight) PURE; STDMETHOD_(DWORD, GetNumBoneInfluences)(THIS_ DWORD bone) PURE; STDMETHOD(GetBoneInfluence)(THIS_ DWORD bone, DWORD* vertices, FLOAT* weights) PURE; STDMETHOD(GetBoneVertexInfluence)(THIS_ DWORD boneNum, DWORD influenceNum, float *pWeight, DWORD *pVertexNum) PURE; STDMETHOD(GetMaxVertexInfluences)(THIS_ DWORD* maxVertexInfluences) PURE; STDMETHOD_(DWORD, GetNumBones)(THIS) PURE; STDMETHOD(FindBoneVertexInfluenceIndex)(THIS_ DWORD boneNum, DWORD vertexNum, DWORD *pInfluenceIndex) PURE; // This gets the max face influences based on a triangle mesh with the specified index buffer STDMETHOD(GetMaxFaceInfluences)(THIS_ LPDIRECT3DINDEXBUFFER9 pIB, DWORD NumFaces, DWORD* maxFaceInfluences) PURE; // Set min bone influence. Bone influences that are smaller than this are ignored STDMETHOD(SetMinBoneInfluence)(THIS_ FLOAT MinInfl) PURE; // Get min bone influence. STDMETHOD_(FLOAT, GetMinBoneInfluence)(THIS) PURE; // Bone names are returned by D3DXLoadSkinMeshFromXof. They are not used by any other method of this object STDMETHOD(SetBoneName)(THIS_ DWORD Bone, LPCSTR pName) PURE; // pName is copied to an internal string buffer STDMETHOD_(LPCSTR, GetBoneName)(THIS_ DWORD Bone) PURE; // A pointer to an internal string buffer is returned. Do not free this. // Bone offset matrices are returned by D3DXLoadSkinMeshFromXof. They are not used by any other method of this object STDMETHOD(SetBoneOffsetMatrix)(THIS_ DWORD Bone, CONST D3DXMATRIX *pBoneTransform) PURE; // pBoneTransform is copied to an internal buffer STDMETHOD_(LPD3DXMATRIX, GetBoneOffsetMatrix)(THIS_ DWORD Bone) PURE; // A pointer to an internal matrix is returned. Do not free this. // Clone a skin info object STDMETHOD(Clone)(THIS_ LPD3DXSKININFO* ppSkinInfo) PURE; // Update bone influence information to match vertices after they are reordered. This should be called // if the target vertex buffer has been reordered externally. STDMETHOD(Remap)(THIS_ DWORD NumVertices, DWORD* pVertexRemap) PURE; // These methods enable the modification of the vertex layout of the vertices that will be skinned STDMETHOD(SetFVF)(THIS_ DWORD FVF) PURE; STDMETHOD(SetDeclaration)(THIS_ CONST D3DVERTEXELEMENT9 *pDeclaration) PURE; STDMETHOD_(DWORD, GetFVF)(THIS) PURE; STDMETHOD(GetDeclaration)(THIS_ D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]) PURE; // Apply SW skinning based on current pose matrices to the target vertices. STDMETHOD(UpdateSkinnedMesh)(THIS_ CONST D3DXMATRIX* pBoneTransforms, CONST D3DXMATRIX* pBoneInvTransposeTransforms, LPCVOID pVerticesSrc, PVOID pVerticesDst) PURE; // Takes a mesh and returns a new mesh with per vertex blend weights and a bone combination // table that describes which bones affect which subsets of the mesh STDMETHOD(ConvertToBlendedMesh)(THIS_ LPD3DXMESH pMesh, DWORD Options, CONST DWORD *pAdjacencyIn, LPDWORD pAdjacencyOut, DWORD* pFaceRemap, LPD3DXBUFFER *ppVertexRemap, DWORD* pMaxFaceInfl, DWORD* pNumBoneCombinations, LPD3DXBUFFER* ppBoneCombinationTable, LPD3DXMESH* ppMesh) PURE; // Takes a mesh and returns a new mesh with per vertex blend weights and indices // and a bone combination table that describes which bones palettes affect which subsets of the mesh STDMETHOD(ConvertToIndexedBlendedMesh)(THIS_ LPD3DXMESH pMesh, DWORD Options, DWORD paletteSize, CONST DWORD *pAdjacencyIn, LPDWORD pAdjacencyOut, DWORD* pFaceRemap, LPD3DXBUFFER *ppVertexRemap, DWORD* pMaxVertexInfl, DWORD* pNumBoneCombinations, LPD3DXBUFFER* ppBoneCombinationTable, LPD3DXMESH* ppMesh) PURE; }; #ifdef __cplusplus extern "C" { #endif //__cplusplus HRESULT WINAPI D3DXCreateMesh( DWORD NumFaces, DWORD NumVertices, DWORD Options, CONST D3DVERTEXELEMENT9 *pDeclaration, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXMESH* ppMesh); HRESULT WINAPI D3DXCreateMeshFVF( DWORD NumFaces, DWORD NumVertices, DWORD Options, DWORD FVF, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXMESH* ppMesh); HRESULT WINAPI D3DXCreateSPMesh( LPD3DXMESH pMesh, CONST DWORD* pAdjacency, CONST D3DXATTRIBUTEWEIGHTS *pVertexAttributeWeights, CONST FLOAT *pVertexWeights, LPD3DXSPMESH* ppSMesh); // clean a mesh up for simplification, try to make manifold HRESULT WINAPI D3DXCleanMesh( D3DXCLEANTYPE CleanType, LPD3DXMESH pMeshIn, CONST DWORD* pAdjacencyIn, LPD3DXMESH* ppMeshOut, DWORD* pAdjacencyOut, LPD3DXBUFFER* ppErrorsAndWarnings); HRESULT WINAPI D3DXValidMesh( LPD3DXMESH pMeshIn, CONST DWORD* pAdjacency, LPD3DXBUFFER* ppErrorsAndWarnings); HRESULT WINAPI D3DXGeneratePMesh( LPD3DXMESH pMesh, CONST DWORD* pAdjacency, CONST D3DXATTRIBUTEWEIGHTS *pVertexAttributeWeights, CONST FLOAT *pVertexWeights, DWORD MinValue, DWORD Options, LPD3DXPMESH* ppPMesh); HRESULT WINAPI D3DXSimplifyMesh( LPD3DXMESH pMesh, CONST DWORD* pAdjacency, CONST D3DXATTRIBUTEWEIGHTS *pVertexAttributeWeights, CONST FLOAT *pVertexWeights, DWORD MinValue, DWORD Options, LPD3DXMESH* ppMesh); HRESULT WINAPI D3DXComputeBoundingSphere( CONST D3DXVECTOR3 *pFirstPosition, // pointer to first position DWORD NumVertices, DWORD dwStride, // count in bytes to subsequent position vectors D3DXVECTOR3 *pCenter, FLOAT *pRadius); HRESULT WINAPI D3DXComputeBoundingBox( CONST D3DXVECTOR3 *pFirstPosition, // pointer to first position DWORD NumVertices, DWORD dwStride, // count in bytes to subsequent position vectors D3DXVECTOR3 *pMin, D3DXVECTOR3 *pMax); HRESULT WINAPI D3DXComputeNormals( LPD3DXBASEMESH pMesh, CONST DWORD *pAdjacency); HRESULT WINAPI D3DXCreateBuffer( DWORD NumBytes, LPD3DXBUFFER *ppBuffer); HRESULT WINAPI D3DXLoadMeshFromXA( LPCSTR pFilename, DWORD Options, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXBUFFER *ppAdjacency, LPD3DXBUFFER *ppMaterials, LPD3DXBUFFER *ppEffectInstances, DWORD *pNumMaterials, LPD3DXMESH *ppMesh); HRESULT WINAPI D3DXLoadMeshFromXW( LPCWSTR pFilename, DWORD Options, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXBUFFER *ppAdjacency, LPD3DXBUFFER *ppMaterials, LPD3DXBUFFER *ppEffectInstances, DWORD *pNumMaterials, LPD3DXMESH *ppMesh); #ifdef UNICODE #define D3DXLoadMeshFromX D3DXLoadMeshFromXW #else #define D3DXLoadMeshFromX D3DXLoadMeshFromXA #endif HRESULT WINAPI D3DXLoadMeshFromXInMemory( LPCVOID Memory, DWORD SizeOfMemory, DWORD Options, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXBUFFER *ppAdjacency, LPD3DXBUFFER *ppMaterials, LPD3DXBUFFER *ppEffectInstances, DWORD *pNumMaterials, LPD3DXMESH *ppMesh); HRESULT WINAPI D3DXLoadMeshFromXResource( HMODULE Module, LPCSTR Name, LPCSTR Type, DWORD Options, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXBUFFER *ppAdjacency, LPD3DXBUFFER *ppMaterials, LPD3DXBUFFER *ppEffectInstances, DWORD *pNumMaterials, LPD3DXMESH *ppMesh); HRESULT WINAPI D3DXSaveMeshToXA( LPCSTR pFilename, LPD3DXMESH pMesh, CONST DWORD* pAdjacency, CONST D3DXMATERIAL* pMaterials, CONST D3DXEFFECTINSTANCE* pEffectInstances, DWORD NumMaterials, DWORD Format ); HRESULT WINAPI D3DXSaveMeshToXW( LPCWSTR pFilename, LPD3DXMESH pMesh, CONST DWORD* pAdjacency, CONST D3DXMATERIAL* pMaterials, CONST D3DXEFFECTINSTANCE* pEffectInstances, DWORD NumMaterials, DWORD Format ); #ifdef UNICODE #define D3DXSaveMeshToX D3DXSaveMeshToXW #else #define D3DXSaveMeshToX D3DXSaveMeshToXA #endif HRESULT WINAPI D3DXCreatePMeshFromStream( IStream *pStream, DWORD Options, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXBUFFER *ppMaterials, LPD3DXBUFFER *ppEffectInstances, DWORD* pNumMaterials, LPD3DXPMESH *ppPMesh); // Creates a skin info object based on the number of vertices, number of bones, and a declaration describing the vertex layout of the target vertices // The bone names and initial bone transforms are not filled in the skin info object by this method. HRESULT WINAPI D3DXCreateSkinInfo( DWORD NumVertices, CONST D3DVERTEXELEMENT9 *pDeclaration, DWORD NumBones, LPD3DXSKININFO* ppSkinInfo); // Creates a skin info object based on the number of vertices, number of bones, and a FVF describing the vertex layout of the target vertices // The bone names and initial bone transforms are not filled in the skin info object by this method. HRESULT WINAPI D3DXCreateSkinInfoFVF( DWORD NumVertices, DWORD FVF, DWORD NumBones, LPD3DXSKININFO* ppSkinInfo); #ifdef __cplusplus } extern "C" { #endif //__cplusplus HRESULT WINAPI D3DXLoadMeshFromXof( LPD3DXFILEDATA pxofMesh, DWORD Options, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXBUFFER *ppAdjacency, LPD3DXBUFFER *ppMaterials, LPD3DXBUFFER *ppEffectInstances, DWORD *pNumMaterials, LPD3DXMESH *ppMesh); // This similar to D3DXLoadMeshFromXof, except also returns skinning info if present in the file // If skinning info is not present, ppSkinInfo will be NULL HRESULT WINAPI D3DXLoadSkinMeshFromXof( LPD3DXFILEDATA pxofMesh, DWORD Options, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXBUFFER* ppAdjacency, LPD3DXBUFFER* ppMaterials, LPD3DXBUFFER *ppEffectInstances, DWORD *pMatOut, LPD3DXSKININFO* ppSkinInfo, LPD3DXMESH* ppMesh); // The inverse of D3DXConvertTo{Indexed}BlendedMesh() functions. It figures out the skinning info from // the mesh and the bone combination table and populates a skin info object with that data. The bone // names and initial bone transforms are not filled in the skin info object by this method. This works // with either a non-indexed or indexed blended mesh. It examines the FVF or declarator of the mesh to // determine what type it is. HRESULT WINAPI D3DXCreateSkinInfoFromBlendedMesh( LPD3DXBASEMESH pMesh, DWORD NumBones, CONST D3DXBONECOMBINATION *pBoneCombinationTable, LPD3DXSKININFO* ppSkinInfo); HRESULT WINAPI D3DXTessellateNPatches( LPD3DXMESH pMeshIn, CONST DWORD* pAdjacencyIn, FLOAT NumSegs, BOOL QuadraticInterpNormals, // if false use linear intrep for normals, if true use quadratic LPD3DXMESH *ppMeshOut, LPD3DXBUFFER *ppAdjacencyOut); //generates implied outputdecl from input decl //the decl generated from this should be used to generate the output decl for //the tessellator subroutines. HRESULT WINAPI D3DXGenerateOutputDecl( D3DVERTEXELEMENT9 *pOutput, CONST D3DVERTEXELEMENT9 *pInput); //loads patches from an XFileData //since an X file can have up to 6 different patch meshes in it, //returns them in an array - pNumPatches will contain the number of //meshes in the actual file. HRESULT WINAPI D3DXLoadPatchMeshFromXof( LPD3DXFILEDATA pXofObjMesh, DWORD Options, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXBUFFER *ppMaterials, LPD3DXBUFFER *ppEffectInstances, PDWORD pNumMaterials, LPD3DXPATCHMESH *ppMesh); //computes the size a single rect patch. HRESULT WINAPI D3DXRectPatchSize( CONST FLOAT *pfNumSegs, //segments for each edge (4) DWORD *pdwTriangles, //output number of triangles DWORD *pdwVertices); //output number of vertices //computes the size of a single triangle patch HRESULT WINAPI D3DXTriPatchSize( CONST FLOAT *pfNumSegs, //segments for each edge (3) DWORD *pdwTriangles, //output number of triangles DWORD *pdwVertices); //output number of vertices //tessellates a patch into a created mesh //similar to D3D RT patch HRESULT WINAPI D3DXTessellateRectPatch( LPDIRECT3DVERTEXBUFFER9 pVB, CONST FLOAT *pNumSegs, CONST D3DVERTEXELEMENT9 *pdwInDecl, CONST D3DRECTPATCH_INFO *pRectPatchInfo, LPD3DXMESH pMesh); HRESULT WINAPI D3DXTessellateTriPatch( LPDIRECT3DVERTEXBUFFER9 pVB, CONST FLOAT *pNumSegs, CONST D3DVERTEXELEMENT9 *pInDecl, CONST D3DTRIPATCH_INFO *pTriPatchInfo, LPD3DXMESH pMesh); //creates an NPatch PatchMesh from a D3DXMESH HRESULT WINAPI D3DXCreateNPatchMesh( LPD3DXMESH pMeshSysMem, LPD3DXPATCHMESH *pPatchMesh); //creates a patch mesh HRESULT WINAPI D3DXCreatePatchMesh( CONST D3DXPATCHINFO *pInfo, //patch type DWORD dwNumPatches, //number of patches DWORD dwNumVertices, //number of control vertices DWORD dwOptions, //options CONST D3DVERTEXELEMENT9 *pDecl, //format of control vertices LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXPATCHMESH *pPatchMesh); //returns the number of degenerates in a patch mesh - //text output put in string. HRESULT WINAPI D3DXValidPatchMesh(LPD3DXPATCHMESH pMesh, DWORD *dwcDegenerateVertices, DWORD *dwcDegeneratePatches, LPD3DXBUFFER *ppErrorsAndWarnings); UINT WINAPI D3DXGetFVFVertexSize(DWORD FVF); UINT WINAPI D3DXGetDeclVertexSize(CONST D3DVERTEXELEMENT9 *pDecl,DWORD Stream); UINT WINAPI D3DXGetDeclLength(CONST D3DVERTEXELEMENT9 *pDecl); HRESULT WINAPI D3DXDeclaratorFromFVF( DWORD FVF, D3DVERTEXELEMENT9 pDeclarator[MAX_FVF_DECL_SIZE]); HRESULT WINAPI D3DXFVFFromDeclarator( CONST D3DVERTEXELEMENT9 *pDeclarator, DWORD *pFVF); HRESULT WINAPI D3DXWeldVertices( LPD3DXMESH pMesh, DWORD Flags, CONST D3DXWELDEPSILONS *pEpsilons, CONST DWORD *pAdjacencyIn, DWORD *pAdjacencyOut, DWORD *pFaceRemap, LPD3DXBUFFER *ppVertexRemap); typedef struct _D3DXINTERSECTINFO { DWORD FaceIndex; // index of face intersected FLOAT U; // Barycentric Hit Coordinates FLOAT V; // Barycentric Hit Coordinates FLOAT Dist; // Ray-Intersection Parameter Distance } D3DXINTERSECTINFO, *LPD3DXINTERSECTINFO; HRESULT WINAPI D3DXIntersect( LPD3DXBASEMESH pMesh, CONST D3DXVECTOR3 *pRayPos, CONST D3DXVECTOR3 *pRayDir, BOOL *pHit, // True if any faces were intersected DWORD *pFaceIndex, // index of closest face intersected FLOAT *pU, // Barycentric Hit Coordinates FLOAT *pV, // Barycentric Hit Coordinates FLOAT *pDist, // Ray-Intersection Parameter Distance LPD3DXBUFFER *ppAllHits, // Array of D3DXINTERSECTINFOs for all hits (not just closest) DWORD *pCountOfHits); // Number of entries in AllHits array HRESULT WINAPI D3DXIntersectSubset( LPD3DXBASEMESH pMesh, DWORD AttribId, CONST D3DXVECTOR3 *pRayPos, CONST D3DXVECTOR3 *pRayDir, BOOL *pHit, // True if any faces were intersected DWORD *pFaceIndex, // index of closest face intersected FLOAT *pU, // Barycentric Hit Coordinates FLOAT *pV, // Barycentric Hit Coordinates FLOAT *pDist, // Ray-Intersection Parameter Distance LPD3DXBUFFER *ppAllHits, // Array of D3DXINTERSECTINFOs for all hits (not just closest) DWORD *pCountOfHits); // Number of entries in AllHits array HRESULT WINAPI D3DXSplitMesh ( LPD3DXMESH pMeshIn, CONST DWORD *pAdjacencyIn, CONST DWORD MaxSize, CONST DWORD Options, DWORD *pMeshesOut, LPD3DXBUFFER *ppMeshArrayOut, LPD3DXBUFFER *ppAdjacencyArrayOut, LPD3DXBUFFER *ppFaceRemapArrayOut, LPD3DXBUFFER *ppVertRemapArrayOut ); BOOL WINAPI D3DXIntersectTri ( CONST D3DXVECTOR3 *p0, // Triangle vertex 0 position CONST D3DXVECTOR3 *p1, // Triangle vertex 1 position CONST D3DXVECTOR3 *p2, // Triangle vertex 2 position CONST D3DXVECTOR3 *pRayPos, // Ray origin CONST D3DXVECTOR3 *pRayDir, // Ray direction FLOAT *pU, // Barycentric Hit Coordinates FLOAT *pV, // Barycentric Hit Coordinates FLOAT *pDist); // Ray-Intersection Parameter Distance BOOL WINAPI D3DXSphereBoundProbe( CONST D3DXVECTOR3 *pCenter, FLOAT Radius, CONST D3DXVECTOR3 *pRayPosition, CONST D3DXVECTOR3 *pRayDirection); BOOL WINAPI D3DXBoxBoundProbe( CONST D3DXVECTOR3 *pMin, CONST D3DXVECTOR3 *pMax, CONST D3DXVECTOR3 *pRayPosition, CONST D3DXVECTOR3 *pRayDirection); //D3DXComputeTangent // //Computes the Tangent vectors for the TexStage texture coordinates //and places the results in the TANGENT[TangentIndex] specified in the meshes' DECL //puts the binorm in BINORM[BinormIndex] also specified in the decl. // //If neither the binorm or the tangnet are in the meshes declaration, //the function will fail. // //If a tangent or Binorm field is in the Decl, but the user does not //wish D3DXComputeTangent to replace them, then D3DX_DEFAULT specified //in the TangentIndex or BinormIndex will cause it to ignore the specified //semantic. // //Wrap should be specified if the texture coordinates wrap. HRESULT WINAPI D3DXComputeTangent(LPD3DXMESH Mesh, DWORD TexStage, DWORD TangentIndex, DWORD BinormIndex, DWORD Wrap, CONST DWORD *pAdjacency); HRESULT WINAPI D3DXConvertMeshSubsetToSingleStrip( LPD3DXBASEMESH MeshIn, DWORD AttribId, DWORD IBOptions, LPDIRECT3DINDEXBUFFER9 *ppIndexBuffer, DWORD *pNumIndices); HRESULT WINAPI D3DXConvertMeshSubsetToStrips( LPD3DXBASEMESH MeshIn, DWORD AttribId, DWORD IBOptions, LPDIRECT3DINDEXBUFFER9 *ppIndexBuffer, DWORD *pNumIndices, LPD3DXBUFFER *ppStripLengths, DWORD *pNumStrips); //============================================================================ // // D3DXOptimizeFaces: // -------------------- // Generate a face remapping for a triangle list that more effectively utilizes // vertex caches. This optimization is identical to the one provided // by ID3DXMesh::Optimize with the hardware independent option enabled. // // Parameters: // pbIndices // Triangle list indices to use for generating a vertex ordering // NumFaces // Number of faces in the triangle list // NumVertices // Number of vertices referenced by the triangle list // b32BitIndices // TRUE if indices are 32 bit, FALSE if indices are 16 bit // pFaceRemap // Destination buffer to store face ordering // The number stored for a given element is where in the new ordering // the face will have come from. See ID3DXMesh::Optimize for more info. // //============================================================================ HRESULT WINAPI D3DXOptimizeFaces( LPCVOID pbIndices, UINT cFaces, UINT cVertices, BOOL b32BitIndices, DWORD* pFaceRemap); //============================================================================ // // D3DXOptimizeVertices: // -------------------- // Generate a vertex remapping to optimize for in order use of vertices for // a given set of indices. This is commonly used after applying the face // remap generated by D3DXOptimizeFaces // // Parameters: // pbIndices // Triangle list indices to use for generating a vertex ordering // NumFaces // Number of faces in the triangle list // NumVertices // Number of vertices referenced by the triangle list // b32BitIndices // TRUE if indices are 32 bit, FALSE if indices are 16 bit // pVertexRemap // Destination buffer to store vertex ordering // The number stored for a given element is where in the new ordering // the vertex will have come from. See ID3DXMesh::Optimize for more info. // //============================================================================ HRESULT WINAPI D3DXOptimizeVertices( LPCVOID pbIndices, UINT cFaces, UINT cVertices, BOOL b32BitIndices, DWORD* pVertexRemap); #ifdef __cplusplus } #endif //__cplusplus //=========================================================================== // // Data structures for Spherical Harmonic Precomputation // // //============================================================================ typedef enum _D3DXSHCOMPRESSQUALITYTYPE { D3DXSHCQUAL_FASTLOWQUALITY = 1, D3DXSHCQUAL_SLOWHIGHQUALITY = 2, D3DXSHCQUAL_FORCE_DWORD = 0x7fffffff } D3DXSHCOMPRESSQUALITYTYPE; typedef enum _D3DXSHGPUSIMOPT { D3DXSHGPUSIMOPT_SHADOWRES256 = 1, D3DXSHGPUSIMOPT_SHADOWRES512 = 0, D3DXSHGPUSIMOPT_SHADOWRES1024 = 2, D3DXSHGPUSIMOPT_SHADOWRES2048 = 3, D3DXSHGPUSIMOPT_HIGHQUALITY = 4, D3DXSHGPUSIMOPT_FORCE_DWORD = 0x7fffffff } D3DXSHGPUSIMOPT; // for all properties that are colors the luminance is computed // if the simulator is run with a single channel using the following // formula: R * 0.2125 + G * 0.7154 + B * 0.0721 typedef struct _D3DXSHMATERIAL { D3DCOLORVALUE Diffuse; // Diffuse albedo of the surface. (Ignored if object is a Mirror) BOOL bMirror; // Must be set to FALSE. bMirror == TRUE not currently supported BOOL bSubSurf; // true if the object does subsurface scattering - can't do this and be a mirror // subsurface scattering parameters FLOAT RelativeIndexOfRefraction; D3DCOLORVALUE Absorption; D3DCOLORVALUE ReducedScattering; } D3DXSHMATERIAL; // allocated in D3DXSHPRTCompSplitMeshSC // vertices are duplicated into multiple super clusters but // only have a valid status in one super cluster (fill in the rest) typedef struct _D3DXSHPRTSPLITMESHVERTDATA { UINT uVertRemap; // vertex in original mesh this corresponds to UINT uSubCluster; // cluster index relative to super cluster UCHAR ucVertStatus; // 1 if vertex has valid data, 0 if it is "fill" } D3DXSHPRTSPLITMESHVERTDATA; // used in D3DXSHPRTCompSplitMeshSC // information for each super cluster that maps into face/vert arrays typedef struct _D3DXSHPRTSPLITMESHCLUSTERDATA { UINT uVertStart; // initial index into remapped vertex array UINT uVertLength; // number of vertices in this super cluster UINT uFaceStart; // initial index into face array UINT uFaceLength; // number of faces in this super cluster UINT uClusterStart; // initial index into cluster array UINT uClusterLength; // number of clusters in this super cluster } D3DXSHPRTSPLITMESHCLUSTERDATA; // call back function for simulator // return S_OK to keep running the simulator - anything else represents // failure and the simulator will abort. typedef HRESULT (WINAPI *LPD3DXSHPRTSIMCB)(float fPercentDone, LPVOID lpUserContext); // interfaces for PRT buffers/simulator // GUIDs // {F1827E47-00A8-49cd-908C-9D11955F8728} DEFINE_GUID(IID_ID3DXPRTBuffer, 0xf1827e47, 0xa8, 0x49cd, 0x90, 0x8c, 0x9d, 0x11, 0x95, 0x5f, 0x87, 0x28); // {A758D465-FE8D-45ad-9CF0-D01E56266A07} DEFINE_GUID(IID_ID3DXPRTCompBuffer, 0xa758d465, 0xfe8d, 0x45ad, 0x9c, 0xf0, 0xd0, 0x1e, 0x56, 0x26, 0x6a, 0x7); // {06F57E0A-BD95-43f1-A3DA-791CF6CA297B} DEFINE_GUID(IID_ID3DXTextureGutterHelper, 0x6f57e0a, 0xbd95, 0x43f1, 0xa3, 0xda, 0x79, 0x1c, 0xf6, 0xca, 0x29, 0x7b); // {C3F4ADBF-E6D2-4b7b-BFE8-9E7208746ADF} DEFINE_GUID(IID_ID3DXPRTEngine, 0xc3f4adbf, 0xe6d2, 0x4b7b, 0xbf, 0xe8, 0x9e, 0x72, 0x8, 0x74, 0x6a, 0xdf); // interface defenitions typedef interface ID3DXTextureGutterHelper ID3DXTextureGutterHelper; typedef interface ID3DXTextureGutterHelper *LPD3DXTEXTUREGUTTERHELPER; typedef interface ID3DXPRTBuffer ID3DXPRTBuffer; typedef interface ID3DXPRTBuffer *LPD3DXPRTBUFFER; #undef INTERFACE #define INTERFACE ID3DXPRTBuffer // Buffer interface - contains "NumSamples" samples // each sample in memory is stored as NumCoeffs scalars per channel (1 or 3) // Same interface is used for both Vertex and Pixel PRT buffers DECLARE_INTERFACE_(ID3DXPRTBuffer, IUnknown) { // IUnknown STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef)(THIS) PURE; STDMETHOD_(ULONG, Release)(THIS) PURE; // ID3DXPRTBuffer STDMETHOD_(UINT, GetNumSamples)(THIS) PURE; STDMETHOD_(UINT, GetNumCoeffs)(THIS) PURE; STDMETHOD_(UINT, GetNumChannels)(THIS) PURE; STDMETHOD_(BOOL, IsTexture)(THIS) PURE; STDMETHOD_(UINT, GetWidth)(THIS) PURE; STDMETHOD_(UINT, GetHeight)(THIS) PURE; // changes the number of samples allocated in the buffer STDMETHOD(Resize)(THIS_ UINT NewSize) PURE; // ppData will point to the memory location where sample Start begins // pointer is valid for at least NumSamples samples STDMETHOD(LockBuffer)(THIS_ UINT Start, UINT NumSamples, FLOAT **ppData) PURE; STDMETHOD(UnlockBuffer)(THIS) PURE; // every scalar in buffer is multiplied by Scale STDMETHOD(ScaleBuffer)(THIS_ FLOAT Scale) PURE; // every scalar contains the sum of this and pBuffers values // pBuffer must have the same storage class/dimensions STDMETHOD(AddBuffer)(THIS_ LPD3DXPRTBUFFER pBuffer) PURE; // GutterHelper (described below) will fill in the gutter // regions of a texture by interpolating "internal" values STDMETHOD(AttachGH)(THIS_ LPD3DXTEXTUREGUTTERHELPER) PURE; STDMETHOD(ReleaseGH)(THIS) PURE; // Evaluates attached gutter helper on the contents of this buffer STDMETHOD(EvalGH)(THIS) PURE; // extracts a given channel into texture pTexture // NumCoefficients starting from StartCoefficient are copied STDMETHOD(ExtractTexture)(THIS_ UINT Channel, UINT StartCoefficient, UINT NumCoefficients, LPDIRECT3DTEXTURE9 pTexture) PURE; // extracts NumCoefficients coefficients into mesh - only applicable on single channel // buffers, otherwise just lockbuffer and copy data. With SHPRT data NumCoefficients // should be Order^2 STDMETHOD(ExtractToMesh)(THIS_ UINT NumCoefficients, D3DDECLUSAGE Usage, UINT UsageIndexStart, LPD3DXMESH pScene) PURE; }; typedef interface ID3DXPRTCompBuffer ID3DXPRTCompBuffer; typedef interface ID3DXPRTCompBuffer *LPD3DXPRTCOMPBUFFER; #undef INTERFACE #define INTERFACE ID3DXPRTCompBuffer // compressed buffers stored a compressed version of a PRTBuffer DECLARE_INTERFACE_(ID3DXPRTCompBuffer, IUnknown) { // IUnknown STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef)(THIS) PURE; STDMETHOD_(ULONG, Release)(THIS) PURE; // ID3DPRTCompBuffer // NumCoeffs and NumChannels are properties of input buffer STDMETHOD_(UINT, GetNumSamples)(THIS) PURE; STDMETHOD_(UINT, GetNumCoeffs)(THIS) PURE; STDMETHOD_(UINT, GetNumChannels)(THIS) PURE; STDMETHOD_(BOOL, IsTexture)(THIS) PURE; STDMETHOD_(UINT, GetWidth)(THIS) PURE; STDMETHOD_(UINT, GetHeight)(THIS) PURE; // number of clusters, and PCA vectors per-cluster STDMETHOD_(UINT, GetNumClusters)(THIS) PURE; STDMETHOD_(UINT, GetNumPCA)(THIS) PURE; // normalizes PCA weights so that they are between [-1,1] // basis vectors are modified to reflect this STDMETHOD(NormalizeData)(THIS) PURE; // copies basis vectors for cluster "Cluster" into pClusterBasis // (NumPCA+1)*NumCoeffs*NumChannels floats STDMETHOD(ExtractBasis)(THIS_ UINT Cluster, FLOAT *pClusterBasis) PURE; // UINT per sample - which cluster it belongs to STDMETHOD(ExtractClusterIDs)(THIS_ UINT *pClusterIDs) PURE; // copies NumExtract PCA projection coefficients starting at StartPCA // into pPCACoefficients - NumSamples*NumExtract floats copied STDMETHOD(ExtractPCA)(THIS_ UINT StartPCA, UINT NumExtract, FLOAT *pPCACoefficients) PURE; // copies NumPCA projection coefficients starting at StartPCA // into pTexture - should be able to cope with signed formats STDMETHOD(ExtractTexture)(THIS_ UINT StartPCA, UINT NumpPCA, LPDIRECT3DTEXTURE9 pTexture) PURE; // copies NumPCA projection coefficients into mesh pScene // Usage is D3DDECLUSAGE where coefficients are to be stored // UsageIndexStart is starting index STDMETHOD(ExtractToMesh)(THIS_ UINT NumPCA, D3DDECLUSAGE Usage, UINT UsageIndexStart, LPD3DXMESH pScene) PURE; }; #undef INTERFACE #define INTERFACE ID3DXTextureGutterHelper // ID3DXTextureGutterHelper will build and manage // "gutter" regions in a texture - this will allow for // bi-linear interpolation to not have artifacts when rendering // It generates a map (in texture space) where each texel // is in one of 3 states: // 0 Invalid - not used at all // 1 Inside triangle // 2 Gutter texel // 4 represents a gutter texel that will be computed during PRT // For each Inside/Gutter texel it stores the face it // belongs to and barycentric coordinates for the 1st two // vertices of that face. Gutter vertices are assigned to // the closest edge in texture space. // // When used with PRT this requires a unique parameterization // of the model - every texel must correspond to a single point // on the surface of the model and vice versa DECLARE_INTERFACE_(ID3DXTextureGutterHelper, IUnknown) { // IUnknown STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef)(THIS) PURE; STDMETHOD_(ULONG, Release)(THIS) PURE; // ID3DXTextureGutterHelper // dimensions of texture this is bound too STDMETHOD_(UINT, GetWidth)(THIS) PURE; STDMETHOD_(UINT, GetHeight)(THIS) PURE; // Applying gutters recomputes all of the gutter texels of class "2" // based on texels of class "1" or "4" // Applies gutters to a raw float buffer - each texel is NumCoeffs floats // Width and Height must match GutterHelper STDMETHOD(ApplyGuttersFloat)(THIS_ FLOAT *pDataIn, UINT NumCoeffs, UINT Width, UINT Height); // Applies gutters to pTexture // Dimensions must match GutterHelper STDMETHOD(ApplyGuttersTex)(THIS_ LPDIRECT3DTEXTURE9 pTexture); // Applies gutters to a D3DXPRTBuffer // Dimensions must match GutterHelper STDMETHOD(ApplyGuttersPRT)(THIS_ LPD3DXPRTBUFFER pBuffer); // the routines below provide access to the data structures // used by the Apply functions // face map is a UINT per texel that represents the // face of the mesh that texel belongs too - // only valid if same texel is valid in pGutterData // pFaceData must be allocated by the user STDMETHOD(GetFaceMap)(THIS_ UINT *pFaceData) PURE; // BaryMap is a D3DXVECTOR2 per texel // the 1st two barycentric coordinates for the corresponding // face (3rd weight is always 1-sum of first two) // only valid if same texel is valid in pGutterData // pBaryData must be allocated by the user STDMETHOD(GetBaryMap)(THIS_ D3DXVECTOR2 *pBaryData) PURE; // TexelMap is a D3DXVECTOR2 per texel that // stores the location in pixel coordinates where the // corresponding texel is mapped // pTexelData must be allocated by the user STDMETHOD(GetTexelMap)(THIS_ D3DXVECTOR2 *pTexelData) PURE; // GutterMap is a BYTE per texel // 0/1/2 for Invalid/Internal/Gutter texels // 4 represents a gutter texel that will be computed // during PRT // pGutterData must be allocated by the user STDMETHOD(GetGutterMap)(THIS_ BYTE *pGutterData) PURE; // face map is a UINT per texel that represents the // face of the mesh that texel belongs too - // only valid if same texel is valid in pGutterData STDMETHOD(SetFaceMap)(THIS_ UINT *pFaceData) PURE; // BaryMap is a D3DXVECTOR2 per texel // the 1st two barycentric coordinates for the corresponding // face (3rd weight is always 1-sum of first two) // only valid if same texel is valid in pGutterData STDMETHOD(SetBaryMap)(THIS_ D3DXVECTOR2 *pBaryData) PURE; // TexelMap is a D3DXVECTOR2 per texel that // stores the location in pixel coordinates where the // corresponding texel is mapped STDMETHOD(SetTexelMap)(THIS_ D3DXVECTOR2 *pTexelData) PURE; // GutterMap is a BYTE per texel // 0/1/2 for Invalid/Internal/Gutter texels // 4 represents a gutter texel that will be computed // during PRT STDMETHOD(SetGutterMap)(THIS_ BYTE *pGutterData) PURE; }; typedef interface ID3DXPRTEngine ID3DXPRTEngine; typedef interface ID3DXPRTEngine *LPD3DXPRTENGINE; #undef INTERFACE #define INTERFACE ID3DXPRTEngine // ID3DXPRTEngine is used to compute a PRT simulation // Use the following steps to compute PRT for SH // (1) create an interface (which includes a scene) // (2) call SetSamplingInfo // (3) [optional] Set MeshMaterials/albedo's (required if doing bounces) // (4) call ComputeDirectLightingSH // (5) [optional] call ComputeBounce // repeat step 5 for as many bounces as wanted. // if you want to model subsurface scattering you // need to call ComputeSS after direct lighting and // each bounce. // If you want to bake the albedo into the PRT signal, you // must call MutliplyAlbedo, otherwise the user has to multiply // the albedo themselves. Not multiplying the albedo allows you // to model albedo variation at a finer scale then illumination, and // can result in better compression results. // Luminance values are computed from RGB values using the following // formula: R * 0.2125 + G * 0.7154 + B * 0.0721 DECLARE_INTERFACE_(ID3DXPRTEngine, IUnknown) { // IUnknown STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef)(THIS) PURE; STDMETHOD_(ULONG, Release)(THIS) PURE; // ID3DXPRTEngine // This sets a material per attribute in the scene mesh and it is // the only way to specify subsurface scattering parameters. if // bSetAlbedo is FALSE, NumChannels must match the current // configuration of the PRTEngine. If you intend to change // NumChannels (through some other SetAlbedo function) it must // happen before SetMeshMaterials is called. // // NumChannels 1 implies "grayscale" materials, set this to 3 to enable // color bleeding effects // bSetAlbedo sets albedo from material if TRUE - which clobbers per texel/vertex // albedo that might have been set before. FALSE won't clobber. // fLengthScale is used for subsurface scattering - scene is mapped into a 1mm unit cube // and scaled by this amount STDMETHOD(SetMeshMaterials)(THIS_ CONST D3DXSHMATERIAL **ppMaterials, UINT NumMeshes, UINT NumChannels, BOOL bSetAlbedo, FLOAT fLengthScale) PURE; // setting albedo per-vertex or per-texel over rides the albedos stored per mesh // but it does not over ride any other settings // sets an albedo to be used per vertex - the albedo is represented as a float // pDataIn input pointer (pointint to albedo of 1st sample) // NumChannels 1 implies "grayscale" materials, set this to 3 to enable // color bleeding effects // Stride - stride in bytes to get to next samples albedo STDMETHOD(SetPerVertexAlbedo)(THIS_ CONST VOID *pDataIn, UINT NumChannels, UINT Stride) PURE; // represents the albedo per-texel instead of per-vertex (even if per-vertex PRT is used) // pAlbedoTexture - texture that stores the albedo (dimension arbitrary) // NumChannels 1 implies "grayscale" materials, set this to 3 to enable // color bleeding effects // pGH - optional gutter helper, otherwise one is constructed in computation routines and // destroyed (if not attached to buffers) STDMETHOD(SetPerTexelAlbedo)(THIS_ LPDIRECT3DTEXTURE9 pAlbedoTexture, UINT NumChannels, LPD3DXTEXTUREGUTTERHELPER pGH) PURE; // gets the per-vertex albedo STDMETHOD(GetVertexAlbedo)(THIS_ D3DXCOLOR *pVertColors, UINT NumVerts) PURE; // If pixel PRT is being computed normals default to ones that are interpolated // from the vertex normals. This specifies a texture that stores an object // space normal map instead (must use a texture format that can represent signed values) // pNormalTexture - normal map, must be same dimensions as PRTBuffers, signed STDMETHOD(SetPerTexelNormal)(THIS_ LPDIRECT3DTEXTURE9 pNormalTexture) PURE; // Copies per-vertex albedo from mesh // pMesh - mesh that represents the scene. It must have the same // properties as the mesh used to create the PRTEngine // Usage - D3DDECLUSAGE to extract albedos from // NumChannels 1 implies "grayscale" materials, set this to 3 to enable // color bleeding effects STDMETHOD(ExtractPerVertexAlbedo)(THIS_ LPD3DXMESH pMesh, D3DDECLUSAGE Usage, UINT NumChannels) PURE; // Resamples the input buffer into the output buffer // can be used to move between per-vertex and per-texel buffers. This can also be used // to convert single channel buffers to 3-channel buffers and vice-versa. STDMETHOD(ResampleBuffer)(THIS_ LPD3DXPRTBUFFER pBufferIn, LPD3DXPRTBUFFER pBufferOut) PURE; // Returns the scene mesh - including modifications from adaptive spatial sampling // The returned mesh only has positions, normals and texture coordinates (if defined) // pD3DDevice - d3d device that will be used to allocate the mesh // pFaceRemap - each face has a pointer back to the face on the original mesh that it comes from // if the face hasn't been subdivided this will be an identity mapping // pVertRemap - each vertex contains 3 vertices that this is a linear combination of // pVertWeights - weights for each of above indices (sum to 1.0f) // ppMesh - mesh that will be allocated and filled STDMETHOD(GetAdaptedMesh)(THIS_ LPDIRECT3DDEVICE9 pD3DDevice,UINT *pFaceRemap, UINT *pVertRemap, FLOAT *pfVertWeights, LPD3DXMESH *ppMesh) PURE; // Number of vertices currently allocated (includes new vertices from adaptive sampling) STDMETHOD_(UINT, GetNumVerts)(THIS) PURE; // Number of faces currently allocated (includes new faces) STDMETHOD_(UINT, GetNumFaces)(THIS) PURE; // This will subdivide faces on a mesh so that adaptively simulations can // use a more conservative threshold (it won't miss features.) // MinEdgeLength - minimum edge length that will be generated, if 0.0f a // reasonable default will be used // MaxSubdiv - maximum level of subdivision, if 0 is specified a default // value will be used (5) STDMETHOD(RobustMeshRefine)(THIS_ FLOAT MinEdgeLength, UINT MaxSubdiv) PURE; // This sets to sampling information used by the simulator. Adaptive sampling // parameters are currently ignored. // NumRays - number of rays to shoot per sample // UseSphere - if TRUE uses spherical samples, otherwise samples over // the hemisphere. Should only be used with GPU and Vol computations // UseCosine - if TRUE uses a cosine weighting - not used for Vol computations // or if only the visiblity function is desired // Adaptive - if TRUE adaptive sampling (angular) is used // AdaptiveThresh - threshold used to terminate adaptive angular sampling // ignored if adaptive sampling is not set STDMETHOD(SetSamplingInfo)(THIS_ UINT NumRays, BOOL UseSphere, BOOL UseCosine, BOOL Adaptive, FLOAT AdaptiveThresh) PURE; // Methods that compute the direct lighting contribution for objects // always represente light using spherical harmonics (SH) // the albedo is not multiplied by the signal - it just integrates // incoming light. If NumChannels is not 1 the vector is replicated // // SHOrder - order of SH to use // pDataOut - PRT buffer that is generated. Can be single channel STDMETHOD(ComputeDirectLightingSH)(THIS_ UINT SHOrder, LPD3DXPRTBUFFER pDataOut) PURE; // Adaptive variant of above function. This will refine the mesh // generating new vertices/faces to approximate the PRT signal // more faithfully. // SHOrder - order of SH to use // AdaptiveThresh - threshold for adaptive subdivision (in PRT vector error) // if value is less then 1e-6f, 1e-6f is specified // MinEdgeLength - minimum edge length that will be generated // if value is too small a fairly conservative model dependent value // is used // MaxSubdiv - maximum subdivision level, if 0 is specified it // will default to 4 // pDataOut - PRT buffer that is generated. Can be single channel. STDMETHOD(ComputeDirectLightingSHAdaptive)(THIS_ UINT SHOrder, FLOAT AdaptiveThresh, FLOAT MinEdgeLength, UINT MaxSubdiv, LPD3DXPRTBUFFER pDataOut) PURE; // Function that computes the direct lighting contribution for objects // light is always represented using spherical harmonics (SH) // This is done on the GPU and is much faster then using the CPU. // The albedo is not multiplied by the signal - it just integrates // incoming light. If NumChannels is not 1 the vector is replicated. // ZBias/ZAngleBias are akin to parameters used with shadow zbuffers. // A reasonable default for both values is 0.005, but the user should // experiment (ZAngleBias can be zero, ZBias should not be.) // Callbacks should not use the Direct3D9Device the simulator is using. // SetSamplingInfo must be called with TRUE for UseSphere and // FALSE for UseCosine before this method is called. // // pD3DDevice - device used to run GPU simulator - must support PS2.0 // and FP render targets // Flags - parameters for the GPU simulator, combination of one or more // D3DXSHGPUSIMOPT flags. Only one SHADOWRES setting should be set and // the defaults is 512 // SHOrder - order of SH to use // ZBias - bias in normal direction (for depth test) // ZAngleBias - scaled by one minus cosine of angle with light (offset in depth) // pDataOut - PRT buffer that is filled in. Can be single channel STDMETHOD(ComputeDirectLightingSHGPU)(THIS_ LPDIRECT3DDEVICE9 pD3DDevice, UINT Flags, UINT SHOrder, FLOAT ZBias, FLOAT ZAngleBias, LPD3DXPRTBUFFER pDataOut) PURE; // Functions that computes subsurface scattering (using material properties) // Albedo is not multiplied by result. This only works for per-vertex data // use ResampleBuffer to move per-vertex data into a texture and back. // // pDataIn - input data (previous bounce) // pDataOut - result of subsurface scattering simulation // pDataTotal - [optional] results can be summed into this buffer STDMETHOD(ComputeSS)(THIS_ LPD3DXPRTBUFFER pDataIn, LPD3DXPRTBUFFER pDataOut, LPD3DXPRTBUFFER pDataTotal) PURE; // computes a single bounce of inter-reflected light // works for SH based PRT or generic lighting // Albedo is not multiplied by result // // pDataIn - previous bounces data // pDataOut - PRT buffer that is generated // pDataTotal - [optional] can be used to keep a running sum STDMETHOD(ComputeBounce)(THIS_ LPD3DXPRTBUFFER pDataIn, LPD3DXPRTBUFFER pDataOut, LPD3DXPRTBUFFER pDataTotal) PURE; // Adaptive version of above function. // // pDataIn - previous bounces data, can be single channel // AdaptiveThresh - threshold for adaptive subdivision (in PRT vector error) // if value is less then 1e-6f, 1e-6f is specified // MinEdgeLength - minimum edge length that will be generated // if value is too small a fairly conservative model dependent value // is used // MaxSubdiv - maximum subdivision level, if 0 is specified it // will default to 4 // pDataOut - PRT buffer that is generated // pDataTotal - [optional] can be used to keep a running sum STDMETHOD(ComputeBounceAdaptive)(THIS_ LPD3DXPRTBUFFER pDataIn, FLOAT AdaptiveThresh, FLOAT MinEdgeLength, UINT MaxSubdiv, LPD3DXPRTBUFFER pDataOut, LPD3DXPRTBUFFER pDataTotal) PURE; // Computes projection of distant SH radiance into a local SH radiance // function. This models how direct lighting is attenuated by the // scene and is a form of "neighborhood transfer." The result is // a linear operator (matrix) at every sample point, if you multiply // this matrix by the distant SH lighting coefficients you get an // approximation of the local incident radiance function from // direct lighting. These resulting lighting coefficients can // than be projected into another basis or used with any rendering // technique that uses spherical harmonics as input. // SetSamplingInfo must be called with TRUE for UseSphere and // FALSE for UseCosine before this method is called. // Generates SHOrderIn*SHOrderIn*SHOrderOut*SHOrderOut scalars // per channel at each sample location. // // SHOrderIn - Order of the SH representation of distant lighting // SHOrderOut - Order of the SH representation of local lighting // NumVolSamples - Number of sample locations // pSampleLocs - position of sample locations // pDataOut - PRT Buffer that will store output results STDMETHOD(ComputeVolumeSamplesDirectSH)(THIS_ UINT SHOrderIn, UINT SHOrderOut, UINT NumVolSamples, CONST D3DXVECTOR3 *pSampleLocs, LPD3DXPRTBUFFER pDataOut) PURE; // At each sample location computes a linear operator (matrix) that maps // the representation of source radiance (NumCoeffs in pSurfDataIn) // into a local incident radiance function approximated with spherical // harmonics. For example if a light map data is specified in pSurfDataIn // the result is an SH representation of the flow of light at each sample // point. If PRT data for an outdoor scene is used, each sample point // contains a matrix that models how distant lighting bounces of the objects // in the scene and arrives at the given sample point. Combined with // ComputeVolumeSamplesDirectSH this gives the complete representation for // how light arrives at each sample point parameterized by distant lighting. // SetSamplingInfo must be called with TRUE for UseSphere and // FALSE for UseCosine before this method is called. // Generates pSurfDataIn->NumCoeffs()*SHOrder*SHOrder scalars // per channel at each sample location. // // pSurfDataIn - previous bounce data // SHOrder - order of SH to generate projection with // NumVolSamples - Number of sample locations // pSampleLocs - position of sample locations // pDataOut - PRT Buffer that will store output results STDMETHOD(ComputeVolumeSamples)(THIS_ LPD3DXPRTBUFFER pSurfDataIn, UINT SHOrder, UINT NumVolSamples, CONST D3DXVECTOR3 *pSampleLocs, LPD3DXPRTBUFFER pDataOut) PURE; // Frees temporary data structures that can be created for subsurface scattering // this data is freed when the PRTComputeEngine is freed and is lazily created STDMETHOD(FreeSSData)(THIS) PURE; // Frees temporary data structures that can be created for bounce simulations // this data is freed when the PRTComputeEngine is freed and is lazily created STDMETHOD(FreeBounceData)(THIS) PURE; // This computes the convolution coefficients relative to the per sample normals // that minimize error in a least squares sense with respect to the input PRT // data set. These coefficients can be used with skinned/transformed normals to // model global effects with dynamic objects. Shading normals can optionaly be // solved for - these normals (along with the convolution coefficients) can more // accurately represent the PRT signal. // // pDataIn - SH PRT dataset that is input // SHOrder - Order of SH to compute conv coefficients for // pNormOut - Optional array of vectors (passed in) that will be filled with // "shading normals", convolution coefficients are optimized for // these normals. This array must be the same size as the number of // samples in pDataIn // pDataOut - Output buffer (SHOrder convolution coefficients per channel per sample) STDMETHOD(ComputeConvCoeffs)(THIS_ LPD3DXPRTBUFFER pDataIn, UINT SHOrder, D3DXVECTOR3 *pNormOut, LPD3DXPRTBUFFER pDataOut) PURE; // scales all the samples associated with a given sub mesh // can be useful when using subsurface scattering // fScale - value to scale each vector in submesh by STDMETHOD(ScaleMeshChunk)(THIS_ UINT uMeshChunk, FLOAT fScale, LPD3DXPRTBUFFER pDataOut) PURE; // mutliplies each PRT vector by the albedo - can be used if you want to have the albedo // burned into the dataset, often better not to do this. If this is not done the user // must mutliply the albedo themselves when rendering - just multiply the albedo times // the result of the PRT dot product. // If pDataOut is a texture simulation result and there is an albedo texture it // must be represented at the same resolution as the simulation buffer. You can use // LoadSurfaceFromSurface and set a new albedo texture if this is an issue - but must // be careful about how the gutters are handled. // // pDataOut - dataset that will get albedo pushed into it STDMETHOD(MultiplyAlbedo)(THIS_ LPD3DXPRTBUFFER pDataOut) PURE; // Sets a pointer to an optional call back function that reports back to the // user percentage done and gives them the option of quitting // pCB - pointer to call back function, return S_OK for the simulation // to continue // Frequency - 1/Frequency is roughly the number of times the call back // will be invoked // lpUserContext - will be passed back to the users call back STDMETHOD(SetCallBack)(THIS_ LPD3DXSHPRTSIMCB pCB, FLOAT Frequency, LPVOID lpUserContext) PURE; }; // API functions for creating interfaces #ifdef __cplusplus extern "C" { #endif //__cplusplus //============================================================================ // // D3DXCreatePRTBuffer: // -------------------- // Generates a PRT Buffer that can be compressed or filled by a simulator // This function should be used to create per-vertex or volume buffers. // When buffers are created all values are initialized to zero. // // Parameters: // NumSamples // Number of sample locations represented // NumCoeffs // Number of coefficients per sample location (order^2 for SH) // NumChannels // Number of color channels to represent (1 or 3) // ppBuffer // Buffer that will be allocated // //============================================================================ HRESULT WINAPI D3DXCreatePRTBuffer( UINT NumSamples, UINT NumCoeffs, UINT NumChannels, LPD3DXPRTBUFFER* ppBuffer); //============================================================================ // // D3DXCreatePRTBufferTex: // -------------------- // Generates a PRT Buffer that can be compressed or filled by a simulator // This function should be used to create per-pixel buffers. // When buffers are created all values are initialized to zero. // // Parameters: // Width // Width of texture // Height // Height of texture // NumCoeffs // Number of coefficients per sample location (order^2 for SH) // NumChannels // Number of color channels to represent (1 or 3) // ppBuffer // Buffer that will be allocated // //============================================================================ HRESULT WINAPI D3DXCreatePRTBufferTex( UINT Width, UINT Height, UINT NumCoeffs, UINT NumChannels, LPD3DXPRTBUFFER* ppBuffer); //============================================================================ // // D3DXLoadPRTBufferFromFile: // -------------------- // Loads a PRT buffer that has been saved to disk. // // Parameters: // pFilename // Name of the file to load // ppBuffer // Buffer that will be allocated // //============================================================================ HRESULT WINAPI D3DXLoadPRTBufferFromFileA( LPCSTR pFilename, LPD3DXPRTBUFFER* ppBuffer); HRESULT WINAPI D3DXLoadPRTBufferFromFileW( LPCWSTR pFilename, LPD3DXPRTBUFFER* ppBuffer); #ifdef UNICODE #define D3DXLoadPRTBufferFromFile D3DXLoadPRTBufferFromFileW #else #define D3DXLoadPRTBufferFromFile D3DXLoadPRTBufferFromFileA #endif //============================================================================ // // D3DXSavePRTBufferToFile: // -------------------- // Saves a PRTBuffer to disk. // // Parameters: // pFilename // Name of the file to save // pBuffer // Buffer that will be saved // //============================================================================ HRESULT WINAPI D3DXSavePRTBufferToFileA( LPCSTR pFileName, LPD3DXPRTBUFFER pBuffer); HRESULT WINAPI D3DXSavePRTBufferToFileW( LPCWSTR pFileName, LPD3DXPRTBUFFER pBuffer); #ifdef UNICODE #define D3DXSavePRTBufferToFile D3DXSavePRTBufferToFileW #else #define D3DXSavePRTBufferToFile D3DXSavePRTBufferToFileA #endif //============================================================================ // // D3DXLoadPRTCompBufferFromFile: // -------------------- // Loads a PRTComp buffer that has been saved to disk. // // Parameters: // pFilename // Name of the file to load // ppBuffer // Buffer that will be allocated // //============================================================================ HRESULT WINAPI D3DXLoadPRTCompBufferFromFileA( LPCSTR pFilename, LPD3DXPRTCOMPBUFFER* ppBuffer); HRESULT WINAPI D3DXLoadPRTCompBufferFromFileW( LPCWSTR pFilename, LPD3DXPRTCOMPBUFFER* ppBuffer); #ifdef UNICODE #define D3DXLoadPRTCompBufferFromFile D3DXLoadPRTCompBufferFromFileW #else #define D3DXLoadPRTCompBufferFromFile D3DXLoadPRTCompBufferFromFileA #endif //============================================================================ // // D3DXSavePRTCompBufferToFile: // -------------------- // Saves a PRTCompBuffer to disk. // // Parameters: // pFilename // Name of the file to save // pBuffer // Buffer that will be saved // //============================================================================ HRESULT WINAPI D3DXSavePRTCompBufferToFileA( LPCSTR pFileName, LPD3DXPRTCOMPBUFFER pBuffer); HRESULT WINAPI D3DXSavePRTCompBufferToFileW( LPCWSTR pFileName, LPD3DXPRTCOMPBUFFER pBuffer); #ifdef UNICODE #define D3DXSavePRTCompBufferToFile D3DXSavePRTCompBufferToFileW #else #define D3DXSavePRTCompBufferToFile D3DXSavePRTCompBufferToFileA #endif //============================================================================ // // D3DXCreatePRTCompBuffer: // -------------------- // Compresses a PRT buffer (vertex or texel) // // Parameters: // D3DXSHCOMPRESSQUALITYTYPE // Quality of compression - low is faster (computes PCA per voronoi cluster) // high is slower but better quality (clusters based on distance to affine subspace) // NumClusters // Number of clusters to compute // NumPCA // Number of basis vectors to compute // ppBufferIn // Buffer that will be compressed // ppBufferOut // Compressed buffer that will be created // //============================================================================ HRESULT WINAPI D3DXCreatePRTCompBuffer( D3DXSHCOMPRESSQUALITYTYPE Quality, UINT NumClusters, UINT NumPCA, LPD3DXPRTBUFFER pBufferIn, LPD3DXPRTCOMPBUFFER *ppBufferOut ); //============================================================================ // // D3DXCreateTextureGutterHelper: // -------------------- // Generates a "GutterHelper" for a given set of meshes and texture // resolution // // Parameters: // Width // Width of texture // Height // Height of texture // pMesh // Mesh that represents the scene // GutterSize // Number of texels to over rasterize in texture space // this should be at least 1.0 // ppBuffer // GutterHelper that will be created // //============================================================================ HRESULT WINAPI D3DXCreateTextureGutterHelper( UINT Width, UINT Height, LPD3DXMESH pMesh, FLOAT GutterSize, LPD3DXTEXTUREGUTTERHELPER* ppBuffer); //============================================================================ // // D3DXCreatePRTEngine: // -------------------- // Computes a PRTEngine which can efficiently generate PRT simulations // of a scene // // Parameters: // pMesh // Mesh that represents the scene - must have an AttributeTable // where vertices are in a unique attribute. // ExtractUVs // Set this to true if textures are going to be used for albedos // or to store PRT vectors // pBlockerMesh // Optional mesh that just blocks the scene // ppEngine // PRTEngine that will be created // //============================================================================ HRESULT WINAPI D3DXCreatePRTEngine( LPD3DXMESH pMesh, BOOL ExtractUVs, LPD3DXMESH pBlockerMesh, LPD3DXPRTENGINE* ppEngine); //============================================================================ // // D3DXConcatenateMeshes: // -------------------- // Concatenates a group of meshes into one common mesh. This can optionaly transform // each sub mesh or its texture coordinates. If no DECL is given it will // generate a union of all of the DECL's of the sub meshes, promoting channels // and types if neccesary. It will create an AttributeTable if possible, one can // call OptimizeMesh with attribute sort and compacting enabled to ensure this. // // Parameters: // ppMeshes // Array of pointers to meshes that can store PRT vectors // NumMeshes // Number of meshes // Options // Passed through to D3DXCreateMesh // pGeomXForms // [optional] Each sub mesh is transformed by the corresponding // matrix if this array is supplied // pTextureXForms // [optional] UV coordinates for each sub mesh are transformed // by corresponding matrix if supplied // pDecl // [optional] Only information in this DECL is used when merging // data // pD3DDevice // D3D device that is used to create the new mesh // ppMeshOut // Mesh that will be created // //============================================================================ HRESULT WINAPI D3DXConcatenateMeshes( LPD3DXMESH *ppMeshes, UINT NumMeshes, DWORD Options, CONST D3DXMATRIX *pGeomXForms, CONST D3DXMATRIX *pTextureXForms, CONST D3DVERTEXELEMENT9 *pDecl, LPDIRECT3DDEVICE9 pD3DDevice, LPD3DXMESH *ppMeshOut); //============================================================================ // // D3DXSHPRTCompSuperCluster: // -------------------------- // Used with compressed results of D3DXSHPRTSimulation. // Generates "super clusters" - groups of clusters that can be drawn in // the same draw call. A greedy algorithm that minimizes overdraw is used // to group the clusters. // // Parameters: // pClusterIDs // NumVerts cluster ID's (extracted from a compressed buffer) // pScene // Mesh that represents composite scene passed to the simulator // MaxNumClusters // Maximum number of clusters allocated per super cluster // NumClusters // Number of clusters computed in the simulator // pSuperClusterIDs // Array of length NumClusters, contains index of super cluster // that corresponding cluster was assigned to // pNumSuperClusters // Returns the number of super clusters allocated // //============================================================================ HRESULT WINAPI D3DXSHPRTCompSuperCluster( UINT *pClusterIDs, LPD3DXMESH pScene, UINT MaxNumClusters, UINT NumClusters, UINT *pSuperClusterIDs, UINT *pNumSuperClusters); //============================================================================ // // D3DXSHPRTCompSplitMeshSC: // ------------------------- // Used with compressed results of the vertex version of the PRT simulator. // After D3DXSHRTCompSuperCluster has been called this function can be used // to split the mesh into a group of faces/vertices per super cluster. // Each super cluster contains all of the faces that contain any vertex // classified in one of its clusters. All of the vertices connected to this // set of faces are also included with the returned array ppVertStatus // indicating whether or not the vertex belongs to the supercluster. // // Parameters: // pClusterIDs // NumVerts cluster ID's (extracted from a compressed buffer) // NumVertices // Number of vertices in original mesh // NumClusters // Number of clusters (input parameter to compression) // pSuperClusterIDs // Array of size NumClusters that will contain super cluster ID's (from // D3DXSHCompSuerCluster) // NumSuperClusters // Number of superclusters allocated in D3DXSHCompSuerCluster // pInputIB // Raw index buffer for mesh - format depends on bInputIBIs32Bit // InputIBIs32Bit // Indicates whether the input index buffer is 32-bit (otherwise 16-bit // is assumed) // NumFaces // Number of faces in the original mesh (pInputIB is 3 times this length) // ppIBData // LPD3DXBUFFER holds raw index buffer that will contain the resulting split faces. // Format determined by bIBIs32Bit. Allocated by function // pIBDataLength // Length of ppIBData, assigned in function // OutputIBIs32Bit // Indicates whether the output index buffer is to be 32-bit (otherwise // 16-bit is assumed) // ppFaceRemap // LPD3DXBUFFER mapping of each face in ppIBData to original faces. Length is // *pIBDataLength/3. Optional paramter, allocated in function // ppVertData // LPD3DXBUFFER contains new vertex data structure. Size of pVertDataLength // pVertDataLength // Number of new vertices in split mesh. Assigned in function // pSCClusterList // Array of length NumClusters which pSCData indexes into (Cluster* fields) // for each SC, contains clusters sorted by super cluster // pSCData // Structure per super cluster - contains indices into ppIBData, // pSCClusterList and ppVertData // //============================================================================ HRESULT WINAPI D3DXSHPRTCompSplitMeshSC( UINT *pClusterIDs, UINT NumVertices, UINT NumClusters, UINT *pSuperClusterIDs, UINT NumSuperClusters, LPVOID pInputIB, BOOL InputIBIs32Bit, UINT NumFaces, LPD3DXBUFFER *ppIBData, UINT *pIBDataLength, BOOL OutputIBIs32Bit, LPD3DXBUFFER *ppFaceRemap, LPD3DXBUFFER *ppVertData, UINT *pVertDataLength, UINT *pSCClusterList, D3DXSHPRTSPLITMESHCLUSTERDATA *pSCData); #ifdef __cplusplus } #endif //__cplusplus ////////////////////////////////////////////////////////////////////////////// // // Definitions of .X file templates used by mesh load/save functions // that are not RM standard // ////////////////////////////////////////////////////////////////////////////// // {3CF169CE-FF7C-44ab-93C0-F78F62D172E2} DEFINE_GUID(DXFILEOBJ_XSkinMeshHeader, 0x3cf169ce, 0xff7c, 0x44ab, 0x93, 0xc0, 0xf7, 0x8f, 0x62, 0xd1, 0x72, 0xe2); // {B8D65549-D7C9-4995-89CF-53A9A8B031E3} DEFINE_GUID(DXFILEOBJ_VertexDuplicationIndices, 0xb8d65549, 0xd7c9, 0x4995, 0x89, 0xcf, 0x53, 0xa9, 0xa8, 0xb0, 0x31, 0xe3); // {A64C844A-E282-4756-8B80-250CDE04398C} DEFINE_GUID(DXFILEOBJ_FaceAdjacency, 0xa64c844a, 0xe282, 0x4756, 0x8b, 0x80, 0x25, 0xc, 0xde, 0x4, 0x39, 0x8c); // {6F0D123B-BAD2-4167-A0D0-80224F25FABB} DEFINE_GUID(DXFILEOBJ_SkinWeights, 0x6f0d123b, 0xbad2, 0x4167, 0xa0, 0xd0, 0x80, 0x22, 0x4f, 0x25, 0xfa, 0xbb); // {A3EB5D44-FC22-429d-9AFB-3221CB9719A6} DEFINE_GUID(DXFILEOBJ_Patch, 0xa3eb5d44, 0xfc22, 0x429d, 0x9a, 0xfb, 0x32, 0x21, 0xcb, 0x97, 0x19, 0xa6); // {D02C95CC-EDBA-4305-9B5D-1820D7704BBF} DEFINE_GUID(DXFILEOBJ_PatchMesh, 0xd02c95cc, 0xedba, 0x4305, 0x9b, 0x5d, 0x18, 0x20, 0xd7, 0x70, 0x4b, 0xbf); // {B9EC94E1-B9A6-4251-BA18-94893F02C0EA} DEFINE_GUID(DXFILEOBJ_PatchMesh9, 0xb9ec94e1, 0xb9a6, 0x4251, 0xba, 0x18, 0x94, 0x89, 0x3f, 0x2, 0xc0, 0xea); // {B6C3E656-EC8B-4b92-9B62-681659522947} DEFINE_GUID(DXFILEOBJ_PMInfo, 0xb6c3e656, 0xec8b, 0x4b92, 0x9b, 0x62, 0x68, 0x16, 0x59, 0x52, 0x29, 0x47); // {917E0427-C61E-4a14-9C64-AFE65F9E9844} DEFINE_GUID(DXFILEOBJ_PMAttributeRange, 0x917e0427, 0xc61e, 0x4a14, 0x9c, 0x64, 0xaf, 0xe6, 0x5f, 0x9e, 0x98, 0x44); // {574CCC14-F0B3-4333-822D-93E8A8A08E4C} DEFINE_GUID(DXFILEOBJ_PMVSplitRecord, 0x574ccc14, 0xf0b3, 0x4333, 0x82, 0x2d, 0x93, 0xe8, 0xa8, 0xa0, 0x8e, 0x4c); // {B6E70A0E-8EF9-4e83-94AD-ECC8B0C04897} DEFINE_GUID(DXFILEOBJ_FVFData, 0xb6e70a0e, 0x8ef9, 0x4e83, 0x94, 0xad, 0xec, 0xc8, 0xb0, 0xc0, 0x48, 0x97); // {F752461C-1E23-48f6-B9F8-8350850F336F} DEFINE_GUID(DXFILEOBJ_VertexElement, 0xf752461c, 0x1e23, 0x48f6, 0xb9, 0xf8, 0x83, 0x50, 0x85, 0xf, 0x33, 0x6f); // {BF22E553-292C-4781-9FEA-62BD554BDD93} DEFINE_GUID(DXFILEOBJ_DeclData, 0xbf22e553, 0x292c, 0x4781, 0x9f, 0xea, 0x62, 0xbd, 0x55, 0x4b, 0xdd, 0x93); // {F1CFE2B3-0DE3-4e28-AFA1-155A750A282D} DEFINE_GUID(DXFILEOBJ_EffectFloats, 0xf1cfe2b3, 0xde3, 0x4e28, 0xaf, 0xa1, 0x15, 0x5a, 0x75, 0xa, 0x28, 0x2d); // {D55B097E-BDB6-4c52-B03D-6051C89D0E42} DEFINE_GUID(DXFILEOBJ_EffectString, 0xd55b097e, 0xbdb6, 0x4c52, 0xb0, 0x3d, 0x60, 0x51, 0xc8, 0x9d, 0xe, 0x42); // {622C0ED0-956E-4da9-908A-2AF94F3CE716} DEFINE_GUID(DXFILEOBJ_EffectDWord, 0x622c0ed0, 0x956e, 0x4da9, 0x90, 0x8a, 0x2a, 0xf9, 0x4f, 0x3c, 0xe7, 0x16); // {3014B9A0-62F5-478c-9B86-E4AC9F4E418B} DEFINE_GUID(DXFILEOBJ_EffectParamFloats, 0x3014b9a0, 0x62f5, 0x478c, 0x9b, 0x86, 0xe4, 0xac, 0x9f, 0x4e, 0x41, 0x8b); // {1DBC4C88-94C1-46ee-9076-2C28818C9481} DEFINE_GUID(DXFILEOBJ_EffectParamString, 0x1dbc4c88, 0x94c1, 0x46ee, 0x90, 0x76, 0x2c, 0x28, 0x81, 0x8c, 0x94, 0x81); // {E13963BC-AE51-4c5d-B00F-CFA3A9D97CE5} DEFINE_GUID(DXFILEOBJ_EffectParamDWord, 0xe13963bc, 0xae51, 0x4c5d, 0xb0, 0xf, 0xcf, 0xa3, 0xa9, 0xd9, 0x7c, 0xe5); // {E331F7E4-0559-4cc2-8E99-1CEC1657928F} DEFINE_GUID(DXFILEOBJ_EffectInstance, 0xe331f7e4, 0x559, 0x4cc2, 0x8e, 0x99, 0x1c, 0xec, 0x16, 0x57, 0x92, 0x8f); // {9E415A43-7BA6-4a73-8743-B73D47E88476} DEFINE_GUID(DXFILEOBJ_AnimTicksPerSecond, 0x9e415a43, 0x7ba6, 0x4a73, 0x87, 0x43, 0xb7, 0x3d, 0x47, 0xe8, 0x84, 0x76); // {7F9B00B3-F125-4890-876E-1CFFBF697C4D} DEFINE_GUID(DXFILEOBJ_CompressedAnimationSet, 0x7f9b00b3, 0xf125, 0x4890, 0x87, 0x6e, 0x1c, 0x42, 0xbf, 0x69, 0x7c, 0x4d); #pragma pack(push, 1) typedef struct _XFILECOMPRESSEDANIMATIONSET { DWORD CompressedBlockSize; FLOAT TicksPerSec; DWORD PlaybackType; DWORD BufferLength; } XFILECOMPRESSEDANIMATIONSET; #pragma pack(pop) #define XSKINEXP_TEMPLATES \ "xof 0303txt 0032\ template XSkinMeshHeader \ { \ <3CF169CE-FF7C-44ab-93C0-F78F62D172E2> \ WORD nMaxSkinWeightsPerVertex; \ WORD nMaxSkinWeightsPerFace; \ WORD nBones; \ } \ template VertexDuplicationIndices \ { \ <B8D65549-D7C9-4995-89CF-53A9A8B031E3> \ DWORD nIndices; \ DWORD nOriginalVertices; \ array DWORD indices[nIndices]; \ } \ template FaceAdjacency \ { \ <A64C844A-E282-4756-8B80-250CDE04398C> \ DWORD nIndices; \ array DWORD indices[nIndices]; \ } \ template SkinWeights \ { \ <6F0D123B-BAD2-4167-A0D0-80224F25FABB> \ STRING transformNodeName; \ DWORD nWeights; \ array DWORD vertexIndices[nWeights]; \ array float weights[nWeights]; \ Matrix4x4 matrixOffset; \ } \ template Patch \ { \ <A3EB5D44-FC22-429D-9AFB-3221CB9719A6> \ DWORD nControlIndices; \ array DWORD controlIndices[nControlIndices]; \ } \ template PatchMesh \ { \ <D02C95CC-EDBA-4305-9B5D-1820D7704BBF> \ DWORD nVertices; \ array Vector vertices[nVertices]; \ DWORD nPatches; \ array Patch patches[nPatches]; \ [ ... ] \ } \ template PatchMesh9 \ { \ <B9EC94E1-B9A6-4251-BA18-94893F02C0EA> \ DWORD Type; \ DWORD Degree; \ DWORD Basis; \ DWORD nVertices; \ array Vector vertices[nVertices]; \ DWORD nPatches; \ array Patch patches[nPatches]; \ [ ... ] \ } " \ "template EffectFloats \ { \ <F1CFE2B3-0DE3-4e28-AFA1-155A750A282D> \ DWORD nFloats; \ array float Floats[nFloats]; \ } \ template EffectString \ { \ <D55B097E-BDB6-4c52-B03D-6051C89D0E42> \ STRING Value; \ } \ template EffectDWord \ { \ <622C0ED0-956E-4da9-908A-2AF94F3CE716> \ DWORD Value; \ } " \ "template EffectParamFloats \ { \ <3014B9A0-62F5-478c-9B86-E4AC9F4E418B> \ STRING ParamName; \ DWORD nFloats; \ array float Floats[nFloats]; \ } " \ "template EffectParamString \ { \ <1DBC4C88-94C1-46ee-9076-2C28818C9481> \ STRING ParamName; \ STRING Value; \ } \ template EffectParamDWord \ { \ <E13963BC-AE51-4c5d-B00F-CFA3A9D97CE5> \ STRING ParamName; \ DWORD Value; \ } \ template EffectInstance \ { \ <E331F7E4-0559-4cc2-8E99-1CEC1657928F> \ STRING EffectFilename; \ [ ... ] \ } " \ "template AnimTicksPerSecond \ { \ <9E415A43-7BA6-4a73-8743-B73D47E88476> \ DWORD AnimTicksPerSecond; \ } \ template CompressedAnimationSet \ { \ <7F9B00B3-F125-4890-876E-1C42BF697C4D> \ DWORD CompressedBlockSize; \ FLOAT TicksPerSec; \ DWORD PlaybackType; \ DWORD BufferLength; \ array DWORD CompressedData[BufferLength]; \ } " #define XEXTENSIONS_TEMPLATES \ "xof 0303txt 0032\ template FVFData \ { \ <B6E70A0E-8EF9-4e83-94AD-ECC8B0C04897> \ DWORD dwFVF; \ DWORD nDWords; \ array DWORD data[nDWords]; \ } \ template VertexElement \ { \ <F752461C-1E23-48f6-B9F8-8350850F336F> \ DWORD Type; \ DWORD Method; \ DWORD Usage; \ DWORD UsageIndex; \ } \ template DeclData \ { \ <BF22E553-292C-4781-9FEA-62BD554BDD93> \ DWORD nElements; \ array VertexElement Elements[nElements]; \ DWORD nDWords; \ array DWORD data[nDWords]; \ } \ template PMAttributeRange \ { \ <917E0427-C61E-4a14-9C64-AFE65F9E9844> \ DWORD iFaceOffset; \ DWORD nFacesMin; \ DWORD nFacesMax; \ DWORD iVertexOffset; \ DWORD nVerticesMin; \ DWORD nVerticesMax; \ } \ template PMVSplitRecord \ { \ <574CCC14-F0B3-4333-822D-93E8A8A08E4C> \ DWORD iFaceCLW; \ DWORD iVlrOffset; \ DWORD iCode; \ } \ template PMInfo \ { \ <B6C3E656-EC8B-4b92-9B62-681659522947> \ DWORD nAttributes; \ array PMAttributeRange attributeRanges[nAttributes]; \ DWORD nMaxValence; \ DWORD nMinLogicalVertices; \ DWORD nMaxLogicalVertices; \ DWORD nVSplits; \ array PMVSplitRecord splitRecords[nVSplits]; \ DWORD nAttributeMispredicts; \ array DWORD attributeMispredicts[nAttributeMispredicts]; \ } " #endif //__D3DX9MESH_H__
narfster/leopard_directshow
leopard_directshow/Include/dshow/d3dx9mesh.h
C
mit
100,639
using System; using Database.Plugin.Abstractions; using SQLite; using Windows.Storage; namespace Database.Plugin { /// <summary> /// Implementation for Database /// </summary> public class DatabaseImplementation : IDatabase { public SQLiteConnection GetConnection(string databaseFileName) { string folder = ApplicationData.Current.LocalFolder.Path; var connection = new SQLiteConnection(System.IO.Path.Combine(folder, databaseFileName)); return connection; } } }
therealjohn/Xamarin.Plugins
Database/Database/Database.Plugin.WindowsStore/DatabaseImplementation.cs
C#
mit
524
<?php return [ /* |-------------------------------------------------------------------------- | View to Bind JavaScript Vars To |-------------------------------------------------------------------------- | | Set this value to the name of the view (or partial) that | you want to prepend all JavaScript variables to. | */ 'bind_js_vars_to_this_view' => 'frontend.layouts.master', /* |-------------------------------------------------------------------------- | JavaScript Namespace |-------------------------------------------------------------------------- | | By default, we'll add variables to the global window object. However, | it's recommended that you change this to some namespace - anything. | That way, you can access vars, like "SomeNamespace.someVariable." | */ 'js_namespace' => 'window' ];
Lphmedia/youbloom
config/javascript.php
PHP
mit
890
const middleware = {} export default middleware
FoalTS/foal
samples/nuxt.js/backend/.nuxt/middleware.js
JavaScript
mit
49
// Generated by CoffeeScript 1.3.3 (function() { var nock, should, wd; wd = require('../common/wd-with-cov'); nock = require('nock'); should = require('should'); describe("wd", function() { return describe("unit", function() { return describe("callback tests", function() { var server; server = null; before(function(done) { server = nock('http://127.0.0.1:5555').filteringRequestBody(/.*/, '*'); if (process.env.WD_COV == null) { server.log(console.log); } server.post('/wd/hub/session', '*').reply(303, "OK", { 'Location': '/wd/hub/session/1234' }); return done(null); }); return describe("simplecallback empty returns", function() { var browser; browser = null; describe("browser initialization", function() { return it("should initialize browser", function(done) { browser = wd.remote({ port: 5555 }); return browser.init({}, function(err) { should.not.exist(err); return done(null); }); }); }); describe("simplecallback with empty return", function() { return it("should get url", function(done) { server.post('/wd/hub/session/1234/url', '*').reply(200, ""); return browser.get("www.google.com", function(err) { should.not.exist(err); return done(null); }); }); }); describe("simplecallback with 200 OK", function() { return it("should get url", function(done) { server.post('/wd/hub/session/1234/url', '*').reply(200, "OK"); return browser.get("www.google.com", function(err) { should.not.exist(err); return done(null); }); }); }); return describe("simplecallback with empty JSON data", function() { return it("should get url", function(done) { server.post('/wd/hub/session/1234/url', '*').reply(200, '{"sessionId":"1234","status":0,"value":{}}'); return browser.get("www.google.com", function(err) { should.not.exist(err); return done(null); }); }); }); }); }); }); }); }).call(this);
espena/terminal
test/node_modules/testem/examples/saucelabs/node_modules/wd/test/unit/callback-test.js
JavaScript
mit
2,483
//===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the LLVMTargetMachine class. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetMachine.h" #include "llvm/PassManager.h" #include "llvm/Pass.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/GCStrategy.h" #include "llvm/CodeGen/MachineFunctionAnalysis.h" #include "llvm/Target/TargetOptions.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCStreamer.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetRegistry.h" #include "llvm/Transforms/Scalar.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FormattedStream.h" using namespace llvm; namespace llvm { bool EnableFastISel; } static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden, cl::desc("Disable Post Regalloc")); static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden, cl::desc("Disable branch folding")); static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, cl::desc("Disable tail duplication")); static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden, cl::desc("Disable pre-register allocation tail duplication")); static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden, cl::desc("Disable code placement")); static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, cl::desc("Disable Stack Slot Coloring")); static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, cl::desc("Disable Machine LICM")); static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, cl::desc("Disable Machine Sinking")); static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, cl::desc("Disable Loop Strength Reduction Pass")); static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, cl::desc("Disable Codegen Prepare")); static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, cl::desc("Print LLVM IR produced by the loop-reduce pass")); static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, cl::desc("Print LLVM IR input to isel pass")); static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, cl::desc("Dump garbage collector data")); static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden, cl::desc("Verify generated machine code"), cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL)); static cl::opt<bool> EnableMachineCSE("enable-machine-cse", cl::Hidden, cl::desc("Enable Machine CSE")); static cl::opt<cl::boolOrDefault> AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), cl::init(cl::BOU_UNSET)); static bool getVerboseAsm() { switch (AsmVerbose) { default: case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault(); case cl::BOU_TRUE: return true; case cl::BOU_FALSE: return false; } } // Enable or disable FastISel. Both options are needed, because // FastISel is enabled by default with -fast, and we wish to be // able to enable or disable fast-isel independently from -O0. static cl::opt<cl::boolOrDefault> EnableFastISelOption("fast-isel", cl::Hidden, cl::desc("Enable the \"fast\" instruction selector")); // Enable or disable an experimental optimization to split GEPs // and run a special GVN pass which does not examine loads, in // an effort to factor out redundancy implicit in complex GEPs. static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden, cl::desc("Split GEPs and run no-load GVN")); LLVMTargetMachine::LLVMTargetMachine(const Target &T, const std::string &TargetTriple) : TargetMachine(T) { AsmInfo = T.createAsmInfo(TargetTriple); } // Set the default code model for the JIT for a generic target. // FIXME: Is small right here? or .is64Bit() ? Large : Small? void LLVMTargetMachine::setCodeModelForJIT() { setCodeModel(CodeModel::Small); } // Set the default code model for static compilation for a generic target. void LLVMTargetMachine::setCodeModelForStatic() { setCodeModel(CodeModel::Small); } bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM, formatted_raw_ostream &Out, CodeGenFileType FileType, CodeGenOpt::Level OptLevel, bool DisableVerify) { // Add common CodeGen passes. if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify)) return true; OwningPtr<MCContext> Context(new MCContext()); OwningPtr<MCStreamer> AsmStreamer; formatted_raw_ostream *LegacyOutput; switch (FileType) { default: return true; case CGFT_AssemblyFile: { const MCAsmInfo &MAI = *getMCAsmInfo(); MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, Out); AsmStreamer.reset(createAsmStreamer(*Context, Out, MAI, getTargetData()->isLittleEndian(), getVerboseAsm(), InstPrinter, /*codeemitter*/0)); // Set the AsmPrinter's "O" to the output file. LegacyOutput = &Out; break; } case CGFT_ObjectFile: { // Create the code emitter for the target if it exists. If not, .o file // emission fails. MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context); if (MCE == 0) return true; AsmStreamer.reset(createMachOStreamer(*Context, Out, MCE)); // Any output to the asmprinter's "O" stream is bad and needs to be fixed, // force it to come out stderr. // FIXME: this is horrible and leaks, eventually remove the raw_ostream from // asmprinter. LegacyOutput = new formatted_raw_ostream(errs()); break; } case CGFT_Null: // The Null output is intended for use for performance analysis and testing, // not real users. AsmStreamer.reset(createNullStreamer(*Context)); // Any output to the asmprinter's "O" stream is bad and needs to be fixed, // force it to come out stderr. // FIXME: this is horrible and leaks, eventually remove the raw_ostream from // asmprinter. LegacyOutput = new formatted_raw_ostream(errs()); break; } // Create the AsmPrinter, which takes ownership of Context and AsmStreamer // if successful. FunctionPass *Printer = getTarget().createAsmPrinter(*LegacyOutput, *this, *Context, *AsmStreamer, getMCAsmInfo()); if (Printer == 0) return true; // If successful, createAsmPrinter took ownership of AsmStreamer and Context. Context.take(); AsmStreamer.take(); PM.add(Printer); // Make sure the code model is set. setCodeModelForStatic(); PM.add(createGCInfoDeleter()); return false; } /// addPassesToEmitMachineCode - Add passes to the specified pass manager to /// get machine code emitted. This uses a JITCodeEmitter object to handle /// actually outputting the machine code and resolving things like the address /// of functions. This method should returns true if machine code emission is /// not supported. /// bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM, JITCodeEmitter &JCE, CodeGenOpt::Level OptLevel, bool DisableVerify) { // Make sure the code model is set. setCodeModelForJIT(); // Add common CodeGen passes. if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify)) return true; addCodeEmitter(PM, OptLevel, JCE); PM.add(createGCInfoDeleter()); return false; // success! } static void printNoVerify(PassManagerBase &PM, const char *Banner) { if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); } static void printAndVerify(PassManagerBase &PM, const char *Banner, bool allowDoubleDefs = false) { if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); if (VerifyMachineCode) PM.add(createMachineVerifierPass(allowDoubleDefs)); } /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both /// emitting to assembly files or machine code output. /// bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM, CodeGenOpt::Level OptLevel, bool DisableVerify) { // Standard LLVM-Level Passes. // Before running any passes, run the verifier to determine if the input // coming from the front-end and/or optimizer is valid. if (!DisableVerify) PM.add(createVerifierPass()); // Optionally, tun split-GEPs and no-load GVN. if (EnableSplitGEPGVN) { PM.add(createGEPSplitterPass()); PM.add(createGVNPass(/*NoLoads=*/true)); } // Run loop strength reduction before anything else. if (OptLevel != CodeGenOpt::None && !DisableLSR) { PM.add(createLoopStrengthReducePass(getTargetLowering())); if (PrintLSR) PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs())); } // Turn exception handling constructs into something the code generators can // handle. switch (getMCAsmInfo()->getExceptionHandlingType()) { case ExceptionHandling::SjLj: // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, // catch info can get misplaced when a selector ends up more than one block // removed from the parent invoke(s). This could happen when a landing // pad is shared by multiple invokes and is also a target of a normal // edge from elsewhere. PM.add(createSjLjEHPass(getTargetLowering())); PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None)); break; case ExceptionHandling::Dwarf: PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None)); break; case ExceptionHandling::None: PM.add(createLowerInvokePass(getTargetLowering())); break; } PM.add(createGCLoweringPass()); // Make sure that no unreachable blocks are instruction selected. PM.add(createUnreachableBlockEliminationPass()); if (OptLevel != CodeGenOpt::None && !DisableCGP) PM.add(createCodeGenPreparePass(getTargetLowering())); PM.add(createStackProtectorPass(getTargetLowering())); if (PrintISelInput) PM.add(createPrintFunctionPass("\n\n" "*** Final LLVM Code input to ISel ***\n", &dbgs())); // All passes which modify the LLVM IR are now complete; run the verifier // to ensure that the IR is valid. if (!DisableVerify) PM.add(createVerifierPass()); // Standard Lower-Level Passes. // Set up a MachineFunction for the rest of CodeGen to work on. PM.add(new MachineFunctionAnalysis(*this, OptLevel)); // Enable FastISel with -fast, but allow that to be overridden. if (EnableFastISelOption == cl::BOU_TRUE || (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE)) EnableFastISel = true; // Ask the target for an isel. if (addInstSelector(PM, OptLevel)) return true; // Print the instruction selected machine code... printAndVerify(PM, "After Instruction Selection", /* allowDoubleDefs= */ true); // Optimize PHIs before DCE: removing dead PHI cycles may make more // instructions dead. if (OptLevel != CodeGenOpt::None) PM.add(createOptimizePHIsPass()); // Delete dead machine instructions regardless of optimization level. PM.add(createDeadMachineInstructionElimPass()); printAndVerify(PM, "After codegen DCE pass", /* allowDoubleDefs= */ true); if (OptLevel != CodeGenOpt::None) { PM.add(createOptimizeExtsPass()); if (!DisableMachineLICM) PM.add(createMachineLICMPass()); if (EnableMachineCSE) PM.add(createMachineCSEPass()); if (!DisableMachineSink) PM.add(createMachineSinkingPass()); printAndVerify(PM, "After MachineLICM and MachineSinking", /* allowDoubleDefs= */ true); } // Pre-ra tail duplication. if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) { PM.add(createTailDuplicatePass(true)); printAndVerify(PM, "After Pre-RegAlloc TailDuplicate", /* allowDoubleDefs= */ true); } // Run pre-ra passes. if (addPreRegAlloc(PM, OptLevel)) printAndVerify(PM, "After PreRegAlloc passes", /* allowDoubleDefs= */ true); // Perform register allocation. PM.add(createRegisterAllocator()); printAndVerify(PM, "After Register Allocation"); // Perform stack slot coloring. if (OptLevel != CodeGenOpt::None && !DisableSSC) { // FIXME: Re-enable coloring with register when it's capable of adding // kill markers. PM.add(createStackSlotColoringPass(false)); printAndVerify(PM, "After StackSlotColoring"); } // Run post-ra passes. if (addPostRegAlloc(PM, OptLevel)) printAndVerify(PM, "After PostRegAlloc passes"); PM.add(createLowerSubregsPass()); printAndVerify(PM, "After LowerSubregs"); // Insert prolog/epilog code. Eliminate abstract frame index references... PM.add(createPrologEpilogCodeInserter()); printAndVerify(PM, "After PrologEpilogCodeInserter"); // Run pre-sched2 passes. if (addPreSched2(PM, OptLevel)) printAndVerify(PM, "After PreSched2 passes"); // Second pass scheduler. if (OptLevel != CodeGenOpt::None && !DisablePostRA) { PM.add(createPostRAScheduler(OptLevel)); printAndVerify(PM, "After PostRAScheduler"); } // Branch folding must be run after regalloc and prolog/epilog insertion. if (OptLevel != CodeGenOpt::None && !DisableBranchFold) { PM.add(createBranchFoldingPass(getEnableTailMergeDefault())); printNoVerify(PM, "After BranchFolding"); } // Tail duplication. if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) { PM.add(createTailDuplicatePass(false)); printNoVerify(PM, "After TailDuplicate"); } PM.add(createGCMachineCodeAnalysisPass()); if (PrintGCInfo) PM.add(createGCInfoPrinter(dbgs())); if (OptLevel != CodeGenOpt::None && !DisableCodePlace) { PM.add(createCodePlacementOptPass()); printNoVerify(PM, "After CodePlacementOpt"); } if (addPreEmitPass(PM, OptLevel)) printNoVerify(PM, "After PreEmit passes"); return false; }
wrmsr/lljvm
thirdparty/llvm/lib/CodeGen/LLVMTargetMachine.cpp
C++
mit
15,146
'use strict'; const path = require('path'); const webpack = require('webpack'); const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); module.exports = { bail : true, entry : path.join(__dirname, 'src/main/main.js'), target: 'electron-main', output: { path : path.join(__dirname, 'dist'), filename : 'main.js', publicPath : '/dist/', libraryTarget: 'commonjs2' }, resolve: { modules : ['node_modules'], extensions : ['.js'], descriptionFiles: ['package.json'] }, externals: { '7zip': '7zip' }, plugins: [ new webpack.NamedModulesPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }), new CaseSensitivePathsPlugin() ], node: { __dirname : false, __filename: false } };
my-dish/template-electron
template/webpack.main.config.js
JavaScript
mit
896
//分页插件 /** 2014-08-05 ch **/ (function($){ var ms = { init:function(obj,args){ return (function(){ ms.fillHtml(obj,args); ms.bindEvent(obj,args); })(); }, //填充html fillHtml:function(obj,args){ return (function(){ obj.empty(); //上一页 if(args.current > 1){ obj.append('<a href="javascript:;" class="prevPage">上一页</a>'); }else{ obj.remove('.prevPage'); obj.append('<span class="disabled">上一页</span>'); } //中间页码 if(args.current != 1 && args.current >= 4 && args.pageCount != 4){ obj.append('<a href="javascript:;" class="tcdNumber">'+1+'</a>'); } if(args.current-2 > 2 && args.current <= args.pageCount && args.pageCount > 5){ obj.append('<span>...</span>'); } var start = args.current -2,end = args.current+2; if((start > 1 && args.current < 4)||args.current == 1){ end++; } if(args.current > args.pageCount-4 && args.current >= args.pageCount){ start--; } for (;start <= end; start++) { if(start <= args.pageCount && start >= 1){ if(start != args.current){ obj.append('<a href="javascript:;" class="tcdNumber">'+ start +'</a>'); }else{ obj.append('<span class="current">'+ start +'</span>'); } } } if(args.current + 2 < args.pageCount - 1 && args.current >= 1 && args.pageCount > 5){ obj.append('<span>...</span>'); } if(args.current != args.pageCount && args.current < args.pageCount -2 && args.pageCount != 4){ obj.append('<a href="javascript:;" class="tcdNumber">'+args.pageCount+'</a>'); } //下一页 if(args.current < args.pageCount){ obj.append('<a href="javascript:;" class="nextPage">下一页</a>'); }else{ obj.remove('.nextPage'); obj.append('<span class="disabled">下一页</span>'); } })(); }, //绑定事件 bindEvent:function(obj,args){ return (function(){ obj.on("click","a.tcdNumber",function(){ var current = parseInt($(this).text()); ms.fillHtml(obj,{"current":current,"pageCount":args.pageCount}); if(typeof(args.backFn)=="function"){ args.backFn(current); } }); //上一页 obj.on("click","a.prevPage",function(){ var current = parseInt(obj.children("span.current").text()); ms.fillHtml(obj,{"current":current-1,"pageCount":args.pageCount}); if(typeof(args.backFn)=="function"){ args.backFn(current-1); } }); //下一页 obj.on("click","a.nextPage",function(){ var current = parseInt(obj.children("span.current").text()); ms.fillHtml(obj,{"current":current+1,"pageCount":args.pageCount}); if(typeof(args.backFn)=="function"){ args.backFn(current+1); } }); })(); } } $.fn.createPage = function(options){ var args = $.extend({ pageCount : 10, current : 1, backFn : function(){} },options); ms.init(this,args); } })(jQuery); //代码整理:懒人之家 www.lanrenzhijia.com
447491480/little-man
public/default/js/vendors/jquery.page/jquery.page.js
JavaScript
mit
3,004
module Shoulda module Matchers module ActionController # The `filter_param` matcher is used to test parameter filtering # configuration. Specifically, it asserts that the given parameter is # present in `config.filter_parameters`. # # class MyApplication < Rails::Application # config.filter_parameters << :secret_key # end # # # RSpec # describe ApplicationController do # it { should filter_param(:secret_key) } # end # # # Minitest (Shoulda) # class ApplicationControllerTest < ActionController::TestCase # should filter_param(:secret_key) # end # # @return [FilterParamMatcher] # def filter_param(key) FilterParamMatcher.new(key) end # @private class FilterParamMatcher def initialize(key) @key = key end def matches?(controller) filters_key? end def failure_message "Expected #{@key} to be filtered; filtered keys: #{filtered_keys.join(', ')}" end def failure_message_when_negated "Did not expect #{@key} to be filtered" end def description "filter #{@key}" end private def filters_key? filtered_keys.any? do |filter| case filter when Regexp filter =~ @key else filter == @key end end end def filtered_keys Rails.application.config.filter_parameters end end end end end
plribeiro3000/shoulda-matchers
lib/shoulda/matchers/action_controller/filter_param_matcher.rb
Ruby
mit
1,679
<!DOCTYPE HTML> <html> <head> <title>phaser.js - a new beginning</title> <?php require('js.php'); ?> </head> <body> <script type="text/javascript"> var game = new Phaser.Game(); var r = new Phaser.Rectangle(0,0,100,100); console.log(r); </script> </body> </html>
GoodBoyDigital/phaser
wip/examples/rect1.php
PHP
mit
276
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using TestExtensions; using TestGrainInterfaces; using UnitTests.GrainInterfaces; using Xunit; namespace DefaultCluster.Tests.General { /// <summary> /// Unit tests for grains implementing generic interfaces /// </summary> public class GenericGrainTests : HostedTestClusterEnsureDefaultStarted { private static int grainId = 0; public GenericGrainTests(DefaultClusterFixture fixture) : base(fixture) { } public TGrainInterface GetGrain<TGrainInterface>(long i) where TGrainInterface : IGrainWithIntegerKey { return this.GrainFactory.GetGrain<TGrainInterface>(i); } public TGrainInterface GetGrain<TGrainInterface>() where TGrainInterface : IGrainWithIntegerKey { return this.GrainFactory.GetGrain<TGrainInterface>(GetRandomGrainId()); } /// Can instantiate multiple concrete grain types that implement /// different specializations of the same generic interface [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceGetGrain() { var grainOfIntFloat1 = GetGrain<IGenericGrain<int, float>>(); var grainOfIntFloat2 = GetGrain<IGenericGrain<int, float>>(); var grainOfFloatString = GetGrain<IGenericGrain<float, string>>(); await grainOfIntFloat1.SetT(123); await grainOfIntFloat2.SetT(456); await grainOfFloatString.SetT(789.0f); var floatResult1 = await grainOfIntFloat1.MapT2U(); var floatResult2 = await grainOfIntFloat2.MapT2U(); var stringResult = await grainOfFloatString.MapT2U(); Assert.Equal(123f, floatResult1); Assert.Equal(456f, floatResult2); Assert.Equal("789", stringResult); } /// Multiple GetGrain requests with the same id return the same concrete grain [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceMultiplicity() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<IGenericGrain<int, float>>(grainId); await grainRef1.SetT(123); var grainRef2 = GetGrain<IGenericGrain<int, float>>(grainId); var floatResult = await grainRef2.MapT2U(); Assert.Equal(123f, floatResult); } /// Can instantiate generic grain specializations [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_SimpleGenericGrainGetGrain() { var grainOfFloat1 = GetGrain<ISimpleGenericGrain<float>>(); var grainOfFloat2 = GetGrain<ISimpleGenericGrain<float>>(); var grainOfString = GetGrain<ISimpleGenericGrain<string>>(); await grainOfFloat1.Set(1.2f); await grainOfFloat2.Set(3.4f); await grainOfString.Set("5.6"); // generic grain implementation does not change the set value: await grainOfFloat1.Transform(); await grainOfFloat2.Transform(); await grainOfString.Transform(); var floatResult1 = await grainOfFloat1.Get(); var floatResult2 = await grainOfFloat2.Get(); var stringResult = await grainOfString.Get(); Assert.Equal(1.2f, floatResult1); Assert.Equal(3.4f, floatResult2); Assert.Equal("5.6", stringResult); } /// Can instantiate grains that implement generic interfaces with generic type parameters [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_GenericInterfaceWithGenericParametersGetGrain() { var grain = GetGrain<ISimpleGenericGrain<List<float>>>(); var list = new List<float>(); list.Add(0.1f); await grain.Set(list); var result = await grain.Get(); Assert.Single(result); Assert.Equal(0.1f, result[0]); } /// Multiple GetGrain requests with the same id return the same generic grain specialization [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_SimpleGenericGrainMultiplicity() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<float>>(grainId); await grainRef1.Set(1.2f); await grainRef1.Transform(); // NOP for generic grain class var grainRef2 = GetGrain<ISimpleGenericGrain<float>>(grainId); var floatResult = await grainRef2.Get(); Assert.Equal(1.2f, floatResult); } /// If both a concrete implementation and a generic implementation of a /// generic interface exist, prefer the concrete implementation. [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterface() { var grainOfDouble1 = GetGrain<ISimpleGenericGrain<double>>(); var grainOfDouble2 = GetGrain<ISimpleGenericGrain<double>>(); await grainOfDouble1.Set(1.0); await grainOfDouble2.Set(2.0); // concrete implementation (SpecializedSimpleGenericGrain) doubles the set value: await grainOfDouble1.Transform(); await grainOfDouble2.Transform(); var result1 = await grainOfDouble1.Get(); var result2 = await grainOfDouble2.Get(); Assert.Equal(2.0, result1); Assert.Equal(4.0, result2); } /// Multiple GetGrain requests with the same id return the same concrete grain implementation [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterfaceMultiplicity() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<double>>(grainId); await grainRef1.Set(1.0); await grainRef1.Transform(); // SpecializedSimpleGenericGrain doubles the value for generic grain class // a second reference with the same id points to the same grain: var grainRef2 = GetGrain<ISimpleGenericGrain<double>>(grainId); await grainRef2.Transform(); var floatResult = await grainRef2.Get(); Assert.Equal(4.0f, floatResult); } /// Can instantiate concrete grains that implement multiple generic interfaces [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesGetGrain() { var grain1 = GetGrain<ISimpleGenericGrain<int>>(); var grain2 = GetGrain<ISimpleGenericGrain<int>>(); await grain1.Set(1); await grain2.Set(2); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10: await grain1.Transform(); await grain2.Transform(); var result1 = await grain1.Get(); var result2 = await grain2.Get(); Assert.Equal(10, result1); Assert.Equal(20, result2); } /// Multiple GetGrain requests with the same id and interface return the same concrete grain implementation [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity1() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId); await grainRef1.Set(1); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10: await grainRef1.Transform(); //A second reference to the interface will point to the same grain var grainRef2 = GetGrain<ISimpleGenericGrain<int>>(grainId); await grainRef2.Transform(); var floatResult = await grainRef2.Get(); Assert.Equal(100, floatResult); } /// Multiple GetGrain requests with the same id and different interfaces return the same concrete grain implementation [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity2() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId); await grainRef1.Set(1); await grainRef1.Transform(); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10: // A second reference to a different interface implemented by ConcreteGrainWith2GenericInterfaces // will reference the same grain: var grainRef2 = GetGrain<IGenericGrain<int, string>>(grainId); // ConcreteGrainWith2GenericInterfaces returns a string representation of the current value multiplied by 10: var floatResult = await grainRef2.MapT2U(); Assert.Equal("100", floatResult); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_UseGenericFactoryInsideGrain() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<string>>(grainId); await grainRef1.Set("JustString"); await grainRef1.CompareGrainReferences(grainRef1); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrain_GetGrain() { var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); await grain.GetA(); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrainControlFlow() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); await grain.SetA(a); await grain.SetB(b); Task<string> stringPromise = grain.GetAxB(); Assert.Equal(expected, stringPromise.Result); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public void Generic_SimpleGrainControlFlow_Blocking() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); // explicitly use .Wait() and .Result to make sure the client does not deadlock in these cases. grain.SetA(a).Wait(); grain.SetB(b).Wait(); Task<string> stringPromise = grain.GetAxB(); Assert.Equal(expected, stringPromise.Result); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrainDataFlow() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); var setAPromise = grain.SetA(a); var setBPromise = grain.SetB(b); var stringPromise = Task.WhenAll(setAPromise, setBPromise).ContinueWith((_) => grain.GetAxB()).Unwrap(); var x = await stringPromise; Assert.Equal(expected, x); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrain2_GetGrain() { var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); var g2 = this.GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++); var g3 = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++); await g1.GetA(); await g2.GetA(); await g3.GetA(); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrainGenericParameterWithMultipleArguments_GetGrain() { var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<Dictionary<int, int>>>(GetRandomGrainId()); await g1.GetA(); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrainControlFlow2_GetAB() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); var g2 = this.GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++); var g3 = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++); string r1 = await g1.GetAxB(a, b); string r2 = await g2.GetAxB(a, b); string r3 = await g3.GetAxB(a, b); Assert.Equal(expected, r1); Assert.Equal(expected, r2); Assert.Equal(expected, r3); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrainControlFlow3() { ISimpleGenericGrain2<int, float> g = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, float>>(grainId++); await g.SetA(3); await g.SetB(1.25f); Assert.Equal("3x1.25", await g.GetAxB()); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_BasicGrainControlFlow() { IBasicGenericGrain<int, float> g = this.GrainFactory.GetGrain<IBasicGenericGrain<int, float>>(0); await g.SetA(3); await g.SetB(1.25f); Assert.Equal("3x1.25", await g.GetAxB()); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GrainWithListFields() { string a = random.Next(100).ToString(CultureInfo.InvariantCulture); string b = random.Next(100).ToString(CultureInfo.InvariantCulture); var g1 = this.GrainFactory.GetGrain<IGrainWithListFields>(grainId++); var p1 = g1.AddItem(a); var p2 = g1.AddItem(b); await Task.WhenAll(p1, p2); var r1 = await g1.GetItems(); Assert.True( (a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved. string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1])); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_GrainWithListFields() { int a = random.Next(100); int b = random.Next(100); var g1 = this.GrainFactory.GetGrain<IGenericGrainWithListFields<int>>(grainId++); var p1 = g1.AddItem(a); var p2 = g1.AddItem(b); await Task.WhenAll(p1, p2); var r1 = await g1.GetItems(); Assert.True( (a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved. string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1])); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_GrainWithNoProperties_ControlFlow() { int a = random.Next(100); int b = random.Next(100); string expected = a + "x" + b; var g1 = this.GrainFactory.GetGrain<IGenericGrainWithNoProperties<int>>(grainId++); string r1 = await g1.GetAxB(a, b); Assert.Equal(expected, r1); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GrainWithNoProperties_ControlFlow() { int a = random.Next(100); int b = random.Next(100); string expected = a + "x" + b; long grainId = GetRandomGrainId(); var g1 = this.GrainFactory.GetGrain<IGrainWithNoProperties>(grainId); string r1 = await g1.GetAxB(a, b); Assert.Equal(expected, r1); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_ReaderWriterGrain1() { int a = random.Next(100); var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain1<int>>(grainId++); await g.SetValue(a); var res = await g.GetValue(); Assert.Equal(a, res); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_ReaderWriterGrain2() { int a = random.Next(100); string b = "bbbbb"; var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain2<int, string>>(grainId++); await g.SetValue1(a); await g.SetValue2(b); var r1 = await g.GetValue1(); Assert.Equal(a, r1); var r2 = await g.GetValue2(); Assert.Equal(b, r2); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_ReaderWriterGrain3() { int a = random.Next(100); string b = "bbbbb"; double c = 3.145; var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain3<int, string, double>>(grainId++); await g.SetValue1(a); await g.SetValue2(b); await g.SetValue3(c); var r1 = await g.GetValue1(); Assert.Equal(a, r1); var r2 = await g.GetValue2(); Assert.Equal(b, r2); var r3 = await g.GetValue3(); Assert.Equal(c, r3); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Non_Primitive_Type_Argument() { IEchoHubGrain<Guid, string> g1 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, string>>(1); IEchoHubGrain<Guid, int> g2 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, int>>(1); IEchoHubGrain<Guid, byte[]> g3 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, byte[]>>(1); Assert.NotEqual((GrainReference)g1, (GrainReference)g2); Assert.NotEqual((GrainReference)g1, (GrainReference)g3); Assert.NotEqual((GrainReference)g2, (GrainReference)g3); await g1.Foo(Guid.Empty, "", 1); await g2.Foo(Guid.Empty, 0, 2); await g3.Foo(Guid.Empty, new byte[] { }, 3); Assert.Equal(1, await g1.GetX()); Assert.Equal(2, await g2.GetX()); Assert.Equal(3m, await g3.GetX()); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_1() { const string msg1 = "Hello from EchoGenericChainGrain-1"; IEchoGenericChainGrain<string> g1 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g1.Echo(msg1); Assert.Equal(msg1, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_2() { const string msg2 = "Hello from EchoGenericChainGrain-2"; IEchoGenericChainGrain<string> g2 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g2.Echo2(msg2); Assert.Equal(msg2, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_3() { const string msg3 = "Hello from EchoGenericChainGrain-3"; IEchoGenericChainGrain<string> g3 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g3.Echo3(msg3); Assert.Equal(msg3, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_4() { const string msg4 = "Hello from EchoGenericChainGrain-4"; var g4 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g4.Echo4(msg4); Assert.Equal(msg4, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_5() { const string msg5 = "Hello from EchoGenericChainGrain-5"; var g5 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g5.Echo5(msg5); Assert.Equal(msg5, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_6() { const string msg6 = "Hello from EchoGenericChainGrain-6"; var g6 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g6.Echo6(msg6); Assert.Equal(msg6, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_1Argument_GenericCallOnly() { var grain = this.GrainFactory.GetGrain<IGeneric1Argument<string>>(Guid.NewGuid(), "UnitTests.Grains.Generic1ArgumentGrain"); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.Ping(s1); Assert.Equal(s1, s2); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_1Argument_NonGenericCallFirst() { var id = Guid.NewGuid(); var nonGenericFacet = this.GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain"); await Assert.ThrowsAsync<OrleansException>(async () => { try { await nonGenericFacet.Ping(); } catch (AggregateException exc) { throw exc.GetBaseException(); } }); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_1Argument_GenericCallFirst() { var id = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IGeneric1Argument<string>>(id, "UnitTests.Grains.Generic1ArgumentGrain"); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.Ping(s1); Assert.Equal(s1, s2); var nonGenericFacet = this.GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain"); await Assert.ThrowsAsync<OrleansException>(async () => { try { await nonGenericFacet.Ping(); } catch (AggregateException exc) { throw exc.GetBaseException(); } }); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task DifferentTypeArgsProduceIndependentActivations() { var grain1 = this.GrainFactory.GetGrain<IDbGrain<int>>(0); await grain1.SetValue(123); var grain2 = this.GrainFactory.GetGrain<IDbGrain<string>>(0); var v = await grain2.GetValue(); Assert.Null(v); } [Fact, TestCategory("BVT"), TestCategory("Generics"), TestCategory("Echo")] public async Task Generic_PingSelf() { var id = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.PingSelf(s1); Assert.Equal(s1, s2); } [Fact, TestCategory("BVT"), TestCategory("Generics"), TestCategory("Echo")] public async Task Generic_PingOther() { var id = Guid.NewGuid(); var targetId = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.PingOther(target, s1); Assert.Equal(s1, s2); } [Fact, TestCategory("BVT"), TestCategory("Generics"), TestCategory("Echo")] public async Task Generic_PingSelfThroughOther() { var id = Guid.NewGuid(); var targetId = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.PingSelfThroughOther(target, s1); Assert.Equal(s1, s2); } [Fact, TestCategory("BVT"), TestCategory("Generics"), TestCategory("ActivateDeactivate")] public async Task Generic_ScheduleDelayedPingAndDeactivate() { var id = Guid.NewGuid(); var targetId = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId); var s1 = Guid.NewGuid().ToString(); await grain.ScheduleDelayedPingToSelfAndDeactivate(target, s1, TimeSpan.FromSeconds(5)); await Task.Delay(TimeSpan.FromSeconds(6)); var s2 = await grain.GetLastValue(); Assert.Equal(s1, s2); } [Fact, TestCategory("BVT"), TestCategory("Generics"), TestCategory("Serialization")] public async Task SerializationTests_Generic_CircularReferenceTest() { var grainId = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<ICircularStateTestGrain>(primaryKey: grainId, keyExtension: grainId.ToString("N")); var c1 = await grain.GetState(); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_GrainWithTypeConstraints() { var grainId = Guid.NewGuid().ToString(); var grain = this.GrainFactory.GetGrain<IGenericGrainWithConstraints<List<int>, int, string>>(grainId); var result = await grain.GetCount(); Assert.Equal(0, result); await grain.Add(42); result = await grain.GetCount(); Assert.Equal(1, result); } [Fact, TestCategory("BVT"), TestCategory("Persistence")] public async Task Generic_GrainWithValueTypeState() { Guid id = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IValueTypeTestGrain>(id); var initial = await grain.GetStateData(); Assert.Equal(new ValueTypeTestData(0), initial); var expectedValue = new ValueTypeTestData(42); await grain.SetStateData(expectedValue); Assert.Equal(expectedValue, await grain.GetStateData()); } [Fact(Skip = "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")] public async Task Generic_CastToGenericInterfaceAfterActivation() { var grain = this.GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid()); await grain.DoSomething(); //activates original grain type here var castRef = grain.AsReference<ISomeGenericGrain<string>>(); var result = await castRef.Hello(); Assert.Equal("Hello!", result); } [Fact(Skip= "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")] public async Task Generic_CastToDifferentlyConcretizedGenericInterfaceBeforeActivation() { var grain = this.GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid()); var castRef = grain.AsReference<IIndependentlyConcretizedGenericGrain<string>>(); var result = await castRef.Hello(); Assert.Equal("Hello!", result); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public async Task Generic_CastToDifferentlyConcretizedInterfaceBeforeActivation() { var grain = this.GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid()); var castRef = grain.AsReference<IIndependentlyConcretizedGrain>(); var result = await castRef.Hello(); Assert.Equal("Hello!", result); } [Fact, TestCategory("BVT"), TestCategory("Cast"), TestCategory("Generics")] public async Task Generic_CastGenericInterfaceToNonGenericInterfaceBeforeActivation() { var grain = this.GrainFactory.GetGrain<IGenericCastableGrain<string>>(Guid.NewGuid()); var castRef = grain.AsReference<INonGenericCastGrain>(); var result = await castRef.Hello(); Assert.Equal("Hello!", result); } /// <summary> /// Tests that generic grains can have generic state and that the parameters to the Grain{TState} /// class do not have to match the parameters to the grain class itself. /// </summary> /// <returns></returns> [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainStateParameterMismatchTest() { var grain = this.GrainFactory.GetGrain<IGenericGrainWithGenericState<int, List<Guid>, string>>(Guid.NewGuid()); var result = await grain.GetStateType(); Assert.Equal(typeof(List<Guid>), result); } } namespace Generic.EdgeCases { using UnitTests.GrainInterfaces.Generic.EdgeCases; public class GenericEdgeCaseTests : HostedTestClusterEnsureDefaultStarted { public GenericEdgeCaseTests(DefaultClusterFixture fixture) : base(fixture) { } static async Task<Type[]> GetConcreteGenArgs(IBasicGrain @this) { var genArgTypeNames = await @this.ConcreteGenArgTypeNames(); return genArgTypeNames.Select(n => Type.GetType(n)) .ToArray(); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_PartiallySpecifyingGenericGrainFulfilsInterface() { var grain = this.GrainFactory.GetGrain<IGrainWithTwoGenArgs<string, int>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_GenericGrainCanReuseOwnGenArgRepeatedly() { //resolves correctly but can't be activated: too many gen args supplied for concrete class var grain = this.GrainFactory.GetGrain<IGrainReceivingRepeatedGenArgs<int, int>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable() { var grain = this.GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable_Activating() { var grain = this.GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid()); var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedRearrangedGenArgsResolved() { //again resolves to the correct generic type definition, but fails on activation as too many args //gen args aren't being properly inferred from matched concrete type var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsAmongstOthers<int, string, int>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(string), typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInTypeResolution() { var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(Enumerable.Empty<Type>()) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting() { var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting_Activating() { //Only errors on invocation: wrong arity again var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid()); var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RearrangedGenArgsOfCorrectArityAreResolved() { var grain = this.GrainFactory.GetGrain<IReceivingRearrangedGenArgs<int, long>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(long), typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable() { var grain = this.GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable_Activating() { var grain = this.GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid()); var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } //************************************************************************************************************** //************************************************************************************************************** //Below must be commented out, as supplying multiple fully-specified generic interfaces //to a class causes the codegen to fall over, stopping all other tests from working. //See new test here of the bit causing the issue - type info conflation: //UnitTests.CodeGeneration.CodeGeneratorTests.CodeGen_EncounteredFullySpecifiedInterfacesAreEncodedDistinctly() //public interface IFullySpecifiedGenericInterface<T> : IBasicGrain //{ } //public interface IDerivedFromMultipleSpecializationsOfSameInterface : IFullySpecifiedGenericInterface<int>, IFullySpecifiedGenericInterface<long> //{ } //public class GrainFulfillingMultipleSpecializationsOfSameInterfaceViaIntermediate : BasicGrain, IDerivedFromMultipleSpecializationsOfSameInterface //{ } //[Fact, TestCategory("Generics")] //public async Task CastingBetweenFullySpecifiedGenericInterfaces() //{ // //Is this legitimate? Solely in the realm of virtual grain interfaces - no special knowledge of implementation implicated, only of interface hierarchy // //codegen falling over: duplicate key when both specializations are matched to same concrete type // var grain = this.GrainFactory.GetGrain<IDerivedFromMultipleSpecializationsOfSameInterface>(Guid.NewGuid()); // await grain.Hello(); // var castRef = grain.AsReference<IFullySpecifiedGenericInterface<int>>(); // await castRef.Hello(); // var castRef2 = castRef.AsReference<IFullySpecifiedGenericInterface<long>>(); // await castRef2.Hello(); //} //******************************************************************************************************* [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs() { var grain = this.GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>(); var response = await grain.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs_Activating() { var grain = this.GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid()); var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>(); var response = await grain.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_GenArgsCanBeFurtherSpecialized() { var grain = this.GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_GenArgsCanBeFurtherSpecializedIntoArrays() { var grain = this.GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<long[]>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(long) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs() { var grain = this.GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>(); var response = await grain.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs_Activating() { var grain = this.GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid()); var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>(); var response = await grain.Hello(); Assert.Equal("Hello!", response); } } } }
ibondy/orleans
test/DefaultCluster.Tests/GenericGrainTests.cs
C#
mit
42,815
/* * * Copyright (C) 2003-2011, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmimage * * Author: Alexander Haderer * * Purpose: Implements PNG interface for plugable image formats * */ #include "dcmtk/config/osconfig.h" #ifdef WITH_LIBPNG #include "dcmtk/dcmdata/dctypes.h" #include "dcmtk/dcmimgle/diimage.h" #include "dcmtk/dcmimage/dipipng.h" #include "dcmtk/dcmdata/dcuid.h" /* for dcmtk version */ BEGIN_EXTERN_C #ifdef HAVE_LIBPNG_PNG_H #include <libpng/png.h> #else #include <png.h> #endif END_EXTERN_C DiPNGPlugin::DiPNGPlugin() : DiPluginFormat() , interlaceType(E_pngInterlaceAdam7) , metainfoType(E_pngFileMetainfo) , bitsPerSample(8) { } DiPNGPlugin::~DiPNGPlugin() { } int DiPNGPlugin::write( DiImage *image, FILE *stream, const unsigned long frame) const { volatile int result = 0; // gcc -W requires volatile here because of longjmp if ((image != NULL) && (stream != NULL)) { /* create bitmap with 8 or 16 bits per sample */ const int bit_depth = bitsPerSample; const void *data = image->getOutputData(frame, bit_depth /*bits*/, 0 /*planar*/); if (data != NULL) { png_struct *png_ptr = NULL; png_info *info_ptr = NULL; png_byte *pix_ptr = NULL; png_byte ** volatile row_ptr = NULL; volatile png_textp text_ptr = NULL; png_time ptime; const int width = image->getColumns(); const int height = image->getRows(); int color_type; int bpp; // bytesperpixel int row; // create png write struct png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL ); if( png_ptr == NULL ) { return 0; } // create png info struct info_ptr = png_create_info_struct( png_ptr ); if( info_ptr == NULL ) { png_destroy_write_struct( &png_ptr, NULL ); return 0; } // setjmp stuff for png lib if( setjmp(png_jmpbuf(png_ptr) ) ) { png_destroy_write_struct( &png_ptr, NULL ); if( row_ptr ) delete[] row_ptr; if( text_ptr ) delete[] text_ptr; return 0; } if( (image->getInternalColorModel() == EPI_Monochrome1) || (image->getInternalColorModel() == EPI_Monochrome2) ) { color_type = PNG_COLOR_TYPE_GRAY; bpp = bit_depth / 8; } else { color_type = PNG_COLOR_TYPE_RGB; bpp = 3 * bit_depth / 8; } int opt_interlace = 0; switch (interlaceType) { case E_pngInterlaceAdam7: opt_interlace = PNG_INTERLACE_ADAM7; break; case E_pngInterlaceNone: opt_interlace = PNG_INTERLACE_NONE; break; } // init png io structure png_init_io( png_ptr, stream ); // set write mode png_set_IHDR( png_ptr, info_ptr, width, height, bit_depth, color_type, opt_interlace, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); // set text & time if( metainfoType == E_pngFileMetainfo ) { text_ptr = new png_text[3]; if( text_ptr == NULL ) { png_destroy_write_struct( &png_ptr, NULL ); return result; } text_ptr[0].key = OFconst_cast(char *, "Title"); text_ptr[0].text = OFconst_cast(char *, "Converted DICOM Image"); text_ptr[0].compression = PNG_TEXT_COMPRESSION_NONE; text_ptr[1].key = OFconst_cast(char *, "Software"); text_ptr[1].text = OFconst_cast(char *, "OFFIS DCMTK"); text_ptr[1].compression = PNG_TEXT_COMPRESSION_NONE; text_ptr[2].key = OFconst_cast(char *, "Version"); text_ptr[2].text = OFconst_cast(char *, OFFIS_DCMTK_VERSION); text_ptr[2].compression = PNG_TEXT_COMPRESSION_NONE; #ifdef PNG_iTXt_SUPPORTED text_ptr[0].lang = NULL; text_ptr[1].lang = NULL; text_ptr[2].lang = NULL; #endif png_set_text( png_ptr, info_ptr, text_ptr, 3 ); png_convert_from_time_t( &ptime, time(NULL) ); png_set_tIME( png_ptr, info_ptr, &ptime ); } // write header png_write_info( png_ptr, info_ptr ); row_ptr = new png_bytep[height]; if( row_ptr == NULL ) { png_destroy_write_struct( &png_ptr, NULL ); if( text_ptr ) delete[] text_ptr; return result; } for( row=0, pix_ptr=OFstatic_cast(png_byte*, OFconst_cast(void*, data)); row<height; row++, pix_ptr+=width*bpp ) { row_ptr[row] = pix_ptr; } // swap bytes (if needed) if ( (bit_depth == 16) && (gLocalByteOrder != EBO_BigEndian) ) png_set_swap( png_ptr ); // write image png_write_image( png_ptr, row_ptr ); // write additional chunks png_write_end( png_ptr, info_ptr ); // finish png_destroy_write_struct( &png_ptr, NULL ); delete[] row_ptr; if( text_ptr ) delete[] text_ptr; result = 1; } } return result; } void DiPNGPlugin::setInterlaceType(DiPNGInterlace itype) { interlaceType = itype; } void DiPNGPlugin::setMetainfoType(DiPNGMetainfo minfo) { metainfoType = minfo; } void DiPNGPlugin::setBitsPerSample(const int bpp) { if( (bpp == 8) || (bpp == 16) ) bitsPerSample = bpp; } OFString DiPNGPlugin::getLibraryVersionString() { OFString versionStr = "LIBPNG, Version "; char cver[10]; png_uint_32 ver = png_access_version_number(); if( ver < 999999 ) { sprintf( cver, "%li.%li.%li", OFstatic_cast(long int, (ver/10000)%100), OFstatic_cast(long int, (ver/100)%100), OFstatic_cast(long int, ver%100) ); }else{ sprintf( cver, "unknown" ); } versionStr.append( cver ); return versionStr; } #else /* WITH_LIBPNG */ int dipipng_cc_dummy_to_keep_linker_from_moaning = 0; #endif
leonardorame/openpacs
dcmtk-3.6.1_20150629/dcmimage/libsrc/dipipng.cc
C++
mit
6,073
using System; using System.Runtime.CompilerServices; using CodeJam.Arithmetic; using CodeJam.PerfTests; using JetBrains.Annotations; using NUnit.Framework; using static CodeJam.PerfTests.CompetitionHelpers; // ReSharper disable once CheckNamespace namespace CodeJam { /// <summary> /// Proof test: <see cref="EnumHelper"/> methods are faster than their framework counterparts. /// </summary> [PublicAPI] [TestFixture(Category = PerfTestCategory + ": EnumHelper")] [CompetitionBurstMode] public class EnumHelperPerfTests { #region PerfTest helpers [Flags, PublicAPI] public enum F : byte { Zero = 0x0, A = 0x1, B = 0x2, C = 0x4, D = 0x8, // ReSharper disable once InconsistentNaming CD = C | D } private const string Fa = nameof(F.A); private const string Fx = "X"; #endregion private static readonly int Count = CompetitionRunHelpers.BurstModeLoopCount / 16; [Test] public void RunIsDefinedCase() => Competition.Run<IsDefinedCase>(); public class IsDefinedCase { [CompetitionBaseline] [GcAllocations(0)] public bool Test00IsDefined() { var a = false; for (var i = 0; i < Count; i++) a = EnumHelper.IsDefined(F.C | F.D); return a; } [CompetitionBenchmark(0.44, 1.38)] [GcAllocations(0)] public bool Test01IsDefinedUndefined() { var a = false; for (var i = 0; i < Count; i++) a = EnumHelper.IsDefined(F.B | F.C); return a; } [CompetitionBenchmark(20.99, 56.07)] [GcAllocations(29.31, 48.02, BinarySizeUnit.Kilobyte)] public bool Test02EnumIsDefined() { var a = false; for (var i = 0; i < Count; i++) a = Enum.IsDefined(typeof(F), F.C | F.D); return a; } [CompetitionBenchmark(14.57, 62.21)] [GcAllocations(29.31, 48.02, BinarySizeUnit.Kilobyte)] public bool Test03EnumIsDefinedUndefined() { var a = false; for (var i = 0; i < Count; i++) a = Enum.IsDefined(typeof(F), F.B | F.C); return a; } } [Test] public void RunTryParseCase() => Competition.Run<TryParseCase>(); public class TryParseCase { [CompetitionBaseline] [GcAllocations(0)] public F Test00TryParse() { var a = F.Zero; for (var i = 0; i < Count; i++) EnumHelper.TryParse(Fa, out a); return a; } [CompetitionBenchmark(3.80, 4.67)] [GcAllocations(160, BinarySizeUnit.Kilobyte)] public F Test02CheckViaEnumInfo() { var a = F.Zero; for (var i = 0; i < Count; i++) EnumHelper.IsDefined<F>(Fa); return a; } [CompetitionBenchmark(5.20, 11.34)] [GcAllocations(53.73, 88.02, BinarySizeUnit.Kilobyte)] public F Test01TryParseUndefined() { var a = F.Zero; for (var i = 0; i < Count; i++) EnumHelper.TryParse(Fx, out a); return a; } [CompetitionBenchmark(6.30, 18.75)] [GcAllocations(68.37, 112.02, BinarySizeUnit.Kilobyte)] public F Test02EnumTryParse() { var a = F.Zero; for (var i = 0; i < Count; i++) Enum.TryParse(Fa, out a); return a; } [CompetitionBenchmark(3.69, 8.37)] [GcAllocations(53.73, 88.03, BinarySizeUnit.Kilobyte)] public F Test03EnumTryParseUndefined() { var a = F.Zero; for (var i = 0; i < Count; i++) Enum.TryParse(Fx, out a); return a; } } [Test] public void RunIsFlagSetCase() => Competition.Run<IsFlagSetCase>(); public class IsFlagSetCase { [MethodImpl(MethodImplOptions.NoInlining)] private static bool IsFlagSet(F value, F flag) => (value & flag) == flag; private static readonly Func<F, F, bool> _isFlagSetEnumOp = OperatorsFactory.IsFlagSetOperator<F>(); private static readonly Func<int, int, bool> _isFlagSetIntOp = OperatorsFactory.IsFlagSetOperator<int>(); [CompetitionBaseline] [GcAllocations(0)] public bool Test00Baseline() { var a = false; for (var i = 0; i < Count; i++) a = IsFlagSet(F.CD, F.C); return a; } [CompetitionBenchmark(0.99, 1.85)] [GcAllocations(0)] public bool Test01IsFlagSet() { var a = false; for (var i = 0; i < Count; i++) a = F.CD.IsFlagSet(F.C); return a; } [CompetitionBenchmark(0.68, 1.65)] [GcAllocations(0)] public bool Test02IsFlagSetEnumOp() { var a = false; for (var i = 0; i < Count; i++) a = _isFlagSetEnumOp(F.CD, F.C); return a; } [CompetitionBenchmark(0.56, 1.24)] [GcAllocations(0)] public bool Test03IsFlagSetIntOp() { var a = false; for (var i = 0; i < Count; i++) a = _isFlagSetIntOp(8 | 4, 4); return a; } [CompetitionBenchmark(7.18, 20.77)] [GcAllocations(29.30, 48.02, BinarySizeUnit.Kilobyte)] public bool Test04EnumHasFlag() { var a = false; for (var i = 0; i < Count; i++) a = F.CD.HasFlag(F.C); return a; } } [Test] public void RunIsAnyFlagSetCase() => Competition.Run<IsAnyFlagSetCase>(); public class IsAnyFlagSetCase { [MethodImpl(MethodImplOptions.NoInlining)] private static bool IsAnyFlagSet(F value, F flag) => flag == 0 || (value & flag) != 0; private static readonly Func<F, F, bool> _isAnyFlagSetEnumOp = OperatorsFactory.IsAnyFlagSetOperator<F>(); private static readonly Func<int, int, bool> _isAnyFlagSetIntOp = OperatorsFactory.IsAnyFlagSetOperator<int>(); [CompetitionBaseline] [GcAllocations(0)] public bool Test00Baseline() { var a = false; for (var i = 0; i < Count; i++) a = IsAnyFlagSet(F.CD, F.B | F.C); return a; } [CompetitionBenchmark(0.86, 2.27)] [GcAllocations(0)] public bool Test01IsAnyFlagSet() { var a = false; for (var i = 0; i < Count; i++) a = F.CD.IsFlagSet(F.B | F.C); return a; } [CompetitionBenchmark(0.53, 1.22)] [GcAllocations(0)] public bool Test02IsAnyFlagSetEnumOp() { var a = false; for (var i = 0; i < Count; i++) a = _isAnyFlagSetEnumOp(F.CD, F.B | F.C); return a; } [CompetitionBenchmark(0.51, 1.95)] [GcAllocations(0)] public bool Test03IsAnyFlagSetIntOp() { var a = false; for (var i = 0; i < Count; i++) a = _isAnyFlagSetIntOp(8 | 4, 2 | 4); return a; } } [Test] public void RunSetFlagCase() => Competition.Run<SetFlagCase>(); public class SetFlagCase { [MethodImpl(MethodImplOptions.NoInlining)] private static F SetFlag(F value, F flag) => value | flag; private static readonly Func<F, F, F> _setFlagEnumOp = OperatorsFactory.SetFlagOperator<F>(); private static readonly Func<int, int, int> _setFlagIntOp = OperatorsFactory.SetFlagOperator<int>(); [CompetitionBaseline] [GcAllocations(0)] public F Test00Baseline() { var a = F.A; for (var i = 0; i < Count; i++) a = SetFlag(F.CD, F.B | F.C); return a; } [CompetitionBenchmark(0.59, 1.93)] [GcAllocations(0)] public F Test01SetFlag() { var a = F.A; for (var i = 0; i < Count; i++) a = F.CD.SetFlag(F.B | F.C); return a; } [CompetitionBenchmark(0.35, 1.16)] [GcAllocations(0)] public F Test02SetFlagEnumOp() { var a = F.A; for (var i = 0; i < Count; i++) a = _setFlagEnumOp(F.CD, F.B | F.C); return a; } [CompetitionBenchmark(0.34, 1.07)] [GcAllocations(0)] public int Test03SetFlagIntOp() { var a = 1; for (var i = 0; i < Count; i++) a = _setFlagIntOp(8 | 4, 2 | 4); return a; } } [Test] public void RunClearFlagCase() => Competition.Run<ClearFlagCase>(); public class ClearFlagCase { [MethodImpl(MethodImplOptions.NoInlining)] private static F ClearFlag(F value, F flag) => value & ~flag; private static readonly Func<F, F, F> _clearFlagEnumOp = OperatorsFactory.ClearFlagOperator<F>(); private static readonly Func<int, int, int> _clearFlagIntOp = OperatorsFactory.ClearFlagOperator<int>(); [CompetitionBaseline] [GcAllocations(0)] public F Test00Baseline() { var a = F.A; for (var i = 0; i < Count; i++) a = ClearFlag(F.CD, F.B | F.C); return a; } [CompetitionBenchmark(1.05, 2.16)] [GcAllocations(0)] public F Test01ClearFlag() { var a = F.A; for (var i = 0; i < Count; i++) a = F.CD.ClearFlag(F.B | F.C); return a; } [CompetitionBenchmark(0.76, 1.29)] [GcAllocations(0)] public F Test02ClearFlagEnumOp() { var a = F.A; for (var i = 0; i < Count; i++) a = _clearFlagEnumOp(F.CD, F.B | F.C); return a; } [CompetitionBenchmark(0.59, 1.00)] [GcAllocations(0)] public int Test03ClearFlagIntOp() { var a = 1; for (var i = 0; i < Count; i++) a = _clearFlagIntOp(8 | 4, 2 | 4); return a; } } } }
rsdn/CodeJam
PerfTests[WIP]/CodeJam.Main.Tests.Performance/Enums/EnumHelperPerfTests.cs
C#
mit
8,661
// Package event for AMI package event // Newchannel triggered when a new channel is created. type Newchannel struct { Privilege []string Channel string `AMI:"Channel"` ChannelState string `AMI:"Channelstate"` ChannelStateDesc string `AMI:"Channelstatedesc"` CallerIDNum string `AMI:"Calleridnum"` CallerIDName string `AMI:"Calleridname"` AccountCode string `AMI:"Accountcode"` UniqueID string `AMI:"Uniqueid"` Context string `AMI:"Context"` Extension string `AMI:"Exten"` } func init() { eventTrap["Newchannel"] = Newchannel{} }
bit4bit/gami
event/newchannel.go
GO
mit
601
var files = { "webgl": [ "webgl_animation_cloth", "webgl_animation_keyframes", "webgl_animation_skinning_blending", "webgl_animation_skinning_morph", "webgl_animation_multiple", "webgl_camera", "webgl_camera_array", "webgl_camera_cinematic", "webgl_camera_logarithmicdepthbuffer", "webgl_clipping", "webgl_clipping_advanced", "webgl_clipping_intersection", "webgl_clipping_stencil", "webgl_decals", "webgl_depth_texture", "webgl_effects_anaglyph", "webgl_effects_ascii", "webgl_effects_parallaxbarrier", "webgl_effects_peppersghost", "webgl_effects_stereo", "webgl_framebuffer_texture", "webgl_geometries", "webgl_geometries_parametric", "webgl_geometry_colors", "webgl_geometry_colors_lookuptable", "webgl_geometry_convex", "webgl_geometry_cube", "webgl_geometry_dynamic", "webgl_geometry_extrude_shapes", "webgl_geometry_extrude_shapes2", "webgl_geometry_extrude_splines", "webgl_geometry_hierarchy", "webgl_geometry_hierarchy2", "webgl_geometry_minecraft", "webgl_geometry_minecraft_ao", "webgl_geometry_normals", "webgl_geometry_nurbs", "webgl_geometry_shapes", "webgl_geometry_spline_editor", "webgl_geometry_teapot", "webgl_geometry_terrain", "webgl_geometry_terrain_fog", "webgl_geometry_terrain_raycast", "webgl_geometry_text", "webgl_geometry_text_shapes", "webgl_geometry_text_stroke", "webgl_helpers", "webgl_instancing_dynamic", "webgl_instancing_performance", "webgl_instancing_raycast", "webgl_instancing_scatter", "webgl_interactive_buffergeometry", "webgl_interactive_cubes", "webgl_interactive_cubes_gpu", "webgl_interactive_cubes_ortho", "webgl_interactive_lines", "webgl_interactive_points", "webgl_interactive_raycasting_points", "webgl_interactive_voxelpainter", "webgl_kinect", "webgl_layers", "webgl_lensflares", "webgl_lightprobe", "webgl_lightprobe_cubecamera", "webgl_lights_hemisphere", "webgl_lights_physical", "webgl_lights_pointlights", "webgl_lights_pointlights2", "webgl_lights_spotlight", "webgl_lights_spotlights", "webgl_lights_rectarealight", "webgl_lines_colors", "webgl_lines_dashed", "webgl_lines_fat", "webgl_lines_fat_wireframe", "webgl_lines_sphere", "webgl_loader_3ds", "webgl_loader_3mf", "webgl_loader_3mf_materials", "webgl_loader_amf", "webgl_loader_assimp", "webgl_loader_bvh", "webgl_loader_collada", "webgl_loader_collada_kinematics", "webgl_loader_collada_skinning", "webgl_loader_draco", "webgl_loader_fbx", "webgl_loader_fbx_nurbs", "webgl_loader_gcode", "webgl_loader_gltf", "webgl_loader_gltf_extensions", "webgl_loader_imagebitmap", "webgl_loader_json_claraio", "webgl_loader_kmz", "webgl_loader_ldraw", "webgl_loader_lwo", "webgl_loader_md2", "webgl_loader_md2_control", "webgl_loader_mdd", "webgl_loader_mmd", "webgl_loader_mmd_pose", "webgl_loader_mmd_audio", "webgl_loader_nrrd", "webgl_loader_obj", "webgl_loader_obj_mtl", "webgl_loader_obj2", "webgl_loader_obj2_options", "webgl_loader_pcd", "webgl_loader_pdb", "webgl_loader_ply", "webgl_loader_prwm", "webgl_loader_stl", "webgl_loader_svg", "webgl_loader_texture_basis", "webgl_loader_texture_dds", "webgl_loader_texture_exr", "webgl_loader_texture_hdr", "webgl_loader_texture_ktx", "webgl_loader_texture_pvrtc", "webgl_loader_texture_rgbm", "webgl_loader_texture_tga", "webgl_loader_ttf", "webgl_loader_vrm", "webgl_loader_vrml", "webgl_loader_vtk", "webgl_loader_x", "webgl_lod", "webgl_marchingcubes", "webgl_materials", "webgl_materials_blending", "webgl_materials_blending_custom", "webgl_materials_bumpmap", "webgl_materials_car", "webgl_materials_channels", "webgl_materials_cubemap", "webgl_materials_cubemap_balls_reflection", "webgl_materials_cubemap_balls_refraction", "webgl_materials_cubemap_dynamic", "webgl_materials_cubemap_refraction", "webgl_materials_cubemap_mipmaps", "webgl_materials_curvature", "webgl_materials_displacementmap", "webgl_materials_envmaps", "webgl_materials_envmaps_exr", "webgl_materials_envmaps_hdr", "webgl_materials_envmaps_parallax", "webgl_materials_grass", "webgl_materials_lightmap", "webgl_materials_matcap", "webgl_materials_normalmap", "webgl_materials_normalmap_object_space", "webgl_materials_parallaxmap", "webgl_materials_physical_clearcoat", "webgl_materials_physical_reflectivity", "webgl_materials_physical_sheen", "webgl_materials_physical_transparency", "webgl_materials_shaders_fresnel", "webgl_materials_standard", "webgl_materials_texture_anisotropy", "webgl_materials_texture_canvas", "webgl_materials_texture_filters", "webgl_materials_texture_manualmipmap", "webgl_materials_texture_partialupdate", "webgl_materials_texture_rotation", "webgl_materials_translucency", "webgl_materials_variations_basic", "webgl_materials_variations_lambert", "webgl_materials_variations_phong", "webgl_materials_variations_standard", "webgl_materials_variations_physical", "webgl_materials_variations_toon", "webgl_materials_video", "webgl_materials_video_webcam", "webgl_materials_wireframe", "webgl_math_obb", "webgl_math_orientation_transform", "webgl_mirror", "webgl_modifier_simplifier", "webgl_modifier_subdivision", "webgl_modifier_tessellation", "webgl_morphtargets", "webgl_morphtargets_horse", "webgl_morphtargets_sphere", "webgl_multiple_canvases_circle", "webgl_multiple_canvases_complex", "webgl_multiple_canvases_grid", "webgl_multiple_elements", "webgl_multiple_elements_text", "webgl_multiple_renderers", "webgl_multiple_scenes_comparison", "webgl_multiple_views", "webgl_nearestneighbour", "webgl_panorama_cube", "webgl_panorama_dualfisheye", "webgl_panorama_equirectangular", "webgl_performance", "webgl_performance_doublesided", "webgl_performance_static", "webgl_points_billboards", "webgl_points_dynamic", "webgl_points_sprites", "webgl_points_waves", "webgl_raycast_sprite", "webgl_raycast_texture", "webgl_read_float_buffer", "webgl_refraction", "webgl_rtt", "webgl_sandbox", "webgl_shader", "webgl_shader_lava", "webgl_shader2", "webgl_shaders_ocean", "webgl_shaders_ocean2", "webgl_shaders_sky", "webgl_shaders_tonemapping", "webgl_shaders_vector", "webgl_shading_physical", "webgl_shadow_contact", "webgl_shadowmap", "webgl_shadowmap_performance", "webgl_shadowmap_pointlight", "webgl_shadowmap_viewer", "webgl_shadowmap_vsm", "webgl_shadowmesh", "webgl_skinning_simple", "webgl_sprites", "webgl_test_memory", "webgl_test_memory2", "webgl_tonemapping", "webgl_trails", "webgl_video_panorama_equirectangular", "webgl_water", "webgl_water_flowmap" ], "webgl / nodes": [ "webgl_loader_nodes", "webgl_materials_compile", "webgl_materials_envmaps_hdr_nodes", "webgl_materials_envmaps_pmrem_nodes", "webgl_materials_nodes", "webgl_mirror_nodes", "webgl_performance_nodes", "webgl_postprocessing_nodes", "webgl_postprocessing_nodes_pass", "webgl_sprites_nodes", ], "webgl / postprocessing": [ "webgl_postprocessing", "webgl_postprocessing_advanced", "webgl_postprocessing_afterimage", "webgl_postprocessing_backgrounds", "webgl_postprocessing_crossfade", "webgl_postprocessing_dof", "webgl_postprocessing_dof2", "webgl_postprocessing_fxaa", "webgl_postprocessing_glitch", "webgl_postprocessing_godrays", "webgl_postprocessing_rgb_halftone", "webgl_postprocessing_masking", "webgl_postprocessing_ssaa", "webgl_postprocessing_ssaa_unbiased", "webgl_postprocessing_outline", "webgl_postprocessing_pixel", "webgl_postprocessing_procedural", "webgl_postprocessing_sao", "webgl_postprocessing_smaa", "webgl_postprocessing_sobel", "webgl_postprocessing_ssao", "webgl_postprocessing_taa", "webgl_postprocessing_unreal_bloom", "webgl_postprocessing_unreal_bloom_selective" ], "webgl / advanced": [ "webgl_buffergeometry", "webgl_buffergeometry_compression", "webgl_buffergeometry_constructed_from_geometry", "webgl_buffergeometry_custom_attributes_particles", "webgl_buffergeometry_drawrange", "webgl_buffergeometry_indexed", "webgl_buffergeometry_instancing", "webgl_buffergeometry_instancing_billboards", "webgl_buffergeometry_instancing_interleaved", "webgl_buffergeometry_lines", "webgl_buffergeometry_lines_indexed", "webgl_buffergeometry_morphtargets", "webgl_buffergeometry_points", "webgl_buffergeometry_points_interleaved", "webgl_buffergeometry_rawshader", "webgl_buffergeometry_selective_draw", "webgl_buffergeometry_uint", "webgl_custom_attributes", "webgl_custom_attributes_lines", "webgl_custom_attributes_points", "webgl_custom_attributes_points2", "webgl_custom_attributes_points3", "webgl_fire", "webgl_gpgpu_birds", "webgl_gpgpu_water", "webgl_gpgpu_protoplanet", "webgl_instancing_modified", "webgl_lightningstrike", "webgl_materials_modified", "webgl_raymarching_reflect", "webgl_shadowmap_csm", "webgl_shadowmap_pcss", "webgl_simple_gi", "webgl_tiled_forward", "webgl_worker_offscreencanvas" ], "webgl2": [ "webgl2_materials_texture2darray", "webgl2_materials_texture3d", "webgl2_multisampled_renderbuffers", "webgl2_sandbox" ], "webaudio": [ "webaudio_orientation", "webaudio_sandbox", "webaudio_timing", "webaudio_visualizer" ], "webxr": [ "webxr_ar_cones", "webxr_ar_hittest", "webxr_ar_paint", "webxr_vr_ballshooter", "webxr_vr_cubes", "webxr_vr_dragging", "webxr_vr_lorenzattractor", "webxr_vr_panorama", "webxr_vr_panorama_depth", "webxr_vr_paint", "webxr_vr_rollercoaster", "webxr_vr_sandbox", "webxr_vr_sculpt", "webxr_vr_video" ], "physics": [ "physics_ammo_break", "physics_ammo_cloth", "physics_ammo_rope", "physics_ammo_terrain", "physics_ammo_volume", "physics_cannon_instancing" ], "misc": [ "misc_animation_authoring", "misc_animation_groups", "misc_animation_keys", "misc_boxselection", "misc_controls_deviceorientation", "misc_controls_drag", "misc_controls_fly", "misc_controls_map", "misc_controls_orbit", "misc_controls_pointerlock", "misc_controls_trackball", "misc_controls_transform", "misc_exporter_collada", "misc_exporter_draco", "misc_exporter_gltf", "misc_exporter_obj", "misc_exporter_ply", "misc_exporter_stl", "misc_lookat", ], "css2d": [ "css2d_label" ], "css3d": [ "css3d_molecules", "css3d_orthographic", "css3d_panorama", "css3d_panorama_deviceorientation", "css3d_periodictable", "css3d_sandbox", "css3d_sprites", "css3d_youtube" ], "svg": [ "svg_lines", "svg_sandbox" ], "tests": [ "webgl_furnace_test", "webgl_pmrem_test", "misc_uv_tests" ] };
easz/rt_geometry
playground/js/three.js-r115/examples/files.js
JavaScript
mit
10,825
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "c-interface/c-interface.h" ConsoleMethod(GuiPopUpMenuCtrl, add, void, 4, 5, "( entryText , entryID [ , entryScheme ] ) Use the add method to add a new entry with text entryText, ID entryID, and using the scheme entryScheme.\n" "@param entryText Text to display in menu entry.\n" "@param entryID ID to assign to entry. This value may be 1 or greater.\n" "@param entryScheme An integer value representing the ID of an optional color scheme to be used for this entry.\n" "@return No return value.\n" "@sa addScheme, clear") { if (argc > 4) object->addEntry(argv[2], dAtoi(argv[3]), dAtoi(argv[4])); else object->addEntry(argv[2], dAtoi(argv[3]), 0); } ConsoleMethod(GuiPopUpMenuCtrl, addScheme, void, 6, 6, "( entryScheme , fontColor , fontColorHL , fontColorSEL ) Use the addScheme method to create a new color scheme or to modify an existing one.\n" "An integer color vector contains three integer values, each between 0 and 255 and is organized in this order: 'R G B'.\n" "@param entryScheme An integer value representing the ID of the scheme, between 1 and inf.\n" "@param fontColor A vector containing an integer representation of the menu entry's normal color.\n" "@param fontColorHL A vector containing an integer representation of the menu entry's highlighted color.\n" "@param fontColorSEL A vector containing an integer representation of the menu entry's selected color.\n" "@return No return value.\n" "@sa add") { ColorI fontColor, fontColorHL, fontColorSEL; U32 r, g, b; char buf[64]; dStrcpy(buf, argv[3]); char* temp = dStrtok(buf, " \0"); r = temp ? dAtoi(temp) : 0; temp = dStrtok(NULL, " \0"); g = temp ? dAtoi(temp) : 0; temp = dStrtok(NULL, " \0"); b = temp ? dAtoi(temp) : 0; fontColor.set(r, g, b); dStrcpy(buf, argv[4]); temp = dStrtok(buf, " \0"); r = temp ? dAtoi(temp) : 0; temp = dStrtok(NULL, " \0"); g = temp ? dAtoi(temp) : 0; temp = dStrtok(NULL, " \0"); b = temp ? dAtoi(temp) : 0; fontColorHL.set(r, g, b); dStrcpy(buf, argv[5]); temp = dStrtok(buf, " \0"); r = temp ? dAtoi(temp) : 0; temp = dStrtok(NULL, " \0"); g = temp ? dAtoi(temp) : 0; temp = dStrtok(NULL, " \0"); b = temp ? dAtoi(temp) : 0; fontColorSEL.set(r, g, b); object->addScheme(dAtoi(argv[2]), fontColor, fontColorHL, fontColorSEL); } ConsoleMethod(GuiPopUpMenuCtrl, setText, void, 3, 3, "( text ) Use the setText method to change the text displayed in the menu bar.\n" "Pass the NULL string to clear the menu bar text.\n" "@param text New text to display in the menu bar.\n" "@return No return value.\n" "@sa getText, replaceText") { object->setText(argv[2]); } ConsoleMethod(GuiPopUpMenuCtrl, getText, const char*, 2, 2, "() Use the getText method to get the text currently displayed in the menu bar.\n" "@return Returns the text in the menu bar or NULL if no text is present.\n" "@sa getSelected, setText") { return object->getText(); } ConsoleMethod(GuiPopUpMenuCtrl, clear, void, 2, 2, "() Use the clear method to remove all entries and schemes from the menu.\n" "@return No return value.\n" "@sa add, addScheme") { object->clear(); } ConsoleMethod(GuiPopUpMenuCtrl, sort, void, 2, 2, "() Use the sort method to sort the menu in ascending order.\n" "This is a lexicographic sort, so number (1,2,3,...) will come before letters (a,b,c,...)\n" "@return No return value.") { object->sort(); } // DAW: Added to sort the entries by ID ConsoleMethod(GuiPopUpMenuCtrl, sortID, void, 2, 2, "() Sort the list by ID.\n" "@return No return value.") { object->sortID(); } ConsoleMethod(GuiPopUpMenuCtrl, forceOnAction, void, 2, 2, "() Use the forceOnAction method to force the onAction callback to be triggered.\n" "@return No return value.\n" "@sa forceClose, onAction (GUIControl callback)") { object->onAction(); } ConsoleMethod(GuiPopUpMenuCtrl, forceClose, void, 2, 2, "() Use the forceClose method to force the menu to close.\n" "This is useful for making menus that fold up after a short delay when the mouse leaves the menu area.\n" "@return No return value.\n" "@sa forceOnAction") { object->closePopUp(); } ConsoleMethod(GuiPopUpMenuCtrl, getSelected, S32, 2, 2, "() Use the getSelected method to get the ID of the last selected entry.\n" "@return Returns the ID of the currently selected entry, or 0 meaning no menu was selected after the last menu open.") { return object->getSelected(); } ConsoleMethod(GuiPopUpMenuCtrl, setSelected, void, 3, 4, "(int id, [scriptCallback=true]) Set the object status as selected\n" "@param id The object's ID.\n" "@param scriptCallback Flag whether to notify\n" "@return No return value.") { if (argc > 3) object->setSelected(dAtoi(argv[2]), dAtob(argv[3])); else object->setSelected(dAtoi(argv[2])); } ConsoleMethod(GuiPopUpMenuCtrl, setFirstSelected, void, 2, 2, "() \n" "@return No return value.") { object->setFirstSelected(); } ConsoleMethod(GuiPopUpMenuCtrl, setNoneSelected, void, 2, 2, "() Deselects all popup menu controls\n" "@return No return value.") { object->setNoneSelected(); } ConsoleMethod(GuiPopUpMenuCtrl, getTextById, const char*, 3, 3, "( ID ) Use the getTextById method to get the text value for the menu item represented by ID.\n" "@param ID An integer value representing the ID of a menu item.\n" "@return Returns a string containing the menu item corresponding to ID, or a NULL string if no menu item has the specified ID.\n" "@sa add, getText") { return(object->getTextById(dAtoi(argv[2]))); } ConsoleMethod(GuiPopUpMenuCtrl, setEnumContent, void, 4, 4, "(string class, string enum)" "This fills the popup with a classrep's field enumeration type info.\n\n" "More of a helper function than anything. If console access to the field list is added, " "at least for the enumerated types, then this should go away.." "@param className The class name associated with this enum content.\n" "@param enumName The name of the enumerated entry to add to the menu. This value must match an enum string as exposed by the engine for the class. The menu item will have the same text as the enum string name, and the ID will be equal to the enumerated entries value.\n" "@return No return value") { AbstractClassRep * classRep = AbstractClassRep::getClassList(); // walk the class list to get our class while (classRep) { if (!dStricmp(classRep->getClassName(), argv[2])) break; classRep = classRep->getNextClass(); } // get it? if (!classRep) { Con::warnf(ConsoleLogEntry::General, "failed to locate class rep for '%s'", argv[2]); return; } // walk the fields to check for this one (findField checks StringTableEntry ptrs...) U32 i; for (i = 0; i < (U32)classRep->mFieldList.size(); i++) if (!dStricmp(classRep->mFieldList[i].pFieldname, argv[3])) break; // found it? if (i == classRep->mFieldList.size()) { Con::warnf(ConsoleLogEntry::General, "failed to locate field '%s' for class '%s'", argv[3], argv[2]); return; } const AbstractClassRep::Field & field = classRep->mFieldList[i]; // check the type if (field.type != TypeEnum) { Con::warnf(ConsoleLogEntry::General, "field '%s' is not an enumeration for class '%s'", argv[3], argv[2]); return; } AssertFatal(field.table, avar("enumeration '%s' for class '%s' with NULL ", argv[3], argv[2])); // fill it for (i = 0; i < (U32)field.table->size; i++) object->addEntry(field.table->table[i].label, field.table->table[i].index); } //------------------------------------------------------------------------------ ConsoleMethod(GuiPopUpMenuCtrl, findText, S32, 3, 3, "( text ) Use the findText method to locate the string text in the list of menu items. It will return the ID of the first entry found.\n" "@param text A string containing the text to search for.\n" "@return Returns an integer value representing the ID of the menu item, or -1 if the text was not found.") { return(object->findText(argv[2])); } //------------------------------------------------------------------------------ ConsoleMethod(GuiPopUpMenuCtrl, size, S32, 2, 2, "() Get the size of the menu, ie the number of entries in it.\n" "@return The numbers of entries as an integer.") { return(object->getNumEntries()); } //------------------------------------------------------------------------------ ConsoleMethod(GuiPopUpMenuCtrl, replaceText, void, 3, 3, "( enable ) Use the replaceText method to enable the updating of the menu bar text when a menu item is selected.\n" "This does not prevent changing the menu bar text with setText.\n" "@param enable A boolean value enabling or disabling the automatic updating of the menu bar text when a selection is made.\n" "@return No return value.\n" "@sa getText, setText") { object->replaceText(dAtoi(argv[2])); } extern "C"{ DLL_PUBLIC GuiPopupTextListCtrl* GuiPopupTextListCtrlCreateInstance() { return new GuiPopupTextListCtrl(); } DLL_PUBLIC GuiPopUpMenuCtrl* GuiPopUpMenuCtrlCreateInstance() { return new GuiPopUpMenuCtrl(); } DLL_PUBLIC void GuiPopUpMenuCtrlAdd(GuiPopUpMenuCtrl* ctrl, const char* entryText, S32 entryID, S32 entryScheme) { ctrl->addEntry(entryText, entryID, entryScheme); } DLL_PUBLIC void GuiPopUpMenuCtrlAddScheme(GuiPopUpMenuCtrl* ctrl, S32 entryScheme, CInterface::ColorParam fontColor, CInterface::ColorParam fontColorHL, CInterface::ColorParam fontColorSEL) { ctrl->addScheme(entryScheme, fontColor, fontColorHL, fontColorSEL); } DLL_PUBLIC void GuiPopUpMenuCtrlSetText(GuiPopUpMenuCtrl* ctrl, const char* text) { ctrl->setText(text); } DLL_PUBLIC const char* GuiPopUpMenuCtrlGetText(GuiPopUpMenuCtrl* ctrl) { return ctrl->getText(); } DLL_PUBLIC void GuiPopUpMenuCtrlClear(GuiPopUpMenuCtrl* ctrl) { ctrl->clear(); } DLL_PUBLIC void GuiPopUpMenuCtrlSort(GuiPopUpMenuCtrl* ctrl) { ctrl->sort(); } DLL_PUBLIC void GuiPopUpMenuCtrlSortID(GuiPopUpMenuCtrl* ctrl) { ctrl->sortID(); } DLL_PUBLIC void GuiPopUpMenuCtrlForceOnAction(GuiPopUpMenuCtrl* ctrl) { ctrl->onAction(); } DLL_PUBLIC void GuiPopUpMenuCtrlClosePopUp(GuiPopUpMenuCtrl* ctrl) { ctrl->closePopUp(); } DLL_PUBLIC S32 GuiPopUpMenuCtrlGetSelected(GuiPopUpMenuCtrl* ctrl) { return ctrl->getSelected(); } DLL_PUBLIC void GuiPopUpMenuCtrlSetSelected(GuiPopUpMenuCtrl* ctrl, S32 id, bool scriptCallback) { ctrl->setSelected(id, scriptCallback); } DLL_PUBLIC void GuiPopUpMenuCtrlSetFirstSelected(GuiPopUpMenuCtrl* ctrl) { ctrl->setFirstSelected(); } DLL_PUBLIC void GuiPopUpMenuCtrlSetNoneSelected(GuiPopUpMenuCtrl* ctrl) { ctrl->setNoneSelected(); } DLL_PUBLIC const char* GuiPopUpMenuCtrlGetTextById(GuiPopUpMenuCtrl* ctrl, S32 ID) { return ctrl->getTextById(ID); } DLL_PUBLIC void GuiPopUpMenuCtrlSetEnumContent(GuiPopUpMenuCtrl* ctrl, const char* contentClass, const char* contentEnum) { AbstractClassRep * classRep = AbstractClassRep::getClassList(); // walk the class list to get our class while (classRep) { if (!dStricmp(classRep->getClassName(), contentClass)) break; classRep = classRep->getNextClass(); } // get it? if (!classRep) { Con::warnf(ConsoleLogEntry::General, "failed to locate class rep for '%s'", contentClass); return; } // walk the fields to check for this one (findField checks StringTableEntry ptrs...) U32 i; for (i = 0; i < (U32)classRep->mFieldList.size(); i++) if (!dStricmp(classRep->mFieldList[i].pFieldname, contentEnum)) break; // found it? if (i == classRep->mFieldList.size()) { Con::warnf(ConsoleLogEntry::General, "failed to locate field '%s' for class '%s'", contentEnum, contentClass); return; } const AbstractClassRep::Field & field = classRep->mFieldList[i]; // check the type if (field.type != TypeEnum) { Con::warnf(ConsoleLogEntry::General, "field '%s' is not an enumeration for class '%s'", contentEnum, contentClass); return; } AssertFatal(field.table, avar("enumeration '%s' for class '%s' with NULL ", contentEnum, contentClass)); // fill it for (i = 0; i < (U32)field.table->size; i++) ctrl->addEntry(field.table->table[i].label, field.table->table[i].index); } DLL_PUBLIC S32 GuiPopUpMenuCtrlFindText(GuiPopUpMenuCtrl* ctrl, const char* text) { return ctrl->findText(text); } DLL_PUBLIC S32 GuiPopUpMenuCtrlSize(GuiPopUpMenuCtrl* ctrl) { return ctrl->getNumEntries(); } DLL_PUBLIC void GuiPopUpMenuCtrlReplaceText(GuiPopUpMenuCtrl* ctrl, bool enable) { ctrl->replaceText(enable); } }
andr3wmac/Torque6
src/gui/guiPopUpCtrl_Binding.h
C
mit
14,265
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * IgbFiletoMatrix_Plugin.cc * * Written by: * Karli Gillette * Department of Bioengineering * University of Utah * */ #include <Core/IEPlugin/IgbFileToMatrix_Plugin.h> #include <Core/Datatypes/DenseMatrix.h> #include <Core/Datatypes/MatrixTypeConversions.h> #include <Core/Utils/Legacy/StringUtil.h> #include <Core/Logging/LoggerInterface.h> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <iostream> #include <fstream> #include <sstream> using namespace SCIRun; using namespace SCIRun::Core; using namespace SCIRun::Core::Logging; using namespace SCIRun::Core::Datatypes; MatrixHandle SCIRun::IgbFileMatrix_reader(LoggerHandle pr, const char *filename) { std::string line; std::vector<std::string> strs; int x_size=0; int t_size=0; int count=0; std::ifstream myfile(filename); if (myfile.is_open()) { for (int i=0; i<5; i++) { std::getline(myfile,line); boost::split(strs,line,boost::is_any_of(":, ")); size_t sz = line.size(); for (int p=0;p<sz;p++) { if (boost::iequals(strs[p], "x")) { x_size=atoi(strs[p+1].c_str()); count += 1; } if (boost::iequals(strs[p], "t")) { t_size=atoi(strs[p+1].c_str()); count += 1; } if (count == 2) break; } } myfile.close(); } std::streamoff length=0; std::streamsize numbyts=0; std::ifstream is; is.open(filename, std::ios::in | std::ios::binary ); if (is.is_open()) { // get length of file: is.seekg(0, std::ios::end); length = is.tellg(); is.seekg(1024, std::ios::beg); length -= 1024; std::vector<float> vec; vec.resize(length); is.read((char*)&vec[0],length); if (!is) { numbyts = is.gcount(); std::cerr << "Error reading binary data. Number of bytes read: " << numbyts << std::endl; } is.close(); auto result(boost::make_shared<DenseMatrix>(x_size,t_size)); for(size_t p=0;p<t_size;p++ ) { for(size_t pp=0;pp<x_size;pp++ ) { (*result)(pp, p) = vec[(p*x_size)+pp]; } } return result; } return nullptr; }
jcollfont/SCIRun
src/Core/IEPlugin/IgbFileToMatrix_Plugin.cc
C++
mit
3,458
import java.io.*; public class FileOutputter { private BufferedWriter m_writer; private String m_filename; public static void print( String filename, String text ) { try { File file = new File( filename ); BufferedWriter bw = new BufferedWriter( new FileWriter( file.getAbsoluteFile(), true ) ); bw.write( text ); bw.close(); } catch( IOException e ) { e.printStackTrace(); } } public static void println( String filename, String text ) { print( filename, text + "\n" ); } public FileOutputter() { m_filename = "default.txt"; } public FileOutputter( String filename ) { m_filename = filename; } public void print( String text ) { openFile( m_filename ); try { m_writer.write( text ); } catch( IOException e ) { e.printStackTrace(); } closeFile(); } public void println( String text ) { print( text + "\n" ); } private void openFile( String filename ) { try { File file = new File( filename ); m_writer = new BufferedWriter( new FileWriter( file.getAbsoluteFile(), true ) ); } catch( IOException e ) { e.printStackTrace(); } } private void closeFile() { try { m_writer.close(); } catch( IOException e ) { e.printStackTrace(); } } }
Rachels-Courses/Course-Common-Files
STUDENT_REFERENCE/EXAMPLE_CODE/File IO/Java/OutputCSV/FileOutputter.java
Java
mit
1,760
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" HREF="favicon.ico"> <title>vis.js - Groups documentation.</title> <!-- Bootstrap core CSS --> <link href="../css/bootstrap.css" rel="stylesheet"> <!-- Tipue vendor css --> <link href="../css/tipuesearch.css" rel="stylesheet"> <link href="../css/style.css" rel="stylesheet"> <link href="../css/prettify.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="../js/toggleTable.js"></script> <script type="text/javascript" src="../js/googleAnalytics.js"></script> <script type="text/javascript" src="../js/prettify/prettify.js"></script> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <script src="../js/smooth-scroll.min.js"></script> <script language="JavaScript"> smoothScroll.init(); </script> <style> </style> </head> <body onload="prettyPrint();"> <div class="navbar-wrapper"> <div class="container"> <nav class="navbar navbar-inverse navbar-static-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand hidden-sm" href="./index.html">vis.js</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="http://www.visjs.org/index.html#modules">Modules</a></li> <li><a href="http://www.visjs.org/blog.html">Blog</a></li> <li><a href="http://www.visjs.org/index.html#download_install">Download</a></li> <li><a href="http://www.visjs.org/showcase/index.html">Showcase</a></li> <li><a href="http://www.visjs.org/index.html#contribute">Contribute</a></li> <li><a href="http://www.visjs.org/featureRequests.html">Feature requests</a></li> <li><a href="http://www.visjs.org/index.html#licenses">License</a></li> </ul> <form class="navbar-form navbar-right" role="search"> <input name="q" id="tipue_search_input" autocomplete="off" type="text" class="form-control" placeholder="Enter keywords"> <button type="button" class="btn btn-default" onclick="vis.initSiteSearch(true);">Go!</button> </form> <div id="search-results-wrapper" class="panel panel-default"> <div class="panel-body"> <div id="tipue_search_content"></div> </div> </div> <div id="keyword-info" class="panel panel-success"> <div class="panel-body"> Found <span id="keyword-count"></span> results. Click <a id="keyword-jumper-button" href="">here</a> to jump to the first keyword occurence! </div> </div> </div> </div> </nav> </div> </div> <a href="https://github.com/almende/vis" class="hidden-xs hidden-sm hidden-md"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> <div class="container full"> <h1>Network - groups</h1> <p>Handles the group styling.</p> <h3>Options</h3> <p>The options for the canvas have to be contained in an object titled 'groups'.</p> <p>Click on the options shown to show how these options are supposed to be used.</p> <ul class="nav nav-tabs"> <li role="presentation" class="active" onclick="toggleTab(this)"><a href="#">options hidden</a></li> <li role="presentation" onclick="toggleTab(this);" targetNode="fullOptions"><a href="#">options shown</a></li> </ul> <br> <pre class="prettyprint lang-js options hidden" id="fullOptions"> var options = { groups:{ useDefaultGroups: true, myGroupId:{ /*node options*/ } } } network.setOptions(options); </pre> <p>All of the individual options are explained here:</p> <table class="options"> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> <tr> <td>useDefaultGroups</td> <td>Boolean</td> <td><code>true</code></td> <td>If your nodes have groups defined that are not in the Groups module, the module loops over the groups it does have, allocating one for each unknown group. When all are used, it goes back to the first group. By setting this to false, the default groups will not be used in this cycle. </td> </tr> <tr> <td>group*</td> <td>Object</td> <td><code></code></td> <td> You can add multiple groups containing styling information that applies to a certain subset of groups. All options described in the <a href="./nodes.html">nodes module</a> that make sense can be used here (you're not going to set the same id or x,y position for a group of nodes). Example: <pre class="prettyprint lang-js options"> var nodes = [ {id:1, group:'myGroup', label:"I'm in a custom group called 'myGroup'!"} ] var options = { groups: { myGroup: {color:{background:'red'}, borderWidth:3} } } </pre> *) the option is not called group, as shown by the example but can by any custom id, except for 'useDefaultGroups'. </td> </tr> </table> </div> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="../js/jquery.min.js"></script> <script src="../js/bootstrap.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="../js/ie10-viewport-bug-workaround.js"></script> <!-- jquery extensions --> <script src="../js/jquery.highlight.js"></script> <script src="../js/jquery.url.min.js"></script> <!-- Tipue vendor js --> <script src="../js/tipuesearch.config.js"></script> <script src="../js/tipuesearch.js"></script> <!-- controller --> <script src="../js/main.js"></script>
jucapoco/baseSiteGanttChart
node_modules/vis/docs/network/groups.html
HTML
mit
7,813
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ WebInspector.AuditRules.IPAddressRegexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; WebInspector.AuditRules.CacheableResponseCodes = { 200: true, 203: true, 206: true, 300: true, 301: true, 410: true, 304: true // Underlying request is cacheable } /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {Array.<!WebInspector.resourceTypes>} types * @param {boolean} needFullResources * @return {(Object.<string, !Array.<!WebInspector.NetworkRequest>>|Object.<string, !Array.<string>>)} */ WebInspector.AuditRules.getDomainToResourcesMap = function(requests, types, needFullResources) { var domainToResourcesMap = {}; for (var i = 0, size = requests.length; i < size; ++i) { var request = requests[i]; if (types && types.indexOf(request.type) === -1) continue; var parsedURL = request.url.asParsedURL(); if (!parsedURL) continue; var domain = parsedURL.host; var domainResources = domainToResourcesMap[domain]; if (domainResources === undefined) { domainResources = []; domainToResourcesMap[domain] = domainResources; } domainResources.push(needFullResources ? request : request.url); } return domainToResourcesMap; } /** * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.GzipRule = function() { WebInspector.AuditRule.call(this, "network-gzip", "Enable gzip compression"); } WebInspector.AuditRules.GzipRule.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { var totalSavings = 0; var compressedSize = 0; var candidateSize = 0; var summary = result.addChild("", true); for (var i = 0, length = requests.length; i < length; ++i) { var request = requests[i]; if (request.cached || request.statusCode === 304) continue; // Do not test cached resources. if (this._shouldCompress(request)) { var size = request.resourceSize; candidateSize += size; if (this._isCompressed(request)) { compressedSize += size; continue; } var savings = 2 * size / 3; totalSavings += savings; summary.addFormatted("%r could save ~%s", request.url, Number.bytesToString(savings)); result.violationCount++; } } if (!totalSavings) return callback(null); summary.value = String.sprintf("Compressing the following resources with gzip could reduce their transfer size by about two thirds (~%s):", Number.bytesToString(totalSavings)); callback(result); }, _isCompressed: function(request) { var encodingHeader = request.responseHeaderValue("Content-Encoding"); if (!encodingHeader) return false; return /\b(?:gzip|deflate)\b/.test(encodingHeader); }, _shouldCompress: function(request) { return request.type.isTextType() && request.parsedURL.host && request.resourceSize !== undefined && request.resourceSize > 150; }, __proto__: WebInspector.AuditRule.prototype } /** * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.CombineExternalResourcesRule = function(id, name, type, resourceTypeName, allowedPerDomain) { WebInspector.AuditRule.call(this, id, name); this._type = type; this._resourceTypeName = resourceTypeName; this._allowedPerDomain = allowedPerDomain; } WebInspector.AuditRules.CombineExternalResourcesRule.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, [this._type], false); var penalizedResourceCount = 0; // TODO: refactor according to the chosen i18n approach var summary = result.addChild("", true); for (var domain in domainToResourcesMap) { var domainResources = domainToResourcesMap[domain]; var extraResourceCount = domainResources.length - this._allowedPerDomain; if (extraResourceCount <= 0) continue; penalizedResourceCount += extraResourceCount - 1; summary.addChild(String.sprintf("%d %s resources served from %s.", domainResources.length, this._resourceTypeName, WebInspector.AuditRuleResult.resourceDomain(domain))); result.violationCount += domainResources.length; } if (!penalizedResourceCount) return callback(null); summary.value = "There are multiple resources served from same domain. Consider combining them into as few files as possible."; callback(result); }, __proto__: WebInspector.AuditRule.prototype } /** * @constructor * @extends {WebInspector.AuditRules.CombineExternalResourcesRule} */ WebInspector.AuditRules.CombineJsResourcesRule = function(allowedPerDomain) { WebInspector.AuditRules.CombineExternalResourcesRule.call(this, "page-externaljs", "Combine external JavaScript", WebInspector.resourceTypes.Script, "JavaScript", allowedPerDomain); } WebInspector.AuditRules.CombineJsResourcesRule.prototype = { __proto__: WebInspector.AuditRules.CombineExternalResourcesRule.prototype } /** * @constructor * @extends {WebInspector.AuditRules.CombineExternalResourcesRule} */ WebInspector.AuditRules.CombineCssResourcesRule = function(allowedPerDomain) { WebInspector.AuditRules.CombineExternalResourcesRule.call(this, "page-externalcss", "Combine external CSS", WebInspector.resourceTypes.Stylesheet, "CSS", allowedPerDomain); } WebInspector.AuditRules.CombineCssResourcesRule.prototype = { __proto__: WebInspector.AuditRules.CombineExternalResourcesRule.prototype } /** * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.MinimizeDnsLookupsRule = function(hostCountThreshold) { WebInspector.AuditRule.call(this, "network-minimizelookups", "Minimize DNS lookups"); this._hostCountThreshold = hostCountThreshold; } WebInspector.AuditRules.MinimizeDnsLookupsRule.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { var summary = result.addChild(""); var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, null, false); for (var domain in domainToResourcesMap) { if (domainToResourcesMap[domain].length > 1) continue; var parsedURL = domain.asParsedURL(); if (!parsedURL) continue; if (!parsedURL.host.search(WebInspector.AuditRules.IPAddressRegexp)) continue; // an IP address summary.addSnippet(domain); result.violationCount++; } if (!summary.children || summary.children.length <= this._hostCountThreshold) return callback(null); summary.value = "The following domains only serve one resource each. If possible, avoid the extra DNS lookups by serving these resources from existing domains."; callback(result); }, __proto__: WebInspector.AuditRule.prototype } /** * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.ParallelizeDownloadRule = function(optimalHostnameCount, minRequestThreshold, minBalanceThreshold) { WebInspector.AuditRule.call(this, "network-parallelizehosts", "Parallelize downloads across hostnames"); this._optimalHostnameCount = optimalHostnameCount; this._minRequestThreshold = minRequestThreshold; this._minBalanceThreshold = minBalanceThreshold; } WebInspector.AuditRules.ParallelizeDownloadRule.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { function hostSorter(a, b) { var aCount = domainToResourcesMap[a].length; var bCount = domainToResourcesMap[b].length; return (aCount < bCount) ? 1 : (aCount == bCount) ? 0 : -1; } var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap( requests, [WebInspector.resourceTypes.Stylesheet, WebInspector.resourceTypes.Image], true); var hosts = []; for (var url in domainToResourcesMap) hosts.push(url); if (!hosts.length) return callback(null); // no hosts (local file or something) hosts.sort(hostSorter); var optimalHostnameCount = this._optimalHostnameCount; if (hosts.length > optimalHostnameCount) hosts.splice(optimalHostnameCount); var busiestHostResourceCount = domainToResourcesMap[hosts[0]].length; var requestCountAboveThreshold = busiestHostResourceCount - this._minRequestThreshold; if (requestCountAboveThreshold <= 0) return callback(null); var avgResourcesPerHost = 0; for (var i = 0, size = hosts.length; i < size; ++i) avgResourcesPerHost += domainToResourcesMap[hosts[i]].length; // Assume optimal parallelization. avgResourcesPerHost /= optimalHostnameCount; avgResourcesPerHost = Math.max(avgResourcesPerHost, 1); var pctAboveAvg = (requestCountAboveThreshold / avgResourcesPerHost) - 1.0; var minBalanceThreshold = this._minBalanceThreshold; if (pctAboveAvg < minBalanceThreshold) return callback(null); var requestsOnBusiestHost = domainToResourcesMap[hosts[0]]; var entry = result.addChild(String.sprintf("This page makes %d parallelizable requests to %s. Increase download parallelization by distributing the following requests across multiple hostnames.", busiestHostResourceCount, hosts[0]), true); for (var i = 0; i < requestsOnBusiestHost.length; ++i) entry.addURL(requestsOnBusiestHost[i].url); result.violationCount = requestsOnBusiestHost.length; callback(result); }, __proto__: WebInspector.AuditRule.prototype } /** * The reported CSS rule size is incorrect (parsed != original in WebKit), * so use percentages instead, which gives a better approximation. * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.UnusedCssRule = function() { WebInspector.AuditRule.call(this, "page-unusedcss", "Remove unused CSS rules"); } WebInspector.AuditRules.UnusedCssRule.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { var self = this; function evalCallback(styleSheets) { if (progress.isCanceled()) return; if (!styleSheets.length) return callback(null); var selectors = []; var testedSelectors = {}; for (var i = 0; i < styleSheets.length; ++i) { var styleSheet = styleSheets[i]; for (var curRule = 0; curRule < styleSheet.rules.length; ++curRule) { var selectorText = styleSheet.rules[curRule].selectorText; if (testedSelectors[selectorText]) continue; selectors.push(selectorText); testedSelectors[selectorText] = 1; } } function selectorsCallback(callback, styleSheets, testedSelectors, foundSelectors) { if (progress.isCanceled()) return; var inlineBlockOrdinal = 0; var totalStylesheetSize = 0; var totalUnusedStylesheetSize = 0; var summary; for (var i = 0; i < styleSheets.length; ++i) { var styleSheet = styleSheets[i]; var unusedRules = []; for (var curRule = 0; curRule < styleSheet.rules.length; ++curRule) { var rule = styleSheet.rules[curRule]; if (!testedSelectors[rule.selectorText] || foundSelectors[rule.selectorText]) continue; unusedRules.push(rule.selectorText); } totalStylesheetSize += styleSheet.rules.length; totalUnusedStylesheetSize += unusedRules.length; if (!unusedRules.length) continue; var resource = WebInspector.resourceForURL(styleSheet.sourceURL); var isInlineBlock = resource && resource.request && resource.request.type == WebInspector.resourceTypes.Document; var url = !isInlineBlock ? WebInspector.AuditRuleResult.linkifyDisplayName(styleSheet.sourceURL) : String.sprintf("Inline block #%d", ++inlineBlockOrdinal); var pctUnused = Math.round(100 * unusedRules.length / styleSheet.rules.length); if (!summary) summary = result.addChild("", true); var entry = summary.addFormatted("%s: %d% is not used by the current page.", url, pctUnused); for (var j = 0; j < unusedRules.length; ++j) entry.addSnippet(unusedRules[j]); result.violationCount += unusedRules.length; } if (!totalUnusedStylesheetSize) return callback(null); var totalUnusedPercent = Math.round(100 * totalUnusedStylesheetSize / totalStylesheetSize); summary.value = String.sprintf("%s rules (%d%) of CSS not used by the current page.", totalUnusedStylesheetSize, totalUnusedPercent); callback(result); } var foundSelectors = {}; function queryCallback(boundSelectorsCallback, selector, styleSheets, testedSelectors, nodeId) { if (nodeId) foundSelectors[selector] = true; if (boundSelectorsCallback) boundSelectorsCallback(foundSelectors); } function documentLoaded(selectors, document) { var pseudoSelectorRegexp = /::?(?:[\w-]+)(?:\(.*?\))?/g; for (var i = 0; i < selectors.length; ++i) { if (progress.isCanceled()) return; var effectiveSelector = selectors[i].replace(pseudoSelectorRegexp, ""); WebInspector.domAgent.querySelector(document.id, effectiveSelector, queryCallback.bind(null, i === selectors.length - 1 ? selectorsCallback.bind(null, callback, styleSheets, testedSelectors) : null, selectors[i], styleSheets, testedSelectors)); } } WebInspector.domAgent.requestDocument(documentLoaded.bind(null, selectors)); } function styleSheetCallback(styleSheets, sourceURL, continuation, styleSheet) { if (progress.isCanceled()) return; if (styleSheet) { styleSheet.sourceURL = sourceURL; styleSheets.push(styleSheet); } if (continuation) continuation(styleSheets); } function allStylesCallback(error, styleSheetInfos) { if (progress.isCanceled()) return; if (error || !styleSheetInfos || !styleSheetInfos.length) return evalCallback([]); var styleSheets = []; for (var i = 0; i < styleSheetInfos.length; ++i) { var info = styleSheetInfos[i]; WebInspector.CSSStyleSheet.createForId(info.styleSheetId, styleSheetCallback.bind(null, styleSheets, info.sourceURL, i == styleSheetInfos.length - 1 ? evalCallback : null)); } } CSSAgent.getAllStyleSheets(allStylesCallback); }, __proto__: WebInspector.AuditRule.prototype } /** * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.CacheControlRule = function(id, name) { WebInspector.AuditRule.call(this, id, name); } WebInspector.AuditRules.CacheControlRule.MillisPerMonth = 1000 * 60 * 60 * 24 * 30; WebInspector.AuditRules.CacheControlRule.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { var cacheableAndNonCacheableResources = this._cacheableAndNonCacheableResources(requests); if (cacheableAndNonCacheableResources[0].length) this.runChecks(cacheableAndNonCacheableResources[0], result); this.handleNonCacheableResources(cacheableAndNonCacheableResources[1], result); callback(result); }, handleNonCacheableResources: function(requests, result) { }, _cacheableAndNonCacheableResources: function(requests) { var processedResources = [[], []]; for (var i = 0; i < requests.length; ++i) { var request = requests[i]; if (!this.isCacheableResource(request)) continue; if (this._isExplicitlyNonCacheable(request)) processedResources[1].push(request); else processedResources[0].push(request); } return processedResources; }, execCheck: function(messageText, requestCheckFunction, requests, result) { var requestCount = requests.length; var urls = []; for (var i = 0; i < requestCount; ++i) { if (requestCheckFunction.call(this, requests[i])) urls.push(requests[i].url); } if (urls.length) { var entry = result.addChild(messageText, true); entry.addURLs(urls); result.violationCount += urls.length; } }, freshnessLifetimeGreaterThan: function(request, timeMs) { var dateHeader = this.responseHeader(request, "Date"); if (!dateHeader) return false; var dateHeaderMs = Date.parse(dateHeader); if (isNaN(dateHeaderMs)) return false; var freshnessLifetimeMs; var maxAgeMatch = this.responseHeaderMatch(request, "Cache-Control", "max-age=(\\d+)"); if (maxAgeMatch) freshnessLifetimeMs = (maxAgeMatch[1]) ? 1000 * maxAgeMatch[1] : 0; else { var expiresHeader = this.responseHeader(request, "Expires"); if (expiresHeader) { var expDate = Date.parse(expiresHeader); if (!isNaN(expDate)) freshnessLifetimeMs = expDate - dateHeaderMs; } } return (isNaN(freshnessLifetimeMs)) ? false : freshnessLifetimeMs > timeMs; }, responseHeader: function(request, header) { return request.responseHeaderValue(header); }, hasResponseHeader: function(request, header) { return request.responseHeaderValue(header) !== undefined; }, isCompressible: function(request) { return request.type.isTextType(); }, isPubliclyCacheable: function(request) { if (this._isExplicitlyNonCacheable(request)) return false; if (this.responseHeaderMatch(request, "Cache-Control", "public")) return true; return request.url.indexOf("?") == -1 && !this.responseHeaderMatch(request, "Cache-Control", "private"); }, responseHeaderMatch: function(request, header, regexp) { return request.responseHeaderValue(header) ? request.responseHeaderValue(header).match(new RegExp(regexp, "im")) : undefined; }, hasExplicitExpiration: function(request) { return this.hasResponseHeader(request, "Date") && (this.hasResponseHeader(request, "Expires") || this.responseHeaderMatch(request, "Cache-Control", "max-age")); }, _isExplicitlyNonCacheable: function(request) { var hasExplicitExp = this.hasExplicitExpiration(request); return this.responseHeaderMatch(request, "Cache-Control", "(no-cache|no-store|must-revalidate)") || this.responseHeaderMatch(request, "Pragma", "no-cache") || (hasExplicitExp && !this.freshnessLifetimeGreaterThan(request, 0)) || (!hasExplicitExp && request.url && request.url.indexOf("?") >= 0) || (!hasExplicitExp && !this.isCacheableResource(request)); }, isCacheableResource: function(request) { return request.statusCode !== undefined && WebInspector.AuditRules.CacheableResponseCodes[request.statusCode]; }, __proto__: WebInspector.AuditRule.prototype } /** * @constructor * @extends {WebInspector.AuditRules.CacheControlRule} */ WebInspector.AuditRules.BrowserCacheControlRule = function() { WebInspector.AuditRules.CacheControlRule.call(this, "http-browsercache", "Leverage browser caching"); } WebInspector.AuditRules.BrowserCacheControlRule.prototype = { handleNonCacheableResources: function(requests, result) { if (requests.length) { var entry = result.addChild("The following resources are explicitly non-cacheable. Consider making them cacheable if possible:", true); result.violationCount += requests.length; for (var i = 0; i < requests.length; ++i) entry.addURL(requests[i].url); } }, runChecks: function(requests, result, callback) { this.execCheck("The following resources are missing a cache expiration. Resources that do not specify an expiration may not be cached by browsers:", this._missingExpirationCheck, requests, result); this.execCheck("The following resources specify a \"Vary\" header that disables caching in most versions of Internet Explorer:", this._varyCheck, requests, result); this.execCheck("The following cacheable resources have a short freshness lifetime:", this._oneMonthExpirationCheck, requests, result); // Unable to implement the favicon check due to the WebKit limitations. this.execCheck("To further improve cache hit rate, specify an expiration one year in the future for the following cacheable resources:", this._oneYearExpirationCheck, requests, result); }, _missingExpirationCheck: function(request) { return this.isCacheableResource(request) && !this.hasResponseHeader(request, "Set-Cookie") && !this.hasExplicitExpiration(request); }, _varyCheck: function(request) { var varyHeader = this.responseHeader(request, "Vary"); if (varyHeader) { varyHeader = varyHeader.replace(/User-Agent/gi, ""); varyHeader = varyHeader.replace(/Accept-Encoding/gi, ""); varyHeader = varyHeader.replace(/[, ]*/g, ""); } return varyHeader && varyHeader.length && this.isCacheableResource(request) && this.freshnessLifetimeGreaterThan(request, 0); }, _oneMonthExpirationCheck: function(request) { return this.isCacheableResource(request) && !this.hasResponseHeader(request, "Set-Cookie") && !this.freshnessLifetimeGreaterThan(request, WebInspector.AuditRules.CacheControlRule.MillisPerMonth) && this.freshnessLifetimeGreaterThan(request, 0); }, _oneYearExpirationCheck: function(request) { return this.isCacheableResource(request) && !this.hasResponseHeader(request, "Set-Cookie") && !this.freshnessLifetimeGreaterThan(request, 11 * WebInspector.AuditRules.CacheControlRule.MillisPerMonth) && this.freshnessLifetimeGreaterThan(request, WebInspector.AuditRules.CacheControlRule.MillisPerMonth); }, __proto__: WebInspector.AuditRules.CacheControlRule.prototype } /** * @constructor * @extends {WebInspector.AuditRules.CacheControlRule} */ WebInspector.AuditRules.ProxyCacheControlRule = function() { WebInspector.AuditRules.CacheControlRule.call(this, "http-proxycache", "Leverage proxy caching"); } WebInspector.AuditRules.ProxyCacheControlRule.prototype = { runChecks: function(requests, result, callback) { this.execCheck("Resources with a \"?\" in the URL are not cached by most proxy caching servers:", this._questionMarkCheck, requests, result); this.execCheck("Consider adding a \"Cache-Control: public\" header to the following resources:", this._publicCachingCheck, requests, result); this.execCheck("The following publicly cacheable resources contain a Set-Cookie header. This security vulnerability can cause cookies to be shared by multiple users.", this._setCookieCacheableCheck, requests, result); }, _questionMarkCheck: function(request) { return request.url.indexOf("?") >= 0 && !this.hasResponseHeader(request, "Set-Cookie") && this.isPubliclyCacheable(request); }, _publicCachingCheck: function(request) { return this.isCacheableResource(request) && !this.isCompressible(request) && !this.responseHeaderMatch(request, "Cache-Control", "public") && !this.hasResponseHeader(request, "Set-Cookie"); }, _setCookieCacheableCheck: function(request) { return this.hasResponseHeader(request, "Set-Cookie") && this.isPubliclyCacheable(request); }, __proto__: WebInspector.AuditRules.CacheControlRule.prototype } /** * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.ImageDimensionsRule = function() { WebInspector.AuditRule.call(this, "page-imagedims", "Specify image dimensions"); } WebInspector.AuditRules.ImageDimensionsRule.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { var urlToNoDimensionCount = {}; function doneCallback() { for (var url in urlToNoDimensionCount) { var entry = entry || result.addChild("A width and height should be specified for all images in order to speed up page display. The following image(s) are missing a width and/or height:", true); var format = "%r"; if (urlToNoDimensionCount[url] > 1) format += " (%d uses)"; entry.addFormatted(format, url, urlToNoDimensionCount[url]); result.violationCount++; } callback(entry ? result : null); } function imageStylesReady(imageId, styles, isLastStyle, computedStyle) { if (progress.isCanceled()) return; const node = WebInspector.domAgent.nodeForId(imageId); var src = node.getAttribute("src"); if (!src.asParsedURL()) { for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) { if (frameOwnerCandidate.baseURL) { var completeSrc = WebInspector.ParsedURL.completeURL(frameOwnerCandidate.baseURL, src); break; } } } if (completeSrc) src = completeSrc; if (computedStyle.getPropertyValue("position") === "absolute") { if (isLastStyle) doneCallback(); return; } if (styles.attributesStyle) { var widthFound = !!styles.attributesStyle.getLiveProperty("width"); var heightFound = !!styles.attributesStyle.getLiveProperty("height"); } var inlineStyle = styles.inlineStyle; if (inlineStyle) { if (inlineStyle.getPropertyValue("width") !== "") widthFound = true; if (inlineStyle.getPropertyValue("height") !== "") heightFound = true; } for (var i = styles.matchedCSSRules.length - 1; i >= 0 && !(widthFound && heightFound); --i) { var style = styles.matchedCSSRules[i].style; if (style.getPropertyValue("width") !== "") widthFound = true; if (style.getPropertyValue("height") !== "") heightFound = true; } if (!widthFound || !heightFound) { if (src in urlToNoDimensionCount) ++urlToNoDimensionCount[src]; else urlToNoDimensionCount[src] = 1; } if (isLastStyle) doneCallback(); } function getStyles(nodeIds) { if (progress.isCanceled()) return; var targetResult = {}; function inlineCallback(inlineStyle, attributesStyle) { targetResult.inlineStyle = inlineStyle; targetResult.attributesStyle = attributesStyle; } function matchedCallback(result) { if (result) targetResult.matchedCSSRules = result.matchedCSSRules; } if (!nodeIds || !nodeIds.length) doneCallback(); for (var i = 0; nodeIds && i < nodeIds.length; ++i) { WebInspector.cssModel.getMatchedStylesAsync(nodeIds[i], false, false, matchedCallback); WebInspector.cssModel.getInlineStylesAsync(nodeIds[i], inlineCallback); WebInspector.cssModel.getComputedStyleAsync(nodeIds[i], imageStylesReady.bind(null, nodeIds[i], targetResult, i === nodeIds.length - 1)); } } function onDocumentAvailable(root) { if (progress.isCanceled()) return; WebInspector.domAgent.querySelectorAll(root.id, "img[src]", getStyles); } if (progress.isCanceled()) return; WebInspector.domAgent.requestDocument(onDocumentAvailable); }, __proto__: WebInspector.AuditRule.prototype } /** * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.CssInHeadRule = function() { WebInspector.AuditRule.call(this, "page-cssinhead", "Put CSS in the document head"); } WebInspector.AuditRules.CssInHeadRule.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { function evalCallback(evalResult) { if (progress.isCanceled()) return; if (!evalResult) return callback(null); var summary = result.addChild(""); var outputMessages = []; for (var url in evalResult) { var urlViolations = evalResult[url]; if (urlViolations[0]) { result.addFormatted("%s style block(s) in the %r body should be moved to the document head.", urlViolations[0], url); result.violationCount += urlViolations[0]; } for (var i = 0; i < urlViolations[1].length; ++i) result.addFormatted("Link node %r should be moved to the document head in %r", urlViolations[1][i], url); result.violationCount += urlViolations[1].length; } summary.value = String.sprintf("CSS in the document body adversely impacts rendering performance."); callback(result); } function externalStylesheetsReceived(root, inlineStyleNodeIds, nodeIds) { if (progress.isCanceled()) return; if (!nodeIds) return; var externalStylesheetNodeIds = nodeIds; var result = null; if (inlineStyleNodeIds.length || externalStylesheetNodeIds.length) { var urlToViolationsArray = {}; var externalStylesheetHrefs = []; for (var j = 0; j < externalStylesheetNodeIds.length; ++j) { var linkNode = WebInspector.domAgent.nodeForId(externalStylesheetNodeIds[j]); var completeHref = WebInspector.ParsedURL.completeURL(linkNode.ownerDocument.baseURL, linkNode.getAttribute("href")); externalStylesheetHrefs.push(completeHref || "<empty>"); } urlToViolationsArray[root.documentURL] = [inlineStyleNodeIds.length, externalStylesheetHrefs]; result = urlToViolationsArray; } evalCallback(result); } function inlineStylesReceived(root, nodeIds) { if (progress.isCanceled()) return; if (!nodeIds) return; WebInspector.domAgent.querySelectorAll(root.id, "body link[rel~='stylesheet'][href]", externalStylesheetsReceived.bind(null, root, nodeIds)); } function onDocumentAvailable(root) { if (progress.isCanceled()) return; WebInspector.domAgent.querySelectorAll(root.id, "body style", inlineStylesReceived.bind(null, root)); } WebInspector.domAgent.requestDocument(onDocumentAvailable); }, __proto__: WebInspector.AuditRule.prototype } /** * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.StylesScriptsOrderRule = function() { WebInspector.AuditRule.call(this, "page-stylescriptorder", "Optimize the order of styles and scripts"); } WebInspector.AuditRules.StylesScriptsOrderRule.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { function evalCallback(resultValue) { if (progress.isCanceled()) return; if (!resultValue) return callback(null); var lateCssUrls = resultValue[0]; var cssBeforeInlineCount = resultValue[1]; if (lateCssUrls.length) { var entry = result.addChild("The following external CSS files were included after an external JavaScript file in the document head. To ensure CSS files are downloaded in parallel, always include external CSS before external JavaScript.", true); entry.addURLs(lateCssUrls); result.violationCount += lateCssUrls.length; } if (cssBeforeInlineCount) { result.addChild(String.sprintf(" %d inline script block%s found in the head between an external CSS file and another resource. To allow parallel downloading, move the inline script before the external CSS file, or after the next resource.", cssBeforeInlineCount, cssBeforeInlineCount > 1 ? "s were" : " was")); result.violationCount += cssBeforeInlineCount; } callback(result); } function cssBeforeInlineReceived(lateStyleIds, nodeIds) { if (progress.isCanceled()) return; if (!nodeIds) return; var cssBeforeInlineCount = nodeIds.length; var result = null; if (lateStyleIds.length || cssBeforeInlineCount) { var lateStyleUrls = []; for (var i = 0; i < lateStyleIds.length; ++i) { var lateStyleNode = WebInspector.domAgent.nodeForId(lateStyleIds[i]); var completeHref = WebInspector.ParsedURL.completeURL(lateStyleNode.ownerDocument.baseURL, lateStyleNode.getAttribute("href")); lateStyleUrls.push(completeHref || "<empty>"); } result = [ lateStyleUrls, cssBeforeInlineCount ]; } evalCallback(result); } function lateStylesReceived(root, nodeIds) { if (progress.isCanceled()) return; if (!nodeIds) return; WebInspector.domAgent.querySelectorAll(root.id, "head link[rel~='stylesheet'][href] ~ script:not([src])", cssBeforeInlineReceived.bind(null, nodeIds)); } function onDocumentAvailable(root) { if (progress.isCanceled()) return; WebInspector.domAgent.querySelectorAll(root.id, "head script[src] ~ link[rel~='stylesheet'][href]", lateStylesReceived.bind(null, root)); } WebInspector.domAgent.requestDocument(onDocumentAvailable); }, __proto__: WebInspector.AuditRule.prototype } /** * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.CSSRuleBase = function(id, name) { WebInspector.AuditRule.call(this, id, name); } WebInspector.AuditRules.CSSRuleBase.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { CSSAgent.getAllStyleSheets(sheetsCallback.bind(this)); function sheetsCallback(error, headers) { if (error) return callback(null); if (!headers.length) return callback(null); for (var i = 0; i < headers.length; ++i) { var header = headers[i]; if (header.disabled) continue; // Do not check disabled stylesheets. this._visitStyleSheet(header.styleSheetId, i === headers.length - 1 ? finishedCallback : null, result, progress); } } function finishedCallback() { callback(result); } }, _visitStyleSheet: function(styleSheetId, callback, result, progress) { WebInspector.CSSStyleSheet.createForId(styleSheetId, sheetCallback.bind(this)); function sheetCallback(styleSheet) { if (progress.isCanceled()) return; if (!styleSheet) { if (callback) callback(); return; } this.visitStyleSheet(styleSheet, result); for (var i = 0; i < styleSheet.rules.length; ++i) this._visitRule(styleSheet, styleSheet.rules[i], result); this.didVisitStyleSheet(styleSheet, result); if (callback) callback(); } }, _visitRule: function(styleSheet, rule, result) { this.visitRule(styleSheet, rule, result); var allProperties = rule.style.allProperties; for (var i = 0; i < allProperties.length; ++i) this.visitProperty(styleSheet, allProperties[i], result); this.didVisitRule(styleSheet, rule, result); }, visitStyleSheet: function(styleSheet, result) { // Subclasses can implement. }, didVisitStyleSheet: function(styleSheet, result) { // Subclasses can implement. }, visitRule: function(styleSheet, rule, result) { // Subclasses can implement. }, didVisitRule: function(styleSheet, rule, result) { // Subclasses can implement. }, visitProperty: function(styleSheet, property, result) { // Subclasses can implement. }, __proto__: WebInspector.AuditRule.prototype } /** * @constructor * @extends {WebInspector.AuditRules.CSSRuleBase} */ WebInspector.AuditRules.VendorPrefixedCSSProperties = function() { WebInspector.AuditRules.CSSRuleBase.call(this, "page-vendorprefixedcss", "Use normal CSS property names instead of vendor-prefixed ones"); this._webkitPrefix = "-webkit-"; } WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties = [ "background-clip", "background-origin", "background-size", "border-radius", "border-bottom-left-radius", "border-bottom-right-radius", "border-top-left-radius", "border-top-right-radius", "box-shadow", "box-sizing", "opacity", "text-shadow" ].keySet(); WebInspector.AuditRules.VendorPrefixedCSSProperties.prototype = { didVisitStyleSheet: function(styleSheet) { delete this._styleSheetResult; }, visitRule: function(rule) { this._mentionedProperties = {}; }, didVisitRule: function() { delete this._ruleResult; delete this._mentionedProperties; }, visitProperty: function(styleSheet, property, result) { if (!property.name.startsWith(this._webkitPrefix)) return; var normalPropertyName = property.name.substring(this._webkitPrefix.length).toLowerCase(); // Start just after the "-webkit-" prefix. if (WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties[normalPropertyName] && !this._mentionedProperties[normalPropertyName]) { var style = property.ownerStyle; var liveProperty = style.getLiveProperty(normalPropertyName); if (liveProperty && !liveProperty.styleBased) return; // WebCore can provide normal versions of prefixed properties automatically, so be careful to skip only normal source-based properties. var rule = style.parentRule; this._mentionedProperties[normalPropertyName] = true; if (!this._styleSheetResult) this._styleSheetResult = result.addChild(rule.sourceURL ? WebInspector.linkifyResourceAsNode(rule.sourceURL) : "<unknown>"); if (!this._ruleResult) { var anchor = WebInspector.linkifyURLAsNode(rule.sourceURL, rule.selectorText); anchor.preferredPanel = "resources"; anchor.lineNumber = rule.lineNumberInSource(); this._ruleResult = this._styleSheetResult.addChild(anchor); } ++result.violationCount; this._ruleResult.addSnippet(String.sprintf("\"" + this._webkitPrefix + "%s\" is used, but \"%s\" is supported.", normalPropertyName, normalPropertyName)); } }, __proto__: WebInspector.AuditRules.CSSRuleBase.prototype } /** * @constructor * @extends {WebInspector.AuditRule} */ WebInspector.AuditRules.CookieRuleBase = function(id, name) { WebInspector.AuditRule.call(this, id, name); } WebInspector.AuditRules.CookieRuleBase.prototype = { /** * @param {!Array.<!WebInspector.NetworkRequest>} requests * @param {!WebInspector.AuditRuleResult} result * @param {function(WebInspector.AuditRuleResult)} callback * @param {!WebInspector.Progress} progress */ doRun: function(requests, result, callback, progress) { var self = this; function resultCallback(receivedCookies) { if (progress.isCanceled()) return; self.processCookies(receivedCookies, requests, result); callback(result); } WebInspector.Cookies.getCookiesAsync(resultCallback); }, mapResourceCookies: function(requestsByDomain, allCookies, callback) { for (var i = 0; i < allCookies.length; ++i) { for (var requestDomain in requestsByDomain) { if (WebInspector.Cookies.cookieDomainMatchesResourceDomain(allCookies[i].domain(), requestDomain)) this._callbackForResourceCookiePairs(requestsByDomain[requestDomain], allCookies[i], callback); } } }, _callbackForResourceCookiePairs: function(requests, cookie, callback) { if (!requests) return; for (var i = 0; i < requests.length; ++i) { if (WebInspector.Cookies.cookieMatchesResourceURL(cookie, requests[i].url)) callback(requests[i], cookie); } }, __proto__: WebInspector.AuditRule.prototype } /** * @constructor * @extends {WebInspector.AuditRules.CookieRuleBase} */ WebInspector.AuditRules.CookieSizeRule = function(avgBytesThreshold) { WebInspector.AuditRules.CookieRuleBase.call(this, "http-cookiesize", "Minimize cookie size"); this._avgBytesThreshold = avgBytesThreshold; this._maxBytesThreshold = 1000; } WebInspector.AuditRules.CookieSizeRule.prototype = { _average: function(cookieArray) { var total = 0; for (var i = 0; i < cookieArray.length; ++i) total += cookieArray[i].size(); return cookieArray.length ? Math.round(total / cookieArray.length) : 0; }, _max: function(cookieArray) { var result = 0; for (var i = 0; i < cookieArray.length; ++i) result = Math.max(cookieArray[i].size(), result); return result; }, processCookies: function(allCookies, requests, result) { function maxSizeSorter(a, b) { return b.maxCookieSize - a.maxCookieSize; } function avgSizeSorter(a, b) { return b.avgCookieSize - a.avgCookieSize; } var cookiesPerResourceDomain = {}; function collectorCallback(request, cookie) { var cookies = cookiesPerResourceDomain[request.parsedURL.host]; if (!cookies) { cookies = []; cookiesPerResourceDomain[request.parsedURL.host] = cookies; } cookies.push(cookie); } if (!allCookies.length) return; var sortedCookieSizes = []; var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, null, true); var matchingResourceData = {}; this.mapResourceCookies(domainToResourcesMap, allCookies, collectorCallback.bind(this)); for (var requestDomain in cookiesPerResourceDomain) { var cookies = cookiesPerResourceDomain[requestDomain]; sortedCookieSizes.push({ domain: requestDomain, avgCookieSize: this._average(cookies), maxCookieSize: this._max(cookies) }); } var avgAllCookiesSize = this._average(allCookies); var hugeCookieDomains = []; sortedCookieSizes.sort(maxSizeSorter); for (var i = 0, len = sortedCookieSizes.length; i < len; ++i) { var maxCookieSize = sortedCookieSizes[i].maxCookieSize; if (maxCookieSize > this._maxBytesThreshold) hugeCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(sortedCookieSizes[i].domain) + ": " + Number.bytesToString(maxCookieSize)); } var bigAvgCookieDomains = []; sortedCookieSizes.sort(avgSizeSorter); for (var i = 0, len = sortedCookieSizes.length; i < len; ++i) { var domain = sortedCookieSizes[i].domain; var avgCookieSize = sortedCookieSizes[i].avgCookieSize; if (avgCookieSize > this._avgBytesThreshold && avgCookieSize < this._maxBytesThreshold) bigAvgCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(domain) + ": " + Number.bytesToString(avgCookieSize)); } result.addChild(String.sprintf("The average cookie size for all requests on this page is %s", Number.bytesToString(avgAllCookiesSize))); var message; if (hugeCookieDomains.length) { var entry = result.addChild("The following domains have a cookie size in excess of 1KB. This is harmful because requests with cookies larger than 1KB typically cannot fit into a single network packet.", true); entry.addURLs(hugeCookieDomains); result.violationCount += hugeCookieDomains.length; } if (bigAvgCookieDomains.length) { var entry = result.addChild(String.sprintf("The following domains have an average cookie size in excess of %d bytes. Reducing the size of cookies for these domains can reduce the time it takes to send requests.", this._avgBytesThreshold), true); entry.addURLs(bigAvgCookieDomains); result.violationCount += bigAvgCookieDomains.length; } }, __proto__: WebInspector.AuditRules.CookieRuleBase.prototype } /** * @constructor * @extends {WebInspector.AuditRules.CookieRuleBase} */ WebInspector.AuditRules.StaticCookielessRule = function(minResources) { WebInspector.AuditRules.CookieRuleBase.call(this, "http-staticcookieless", "Serve static content from a cookieless domain"); this._minResources = minResources; } WebInspector.AuditRules.StaticCookielessRule.prototype = { processCookies: function(allCookies, requests, result) { var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, [WebInspector.resourceTypes.Stylesheet, WebInspector.resourceTypes.Image], true); var totalStaticResources = 0; for (var domain in domainToResourcesMap) totalStaticResources += domainToResourcesMap[domain].length; if (totalStaticResources < this._minResources) return; var matchingResourceData = {}; this.mapResourceCookies(domainToResourcesMap, allCookies, this._collectorCallback.bind(this, matchingResourceData)); var badUrls = []; var cookieBytes = 0; for (var url in matchingResourceData) { badUrls.push(url); cookieBytes += matchingResourceData[url] } if (badUrls.length < this._minResources) return; var entry = result.addChild(String.sprintf("%s of cookies were sent with the following static resources. Serve these static resources from a domain that does not set cookies:", Number.bytesToString(cookieBytes)), true); entry.addURLs(badUrls); result.violationCount = badUrls.length; }, _collectorCallback: function(matchingResourceData, request, cookie) { matchingResourceData[request.url] = (matchingResourceData[request.url] || 0) + cookie.size(); }, __proto__: WebInspector.AuditRules.CookieRuleBase.prototype }
widged/SOT-skills-report
electron/lib/react-devtools/blink/Source/devtools/front_end/AuditRules.js
JavaScript
mit
53,702
package org.anddev.andengine.util; import android.graphics.Color; /** * @author Nicolas Gramlich * @since 11:13:45 - 04.08.2010 */ public class ColorUtils { // =========================================================== // Constants // =========================================================== private static final float[] HSV_TO_COLOR = new float[3]; private static final int HSV_TO_COLOR_HUE_INDEX = 0; private static final int HSV_TO_COLOR_SATURATION_INDEX = 1; private static final int HSV_TO_COLOR_VALUE_INDEX = 2; private static final int COLOR_FLOAT_TO_INT_FACTOR = 255; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== /** * @param pHue [0 .. 360) * @param pSaturation [0...1] * @param pValue [0...1] */ public static int HSVToColor(final float pHue, final float pSaturation, final float pValue) { HSV_TO_COLOR[HSV_TO_COLOR_HUE_INDEX] = pHue; HSV_TO_COLOR[HSV_TO_COLOR_SATURATION_INDEX] = pSaturation; HSV_TO_COLOR[HSV_TO_COLOR_VALUE_INDEX] = pValue; return Color.HSVToColor(HSV_TO_COLOR); } public static int RGBToColor(final float pRed, final float pGreen, final float pBlue) { return Color.rgb((int)(pRed * COLOR_FLOAT_TO_INT_FACTOR), (int)(pGreen * COLOR_FLOAT_TO_INT_FACTOR), (int)(pBlue * COLOR_FLOAT_TO_INT_FACTOR)); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
liufeiit/itmarry
source/android-game/PlantsVsBugs/src/org/anddev/andengine/util/ColorUtils.java
Java
mit
2,138
# Something
cqqccqc/Something
README.md
Markdown
mit
12
- Place desktop specific containers here. - These containers are common across routes i.e. modals, drawers, etc.
Jonathan-Law/fhd
src/desktop/containers/README.md
Markdown
mit
112
using System; using System.Collections.Generic; namespace KSPAdvancedFlyByWire { public class Bitset { public int m_SingleData = 0; public int[] m_Data = null; public int m_NumBits = 0; public Bitset() {} public Bitset(int numBits) { m_NumBits = numBits; if (numBits <= 32) { m_SingleData = 0; return; } int numInts = numBits / 32 + ((numBits % 32 == 0) ? 0 : 1); m_Data = new int[numInts]; for (var i = 0; i < numInts; i++) { m_Data[i] = 0; } } public Bitset Copy() { Bitset result = new Bitset(m_NumBits); if (m_NumBits <= 32) { result.m_SingleData = m_SingleData; return result; } for(int i = 0; i < m_Data.Length; i++) { result.m_Data[i] = m_Data[i]; } return result; } public override string ToString() { string result = ""; for (int i = 0; i < m_NumBits; i++) { if(Get(i)) { result = "1" + result; } else { result = "0" + result; } } return result; } public Bitset(int numBits, int initialValue) { m_NumBits = numBits; if (numBits <= 32) { numBits = 32; m_SingleData = initialValue; return; } int numInts = numBits / 32 + ((numBits % 32 == 0) ? 0 : 1); m_Data = new int[numInts]; for (var i = 0; i < numInts; i++) { m_Data[i] = 0; } m_Data[0] = initialValue; } public void Set(int bit) { if (m_NumBits <= 32) { m_SingleData |= 1 << (bit % 32); return; } m_Data[bit / 32] |= 1 << (bit % 32); } public bool Get(int bit) { if (m_NumBits <= 32) { return (m_SingleData & (1 << (bit % 32))) != 0; } return (m_Data[bit / 32] & (1 << (bit % 32))) != 0; } } }
taniwha/ksp-advanced-flybywire
Bitset.cs
C#
mit
2,500
--- title: Od Sjevera i Juga do Divote date: 14/03/2020 --- > <p></p> > “Od umnika neki će pasti, da se prokušaju, probrani, čisti do vremena svršetka, jer još nije došlo određeno vrijeme.” (Daniel 11,35) ### Biblijski tekstovi: Daniel 11; Daniel 8,3-8.20-22; Izaija 46,9.10; Daniel 8,9.23; Matej 27,33-50. Na početku ovog izazovnog poglavlja treba naglasiti nekoliko pojedinosti. Prvo, Daniel 11 podudara se s prethodnim općim pregledom proročanstava u Knjizi proroka Daniela. Kao i u 2., 7., 8. i 9. poglavlju, proročka poruka proteže se od vremena proroka do vremena svršetka. Drugo, spominje se smjenjivanje svjetskih sila koje često ugnjetavaju Božji narod. Treće, sretan kraj vrhunac je svakog proročanstva. U 2. poglavlju kamen uništava kip; u 7. poglavlju Sin Čovječji prima kraljevstvo; u 8. i 9. poglavlju čisti se nebesko Svetište zahvaljujući Mesijinoj službi. Prema tome, 11. poglavlje obuhvaća tri osnovne pojedinosti. Prvo, počinje izvještajem o perzijskim kraljevima i govori o njihovim sudbinama i vremenu svršetka, kada kralj Sjevera napada Božju Svetu goru. Drugo, opisan je niz bitaka između kralja Sjevera i kralja Juga i njihov utjecaj na Božji narod. Treće, završava sretnim krajem kada se kralj Sjevera suočava sa smrću kraj “Svete gore Divote” (Daniel 11,45). Ovakav pozitivan završetak označava kraj zla i uspostavljanje Božjeg vječnog kraljevstva. **Oikos: Ovog tjedna čitamo iz knjige Ellen G. White, Velika borba, Znaci vremena, 2010., poglavlje 27**
PrJared/sabbath-school-lessons
src/hr/2020-01/12/01.md
Markdown
mit
1,536
/* * This file Copyright (C) Mnemosyne LLC * * This file is licensed by the GPL version 2. Works owned by the * Transmission project are granted a special exemption to clause 2 (b) * so that the bulk of its code can remain under the MIT license. * This exemption does not extend to derived works not owned by * the Transmission project. * * $Id$ */ #ifndef __TRANSMISSION__ #error only libtransmission should #include this header. #endif #ifndef TR_CACHE_H #define TR_CACHE_H struct evbuffer; typedef struct tr_cache tr_cache; /*** **** ***/ tr_cache * tr_cacheNew (int64_t max_bytes); void tr_cacheFree (tr_cache *); /*** **** ***/ int tr_cacheSetLimit (tr_cache * cache, int64_t max_bytes); int64_t tr_cacheGetLimit (const tr_cache *); int tr_cacheWriteBlock (tr_cache * cache, tr_torrent * torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len, struct evbuffer * writeme); int tr_cacheReadBlock (tr_cache * cache, tr_torrent * torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len, uint8_t * setme); int tr_cachePrefetchBlock (tr_cache * cache, tr_torrent * torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len); /*** **** ***/ int tr_cacheFlushDone (tr_cache * cache); int tr_cacheFlushTorrent (tr_cache * cache, tr_torrent * torrent); int tr_cacheFlushFile (tr_cache * cache, tr_torrent * torrent, tr_file_index_t file); #endif
HaikuArchives/Torrentor
source/libtransmission/cache.h
C
mit
1,944
SET JVM_OPT=-XX:MaxMetaspaceSize=256M START javaw %JVM_OPT% -jar logbook-kai.jar
Sdk0815/logbook-kai
dist-includes/launch.bat
Batchfile
mit
83
package org.jabref.gui.fieldeditors; import java.util.stream.Collectors; import javafx.beans.binding.Bindings; import javafx.fxml.FXML; import javafx.scene.Parent; import javafx.scene.layout.HBox; import org.jabref.gui.autocompleter.SuggestionProvider; import org.jabref.gui.util.ViewModelListCellFactory; import org.jabref.logic.integrity.FieldCheckers; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.ParsedEntryLink; import org.jabref.model.entry.field.Field; import com.airhacks.afterburner.views.ViewLoader; import com.jfoenix.controls.JFXChip; import com.jfoenix.controls.JFXChipView; import com.jfoenix.controls.JFXDefaultChip; public class LinkedEntriesEditor extends HBox implements FieldEditorFX { @FXML private final LinkedEntriesEditorViewModel viewModel; @FXML private JFXChipView<ParsedEntryLink> chipView; public LinkedEntriesEditor(Field field, BibDatabaseContext databaseContext, SuggestionProvider<BibEntry> suggestionProvider, FieldCheckers fieldCheckers) { this.viewModel = new LinkedEntriesEditorViewModel(field, suggestionProvider, databaseContext, fieldCheckers); ViewLoader.view(this) .root(this) .load(); chipView.setConverter(viewModel.getStringConverter()); var autoCompletionItemFactory = new ViewModelListCellFactory<ParsedEntryLink>() .withText(ParsedEntryLink::getKey); chipView.getAutoCompletePopup().setSuggestionsCellFactory(autoCompletionItemFactory); chipView.getAutoCompletePopup().setCellLimit(5); chipView.getSuggestions().addAll(suggestionProvider.getPossibleSuggestions().stream().map(ParsedEntryLink::new).collect(Collectors.toList())); chipView.setChipFactory((view, item) -> { JFXChip<ParsedEntryLink> chip = new JFXDefaultChip<>(view, item); chip.setOnMouseClicked(event -> viewModel.jumpToEntry(item)); return chip; }); Bindings.bindContentBidirectional(chipView.getChips(), viewModel.linkedEntriesProperty()); } public LinkedEntriesEditorViewModel getViewModel() { return viewModel; } @Override public void bindToEntry(BibEntry entry) { viewModel.bindToEntry(entry); } @Override public Parent getNode() { return this; } }
sauliusg/jabref
src/main/java/org/jabref/gui/fieldeditors/LinkedEntriesEditor.java
Java
mit
2,406
// Copyright 2020 The Gitea Authors. All rights reserved. // Copyright 2016 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package convert import ( "strings" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" ) // ToCorrectPageSize makes sure page size is in allowed range. func ToCorrectPageSize(size int) int { if size <= 0 { size = setting.API.DefaultPagingNum } else if size > setting.API.MaxResponseItems { size = setting.API.MaxResponseItems } return size } // ToGitServiceType return GitServiceType based on string func ToGitServiceType(value string) structs.GitServiceType { switch strings.ToLower(value) { case "github": return structs.GithubService case "gitea": return structs.GiteaService case "gitlab": return structs.GitlabService case "gogs": return structs.GogsService default: return structs.PlainGitService } }
cez81/gitea
modules/convert/utils.go
GO
mit
983
var optionValueKeyMarkdown = require('../markdown/js/properties/optionValueKey').body; var optionValueKeyProp = { nameAttr: "optionValueKey", renderString: optionValueKeyMarkdown }; module.exports = optionValueKeyProp;
cloudability/react-super-select
src_docs/properties/optionValueKey.js
JavaScript
mit
228
<div class="content-section introduction"> <div> <span class="feature-title">Messages</span> <span>Messages is used to display messages inline.</span> </div> </div> <div class="content-section implementation"> <p-messages [(value)]="msgs"></p-messages> <h3 class="first">Basic</h3> <div> <button type="button" pButton (click)="showSuccess()" label="Success" class="ui-button-success"></button> <button type="button" pButton (click)="showInfo()" label="Info" class="ui-button-info"></button> <button type="button" pButton (click)="showWarn()" label="Warn" class="ui-button-warning"></button> <button type="button" pButton (click)="showError()" label="Error" class="ui-button-danger"></button> <button type="button" pButton (click)="showMultiple()" label="Multiple"></button> <button type="button" pButton (click)="clear()" icon="fa-close" style="float:right" label="Clear"></button> </div> <h3>Message Service</h3> <button type="button" pButton (click)="showViaService()" label="Use Service"></button> <h3>Inline Message CSS</h3> <p>p-message component is used to display inline messages mostly within forms.</p> <p-message severity="info" text="PrimeNG Rocks"></p-message> <p-message severity="success" text="Record Saved"></p-message> <p-message severity="warn" text="Are you sure?"></p-message> <p-message severity="error" text="Field is required"></p-message> <div style="margin-top:30px"> <input type="text" pInputText placeholder="Username" class="ng-dirty ng-invalid"> <p-message severity="error" text="Field is required"></p-message> </div> <div style="margin-top:30px"> <input type="text" pInputText placeholder="Email" class="ng-dirty ng-invalid"> <p-message severity="error"></p-message> </div> </div> <div class="content-section documentation"> <p-tabView effect="fade"> <p-tabPanel header="Documentation"> <h3>Import</h3> <pre> <code class="language-typescript" pCode ngNonBindable> import &#123;MessagesModule&#125; from 'primeng/primeng'; import &#123;MessageModule&#125; from 'primeng/primeng'; </code> </pre> <h3>Getting Started</h3> <p>A single message is specified by Message interface in PrimeNG that defines the id, severity, summary and detail as the properties. Messages to display can either be defined using the value property which should an array of Message instances or using a MessageService are defined using the value property which should an array of Message instances.</p> <pre> <code class="language-markup" pCode ngNonBindable> &lt;p-messages [(value)]="msgs"&gt;&lt;/p-messages&gt; </code> </pre> <h3>Message Array</h3> <p>A binding to the value property is required to provide messages to the component.</p> <pre> <code class="language-markup" pCode ngNonBindable> &lt;p-messages [(value)]="msgs"&gt;&lt;/p-messages&gt; &lt;button type="button" (click)="show()"&gt;Show&lt;/button&gt; &lt;button type="button" (click)="clear()"&gt;Hide&lt;/button&gt; </code> </pre> <pre> <code class="language-typescript" pCode ngNonBindable> show() &#123; this.msgs.push(&#123;severity:'info', summary:'Info Message', detail:'PrimeNG rocks'&#125;); &#125; hide() &#123; this.msgs = []; &#125; </code> </pre> <h3>Message Service</h3> <p>MessageService alternative does not require a value binding to an array. In order to use this service, import the class and define it as a provider in a component higher up in the component tree such as application instance itself so that descandant components can have it injected.</p> <pre> <code class="language-typescript" pCode ngNonBindable> import &#123;MessageService&#125; from 'primeng/components/common/messageservice'; </code> </pre> <pre> <code class="language-typescript" pCode ngNonBindable> import &#123;Component&#125; from '@angular/core'; import &#123;Message&#125; from 'primeng/components/common/api'; import &#123;MessageService&#125; from 'primeng/components/common/messageservice'; @Component(&#123; templateUrl: './messagesdemo.html' &#125;) export class MessageServiceDemo &#123; constructor(private messageService: MessageService) &#123;&#125; addSingle() &#123; this.messageService.add(&#123;severity:'success', summary:'Service Message', detail:'Via MessageService'&#125;); &#125; addMultiple() &#123; this.messageService.addAll([&#123;severity:'success', summary:'Service Message', detail:'Via MessageService'&#125;, &#123;severity:'info', summary:'Info Message', detail:'Via MessageService'&#125;]); &#125; clear() &#123; this.messageService.clear(); &#125; &#125; </code> </pre> <h3>Closable</h3> <p>Messages are closable by default resulting in a close icon being displayed on top right corner.</p> <pre> <code class="language-markup" pCode ngNonBindable> &lt;p-messages [(value)]="msgs"&gt;&lt;/p-messages&gt; </code> </pre> <p>In order to disable closable messages, set closable to false. Note that in this case two-way binding is not necessary as the component does not need to update its value.</p> <pre> <code class="language-markup" pCode ngNonBindable> &lt;p-messages [value]="msgs" [closable]="false"&gt;&lt;/p-messages&gt; </code> </pre> <h3>Severities</h3> <p>Here are the possible values for the severity of a message.</p> <ul> <li>success</li> <li>info</li> <li>warn</li> <li>error</li> </ul> <h3>Message Component</h3> <p>Message component is useful in cases where messages need to be displayed related to an element such as forms. It has two property, severity and text of the message.</p> <pre> <code class="language-markup" pCode ngNonBindable> &lt;h3&gt;Inline Message CSS&lt;/h3&gt; &lt;p&gt;CSS helpers to display inline messages mostly within forms.&lt;/p&gt; &lt;p-message severity="info" text="PrimeNG Rocks"&gt;&lt;/p-message&gt; &lt;p-message severity="success" text="Record Saved"&gt;&lt;/p-message&gt; &lt;p-message severity="warn" text="Are you sure?"&gt;&lt;/p-message&gt; &lt;p-message severity="error" text="Field is required"&gt;&lt;/p-message&gt; </code> </pre> <h3>Properties</h3> <div class="doc-tablewrapper"> <table class="doc-table"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>value</td> <td>array</td> <td>null</td> <td>An array of messages to display.</td> </tr> <tr> <td>closable</td> <td>boolean</td> <td>true</td> <td>Defines if message box can be closed by the click icon.</td> </tr> </tbody> </table> </div> <h3>Styling</h3> <p>Following is the list of structural style classes, for theming classes visit <a href="#" [routerLink]="['/theming']">theming page</a>.</p> <div class="doc-tablewrapper"> <table class="doc-table"> <thead> <tr> <th>Name</th> <th>Element</th> </tr> </thead> <tbody> <tr> <td>ui-messages</td> <td>Container element.</td> </tr> <tr> <td>ui-messages-info</td> <td>Container element when displaying info messages.</td> </tr> <tr> <td>ui-messages-warn</td> <td>Container element when displaying warning messages.</td> </tr> <tr> <td>ui-messages-error</td> <td>Container element when displaying error messages.</td> </tr> <tr> <td>ui-messages-success</td> <td>Container element when displaying success messages.</td> </tr> <tr> <td>ui-messages-close</td> <td>Close icon.</td> </tr> <tr> <td>ui-messages-icon</td> <td>Severity icon.</td> </tr> <tr> <td>ui-messages-summary</td> <td>Summary of a message.</td> </tr> <tr> <td>ui-messages-detail</td> <td>Detail of a message.</td> </tr> </tbody> </table> </div> <h3>Dependencies</h3> <p>None.</p> </p-tabPanel> <p-tabPanel header="Source"> <a href="https://github.com/primefaces/primeng/tree/master/src/app/showcase/components/messages" class="btn-viewsource" target="_blank"> <i class="fa fa-github"></i> <span>View on GitHub</span> </a> <pre> <code class="language-markup" pCode ngNonBindable> &lt;p-messages [(value)]="msgs"&gt;&lt;/p-messages&gt; &lt;h3 class="first"&gt;Basic&lt;/h3&gt; &lt;div&gt; &lt;button type="button" pButton (click)="showSuccess()" label="Success" class="ui-button-success"&gt;&lt;/button&gt; &lt;button type="button" pButton (click)="showInfo()" label="Info" class="ui-button-info"&gt;&lt;/button&gt; &lt;button type="button" pButton (click)="showWarn()" label="Warn" class="ui-button-warning"&gt;&lt;/button&gt; &lt;button type="button" pButton (click)="showError()" label="Error" class="ui-button-danger"&gt;&lt;/button&gt; &lt;button type="button" pButton (click)="showMultiple()" label="Multiple"&gt;&lt;/button&gt; &lt;button type="button" pButton (click)="clear()" icon="fa-close" style="float:right" label="Clear"&gt;&lt;/button&gt; &lt;/div&gt; &lt;h3&gt;Message Service&lt;/h3&gt; &lt;button type="button" pButton (click)="showViaService()" label="Use Service"&gt;&lt;/button&gt; &lt;h3&gt;Inline Message CSS&lt;/h3&gt; &lt;p&gt;CSS helpers to display inline messages mostly within forms.&lt;/p&gt; &lt;p-message severity="info" text="PrimeNG Rocks"&gt;&lt;/p-message&gt; &lt;p-message severity="success" text="Record Saved"&gt;&lt;/p-message&gt; &lt;p-message severity="warn" text="Are you sure?"&gt;&lt;/p-message&gt; &lt;p-message severity="error" text="Field is required"&gt;&lt;/p-message&gt; &lt;div style="margin-top:30px"&gt; &lt;input type="text" pInputText placeholder="Username" class="ng-dirty ng-invalid"&gt; &lt;p-message severity="error" text="Field is required"&gt;&lt;/p-message&gt; &lt;/div&gt; &lt;div style="margin-top:30px"&gt; &lt;input type="text" pInputText placeholder="Email" class="ng-dirty ng-invalid"&gt; &lt;p-message severity="error"&gt;&lt;/p-message&gt; &lt;/div> </code> </pre> <pre> <code class="language-typescript" pCode ngNonBindable> import &#123;Component&#125; from '@angular/core'; import &#123;SelectItem&#125; from 'primeng/components/common/api'; import &#123;Message&#125; from 'primeng/components/common/api'; import &#123;MessageService&#125; from 'primeng/components/common/messageservice'; @Component(&#123; templateUrl: './messagesdemo.html', providers: [MessageService] &#125;) export class GrowlDemo &#123; msgs: Message[] = []; constructor(private messageService: MessageService) &#123;&#125; showSuccess() &#123; this.msgs = []; this.msgs.push(&#123;severity:'success', summary:'Success Message', detail:'Order submitted'&#125;); &#125; showInfo() &#123; this.msgs = []; this.msgs.push(&#123;severity:'info', summary:'Info Message', detail:'PrimeNG rocks'&#125;); &#125; showWarn() &#123; this.msgs = []; this.msgs.push(&#123;severity:'warn', summary:'Warn Message', detail:'There are unsaved changes'&#125;); &#125; showError() &#123; this.msgs = []; this.msgs.push(&#123;severity:'error', summary:'Error Message', detail:'Validation failed'&#125;); &#125; showMultiple() &#123; this.msgs = []; this.msgs.push(&#123;severity:'info', summary:'Message 1', detail:'PrimeNG rocks'&#125;); this.msgs.push(&#123;severity:'info', summary:'Message 2', detail:'PrimeUI rocks'&#125;); this.msgs.push(&#123;severity:'info', summary:'Message 3', detail:'PrimeFaces rocks'&#125;); &#125; showViaService() &#123; this.messageService.add(&#123;severity:'success', summary:'Service Message', detail:'Via MessageService'&#125;); &#125; clear() &#123; this.msgs = []; &#125; &#125; </code> </pre> </p-tabPanel> </p-tabView> </div>
donriver/primeng
src/app/showcase/components/messages/messagesdemo.html
HTML
mit
13,981
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; namespace Azure.IoT.DeviceUpdate.Models { /// <summary> Update compatibility information. </summary> public partial class Compatibility { /// <summary> Initializes a new instance of Compatibility. </summary> /// <param name="deviceManufacturer"> The manufacturer of device the update is compatible with. </param> /// <param name="deviceModel"> The model of device the update is compatible with. </param> /// <exception cref="ArgumentNullException"> <paramref name="deviceManufacturer"/> or <paramref name="deviceModel"/> is null. </exception> internal Compatibility(string deviceManufacturer, string deviceModel) { if (deviceManufacturer == null) { throw new ArgumentNullException(nameof(deviceManufacturer)); } if (deviceModel == null) { throw new ArgumentNullException(nameof(deviceModel)); } DeviceManufacturer = deviceManufacturer; DeviceModel = deviceModel; } /// <summary> The manufacturer of device the update is compatible with. </summary> public string DeviceManufacturer { get; } /// <summary> The model of device the update is compatible with. </summary> public string DeviceModel { get; } } }
ayeletshpigelman/azure-sdk-for-net
sdk/deviceupdate/Azure.Iot.DeviceUpdate/src/Generated/Models/Compatibility.cs
C#
mit
1,492
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- module.exports = function () { return { sql: "CREATE TABLE [__types] ([table] TEXT, [name] TEXT, [type] TEXT)" }; };
mamaso/azure-mobile-apps-node
src/data/sqlite/statements/columns.createTable.js
JavaScript
mit
367
<?php namespace LaravelDoctrine\Migrations\Configuration; use Doctrine\DBAL\Migrations\Configuration\Configuration as MigrationsConfiguration; use LaravelDoctrine\Migrations\Naming\NamingStrategy; class Configuration extends MigrationsConfiguration { /** * @var NamingStrategy */ protected $namingStrategy; /** * @return NamingStrategy */ public function getNamingStrategy() { return $this->namingStrategy; } /** * @param NamingStrategy $namingStrategy */ public function setNamingStrategy(NamingStrategy $namingStrategy) { $this->namingStrategy = $namingStrategy; } }
chilloutalready/migrations
src/Configuration/Configuration.php
PHP
mit
660
<!doctype html> <html> <head> <title>ATS-Sorting-Quick</title> <style> #canvas-container { margin: 0 auto; width: 920px; height: auto; } </style> <script src="https://cdn.jsdelivr.net/jquery/2.1.1/jquery.min.js"> </script> <script src="https://ats-lang.github.io/LIBRARY/libatscc2js/ATS2-0.3.2/libatscc2js_all.js"> </script> </head> <body> <h1>ATS->C->JS via atscc2js</h1> <div id="canvas-container"> <canvas id="Patsoptaas-Evaluate-canvas" width="920px" height="600px" oncontextmenu="event.preventDefault()"> It seems that canvas is not supported by your browser! </canvas> </div> <!-- HX-2014-11: it must be the last one! --> <script src="./Sorting_quick_php_dats.js"></script> </body> </html>
ashalkhakov/ATS-Postiats-contrib
projects/SMALL/JSmydraw/Sorting_quick/Sorting_quick.html
HTML
mit
704
--- layout: post title: "Quotes: Bull Brains" date: 2014-08-21 12:23:42 categories: quote author: Shane Leonard image: /images/quote-neill-bull-brains.jpg --- From the Sage of Saxtons River, [Humphrey B. Neill](http://www.businessinsider.com/the-sage-of-saxtons-river-2011-3). Neill wrote [The Art of Contrary Thinking](http://www.amazon.com/Art-Contrary-Thinking-Humphrey-Neill/dp/087004110X). "Don't confuse brains with a bull market." It's dangerous to your financial health when you get too confident. Do you have a favourite quote from a famous investor or stock market pundit? We'd love to hear it. Please drop me a message [@shaneleonard121](https://twitter.com/shaneleonard121) or message our full team [@stockflare](https://twitter.com/stockflare). Shane Leonard Managing Director Stockflare
Stockflare/blog
_posts/2014-08-21-quotes-neill-bull-brains.markdown
Markdown
mit
811
/* DotNetMQ - A Complete Message Broker For .NET Copyright (C) 2011 Halil ibrahim KALKAN This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Reflection; using System.IO; using System.Net.Sockets; using System.Threading; using log4net; using MDS.Communication.Messages; using MDS.Communication.Protocols; using MDS.Exceptions; using MDS.Serialization; namespace MDS.Communication.TCPCommunication { /// <summary> /// This class represents an communication channel with a Remote Application via TCP sockets. /// </summary> public class TCPCommunicator : CommunicatorBase { #region Private fields /// <summary> /// Reference to logger /// </summary> private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The TCP socket to the remote application. /// </summary> private readonly Socket _socket; /// <summary> /// The main stream wraps socket to send/receive data. /// </summary> private NetworkStream _networkStream; /// <summary> /// This object is used to send/receive messages as byte array. /// </summary> private readonly IMDSWireProtocol _wireProtocol; /// <summary> /// The thread that listens incoming data. /// </summary> private Thread _thread; #endregion #region Constructors /// <summary> /// Constructor. /// </summary> /// <param name="socket">Open TCP socket connection to the communicator.</param> /// <param name="comminicatorId">Unique identifier for this communicator.</param> public TCPCommunicator(Socket socket, long comminicatorId) : base(comminicatorId) { _socket = socket; _socket.NoDelay = true; CommunicationWay = CommunicationWays.SendAndReceive; _wireProtocol = new MDSDefaultWireProtocol(); } #endregion #region Public methods /// <summary> /// Waits communicator to stop. /// </summary> public override void WaitToStop() { if (_thread == null) { return; } try { _thread.Join(); } catch (Exception ex) { Logger.Warn(ex.Message, ex); } } #endregion #region Protected methods /// <summary> /// Prepares communication objects and starts data listening thread. /// </summary> protected override void StartCommunicaiton() { if (!_socket.Connected) { throw new MDSException("Tried to start communication with a TCP socket that is not connected."); } _networkStream = new NetworkStream(_socket); _thread = new Thread(DoCommunicateAsThread); _thread.Start(); } /// <summary> /// Closes the socket and stops the thread. /// </summary> /// <param name="waitToStop">True, to block caller thread until this object stops</param> protected override void StopCommunicaiton(bool waitToStop) { if (_socket.Connected) { _socket.Shutdown(SocketShutdown.Send); _socket.Close(); } if (waitToStop) { WaitToStop(); } } /// <summary> /// Sends a message to the TCP communicator according Communication type /// </summary> /// <param name="message">Message to send</param> protected override void SendMessageInternal(MDSMessage message) { if(State != CommunicationStates.Connected) { throw new MDSException("Communicator's state is not connected. It can not send message."); } SendMessageToSocket(message); } #endregion #region Private methods /// <summary> /// Entrance point of the thread. /// This method run by thread to listen incoming data from communicator. /// </summary> private void DoCommunicateAsThread() { Logger.Debug("TCPCommunicator thread is started. CommunicatorId=" + ComminicatorId); while (State == CommunicationStates.Connected || State == CommunicationStates.Connecting) { try { //Read a message from _networkStream (socket) and raise MessageReceived event var message = _wireProtocol.ReadMessage(new MDSDefaultDeserializer(_networkStream)); Logger.Debug("Message received by communicator " + ComminicatorId + ": " + message.GetType().Name); OnMessageReceived(message); } catch (Exception ex) { Logger.Error(ex.Message, ex); break; //Stop listening } } //if socket is still connected, then close it try { Stop(false); } catch (Exception ex) { Logger.Warn(ex.Message, ex); } Logger.Debug("TCPCommunicator is stopped. CommunicatorId=" + ComminicatorId); _thread = null; } /// <summary> /// Sends MDSMessage object to the socket. /// </summary> /// <param name="message">Message to be sent</param> private void SendMessageToSocket(MDSMessage message) { Logger.Debug("Message is being sent to communicator " + ComminicatorId + ": " + message.GetType().Name); //Create MemoryStream to write message to a byte array var memoryStream = new MemoryStream(); //Write message _wireProtocol.WriteMessage(new MDSDefaultSerializer(memoryStream), message); //Check the length of message data if (memoryStream.Length > CommunicationConsts.MaxMessageSize) { throw new Exception("Message is too big to send."); } //SendMessage message (contents of created memory stream) var sendBuffer = memoryStream.ToArray(); var length = sendBuffer.Length; var totalSent = 0; while (totalSent < length) { var sent = _socket.Send(sendBuffer, totalSent, length - totalSent, SocketFlags.None); if (sent <= 0) { throw new Exception("Message can not be sent via TCP socket. Only " + totalSent + " bytes of " + length + " bytes are sent."); } totalSent += sent; } Logger.Debug("Message is sent to communicator " + ComminicatorId + ": " + message.GetType().Name); } #endregion } }
andrecarlucci/dotnetmq
src/MDSCore/Communication/TCPCommunication/TCPCommunicator.cs
C#
mit
7,844
module SearchHelper def search_autocomplete_opts(term) return unless current_user resources_results = [ groups_autocomplete(term), projects_autocomplete(term) ].flatten search_pattern = Regexp.new(Regexp.escape(term), "i") generic_results = project_autocomplete + default_autocomplete + help_autocomplete generic_results.select! { |result| result[:label] =~ search_pattern } [ resources_results, generic_results ].flatten.uniq do |item| item[:label] end end def search_entries_info(collection, scope, term) return unless collection.count > 0 from = collection.offset_value + 1 to = collection.offset_value + collection.length count = collection.total_count "Showing #{from} - #{to} of #{count} #{scope.humanize(capitalize: false)} for \"#{term}\"" end def parse_search_result(result) ref = nil filename = nil basename = nil startline = 0 result.each_line.each_with_index do |line, index| if line =~ /^.*:.*:\d+:/ ref, filename, startline = line.split(':') startline = startline.to_i - index extname = Regexp.escape(File.extname(filename)) basename = filename.sub(/#{extname}$/, '') break end end data = "" result.each_line do |line| data << line.sub(ref, '').sub(filename, '').sub(/^:-\d+-/, '').sub(/^::\d+:/, '') end OpenStruct.new( filename: filename, basename: basename, ref: ref, startline: startline, data: data ) end private # Autocomplete results for various settings pages def default_autocomplete [ { category: "Settings", label: "Profile settings", url: profile_path }, { category: "Settings", label: "SSH Keys", url: profile_keys_path }, { category: "Settings", label: "Dashboard", url: root_path }, { category: "Settings", label: "Admin Section", url: admin_root_path }, ] end # Autocomplete results for internal help pages def help_autocomplete [ { category: "Help", label: "API Help", url: help_page_path("api/README") }, { category: "Help", label: "Markdown Help", url: help_page_path("user/markdown") }, { category: "Help", label: "Permissions Help", url: help_page_path("user/permissions") }, { category: "Help", label: "Public Access Help", url: help_page_path("public_access/public_access") }, { category: "Help", label: "Rake Tasks Help", url: help_page_path("raketasks/README") }, { category: "Help", label: "SSH Keys Help", url: help_page_path("ssh/README") }, { category: "Help", label: "System Hooks Help", url: help_page_path("system_hooks/system_hooks") }, { category: "Help", label: "Webhooks Help", url: help_page_path("web_hooks/web_hooks") }, { category: "Help", label: "Workflow Help", url: help_page_path("workflow/README") }, ] end # Autocomplete results for the current project, if it's defined def project_autocomplete if @project && @project.repository.exists? && @project.repository.root_ref ref = @ref || @project.repository.root_ref [ { category: "Current Project", label: "Files", url: namespace_project_tree_path(@project.namespace, @project, ref) }, { category: "Current Project", label: "Commits", url: namespace_project_commits_path(@project.namespace, @project, ref) }, { category: "Current Project", label: "Network", url: namespace_project_network_path(@project.namespace, @project, ref) }, { category: "Current Project", label: "Graph", url: namespace_project_graph_path(@project.namespace, @project, ref) }, { category: "Current Project", label: "Issues", url: namespace_project_issues_path(@project.namespace, @project) }, { category: "Current Project", label: "Merge Requests", url: namespace_project_merge_requests_path(@project.namespace, @project) }, { category: "Current Project", label: "Milestones", url: namespace_project_milestones_path(@project.namespace, @project) }, { category: "Current Project", label: "Snippets", url: namespace_project_snippets_path(@project.namespace, @project) }, { category: "Current Project", label: "Members", url: namespace_project_project_members_path(@project.namespace, @project) }, { category: "Current Project", label: "Wiki", url: namespace_project_wikis_path(@project.namespace, @project) }, ] else [] end end # Autocomplete results for the current user's groups def groups_autocomplete(term, limit = 5) current_user.authorized_groups.search(term).limit(limit).map do |group| { category: "Groups", id: group.id, label: "#{search_result_sanitize(group.name)}", url: group_path(group) } end end # Autocomplete results for the current user's projects def projects_autocomplete(term, limit = 5) current_user.authorized_projects.search_by_title(term). sorted_by_stars.non_archived.limit(limit).map do |p| { category: "Projects", id: p.id, value: "#{search_result_sanitize(p.name)}", label: "#{search_result_sanitize(p.name_with_namespace)}", url: namespace_project_path(p.namespace, p) } end end def search_result_sanitize(str) Sanitize.clean(str) end def search_filter_path(options = {}) exist_opts = { search: params[:search], project_id: params[:project_id], group_id: params[:group_id], scope: params[:scope], repository_ref: params[:repository_ref] } options = exist_opts.merge(options) search_path(options) end # Sanitize a HTML field for search display. Most tags are stripped out and the # maximum length is set to 200 characters. def search_md_sanitize(object, field) html = markdown_field(object, field) html = Truncato.truncate( html, count_tags: false, count_tail: false, max_length: 200 ) # Truncato's filtered_tags and filtered_attributes are not quite the same sanitize(html, tags: %w(a p ol ul li pre code)) end end
screenpages/gitlabhq
app/helpers/search_helper.rb
Ruby
mit
6,269
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.15.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Bot.Builder.Luis.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; /// <summary> /// LUIS intent recommendation. Look at https://www.luis.ai/Help for more /// information. /// </summary> public partial class IntentRecommendation { /// <summary> /// Initializes a new instance of the IntentRecommendation class. /// </summary> public IntentRecommendation() { } /// <summary> /// Initializes a new instance of the IntentRecommendation class. /// </summary> public IntentRecommendation(string intent = default(string), double? score = default(double?), IList<Action> actions = default(IList<Action>)) { Intent = intent; Score = score; Actions = actions; } /// <summary> /// The LUIS intent detected by LUIS service in response to a query. /// </summary> [JsonProperty(PropertyName = "intent")] public string Intent { get; set; } /// <summary> /// The score for the detected intent. /// </summary> [JsonProperty(PropertyName = "score")] public double? Score { get; set; } /// <summary> /// The action associated with this Luis intent. /// </summary> [JsonProperty(PropertyName = "actions")] public IList<Action> Actions { get; set; } } }
Clairety/ConnectMe
CSharp/Library/Luis/Models/IntentRecommendation.cs
C#
mit
1,876
name(smtp). title('An (E)SMTP client for sending mail'). version('1.0.0'). keywords([smtp, mail, sendmail]). author('Jan Wielemaker', 'J.Wielemaker@vu.nl'). home('https://github.com/JanWielemaker/smtp'). download('https://github.com/JanWielemaker/smtp/releases/*.zip').
TeamSPoon/logicmoo_workspace
packs_web/swish/pack/smtp/pack.pl
Perl
mit
270
{% extends "layout.html" %} {% block page_title %} Apprenticeships {% endblock %} {% block content %} <style> .provider-nav a, .nav-forecast a { {% include "includes/nav-on-state-css.html" %} } </style> <main id="content" role="main"> {% include "includes/phase_banner_beta.html" %} {% include "includes/secondary-nav-provider.html" %} <!--div class="breadcrumbs"> <ol role="breadcrumbs"> <li><a href="/{% include "includes/sprint-link.html" %}/balance">Access my funds</a></li> </ol> </div--> <div class="breadcrumbs back-breadcrumb"> <ol role="breadcrumbs"> {% include "includes/breadcrumbs/register-back.html" %} </ol> </div> <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge" >Find your training provider</h1> <p>Search for the provider you have entered into a contract with.</p> <form action="provider-list"> <fieldset> <legend class="visuallyhidden">Find your provider</legend> <div class="form-group"> <label class="form-label-bold" for="search">Search for provider <span class="form-hint">Search for provider by name, UKPRN or postcode</span> </label> <input class="form-control" id="find-a-provider" type="text"> </div> </fieldset> <input class="button" id="search-provider" type="submit" value="Find"> </form> <div style="margin-top:50px"></div> <!-- template to pull in the start tabs so this doesn't get too messy - it is pulling in the tabs --> <!-- {% include "includes/start-tabs.html" %} --> </div> <div class="column-one-third"> <!--aside class="related"> <h2 class="heading-medium" style="margin-top:10px">Existing account</h2> <nav role="navigation"> <ul class="robSideNav"> <li> <a href="../login">Sign in</a> </li> </ul> </nav> </aside--> </div> </div> </main> <script> //jquery that runs the tabs. Uses the jquery.tabs.js from gov.uk $( document ).ready(function() { // change the tabs themselves to active - should be in the above but isn't working because it's looking for a not li so I added this as a quick fix. $("ul#tabs-nav li").click(function(e){ if (!$(this).hasClass("active")) { var tabNum = $(this).index(); var nthChild = tabNum+1; $("ul#tabs-nav li.active").removeClass("active"); $(this).addClass("active"); $("ul#tabs-nav li.active").removeClass("active"); $("ul#tabs-nav li:nth-child("+nthChild+")").addClass("active"); } }); }); $('ul.tabs-nav').each(function(){ // For each set of tabs, we want to keep track of // which tab is active and its associated content var $active, $content, $links = $(this).find('a'); // If the location.hash matches one of the links, use that as the active tab. // If no match is found, use the first link as the initial active tab. $active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]); // $active.addClass('active'); console.log($active) $content = $($active[0].hash); // Hide the remaining content $links.not($active).each(function () { $(this.hash).hide(); }); // Bind the click event handler $(this).on('click', 'a', function(e){ // Make the old tab inactive. // $active.removeClass('active'); $content.hide(); // Update the variables with the new link and content // $active = $(this); $content = $(this.hash); // Make the tab active. // $active.addClass('active'); $content.show(); // Prevent the anchor's default click action e.preventDefault(); }); }); </script> {% endblock %}
SkillsFundingAgency/das-alpha-ui
app/views/commitTwo/contracts/new-contract/find-provider.html
HTML
mit
3,990
class Fix < ActiveRecord::Base has_many :fix_comments belongs_to :issue belongs_to :user def package_info {id: self.id, user_id: self.user_id, user_first_name: self.user.first_name, user_last_name: self.user.last_name, issue_id: self.issue_id, title: self.title, image_url: self.image_url} end end
acoravos/metoo
app/models/fix.rb
Ruby
mit
315
{{ forms.oauth_fields( 'Google Analytics', form.analytics_id, ''' Get it from <a href="https://www.google.com/analytics/web/" target="_blank">Google Analytics</a> ''' ) }}
mdxs/gae-init-docs
main/templates/admin/bit/google_analytics_tracking_id.html
HTML
mit
218
#include "HaViMo2.h" extern Dynamixel *pDxl; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void HaViMo2_Controller::capture(void) { pDxl->writeByte(HaViMo2_ID, 0, 0); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ bool HaViMo2_Controller::ready(void) { // Ping HaViMo2 // If responds => done processing last image, get results // Else => still processing, wait/try again later pDxl->ping(HaViMo2_ID); if (pDxl->getResult()==(1<<COMM_RXSUCCESS)) { return true; } return false; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ uint8_t HaViMo2_Controller::recover(void) { hvm2rb.valid = 0; uint8_t iter; for (iter=0; iter<15; iter++) { hvm2rb.rb[iter].Index=0; hvm2rb.rb[iter].Color=0; } for (iter=0; iter<15; iter++) { pDxl->setTxPacketId(HaViMo2_ID); pDxl->setTxPacketInstruction(INST_READ); pDxl->setTxPacketParameter(0, ((iter+1)*16)); pDxl->setTxPacketParameter(1, 16); pDxl->setTxPacketLength(2); pDxl->txrxPacket(); // Dxl buffer is not cleared prior to RX // If not checking for result, will grab from last valid RX packet if ( (pDxl->getResult()==(1<<COMM_RXSUCCESS)) && (pDxl->getRxPacketLength()==(16+2)) ) { if (pDxl->getRxPacketParameter(1)>0) { hvm2rb.valid++; hvm2rb.rb[hvm2rb.valid-1].Index=pDxl->getRxPacketParameter(0); hvm2rb.rb[hvm2rb.valid-1].Color=pDxl->getRxPacketParameter(1); hvm2rb.rb[hvm2rb.valid-1].NumPix= ( (uint16_t)pDxl->getRxPacketParameter(2)+ ((uint16_t)pDxl->getRxPacketParameter(3)<<8) ); hvm2rb.rb[hvm2rb.valid-1].SumX= ( ((uint32_t)pDxl->getRxPacketParameter(4)+ ((uint32_t)pDxl->getRxPacketParameter(5)<<8)+ ((uint32_t)pDxl->getRxPacketParameter(6)<<16)) ); hvm2rb.rb[hvm2rb.valid-1].SumY= ( ((uint32_t)pDxl->getRxPacketParameter(8)+ ((uint32_t)pDxl->getRxPacketParameter(9)<<8)+ ((uint32_t)pDxl->getRxPacketParameter(10)<<16)) ); hvm2rb.rb[hvm2rb.valid-1].MaxX=pDxl->getRxPacketParameter(12); hvm2rb.rb[hvm2rb.valid-1].MinX=pDxl->getRxPacketParameter(13); hvm2rb.rb[hvm2rb.valid-1].MaxY=pDxl->getRxPacketParameter(14); hvm2rb.rb[hvm2rb.valid-1].MinY=pDxl->getRxPacketParameter(15); } } } return hvm2rb.valid; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ uint8_t HaViMo2_Controller::regions(void) { return hvm2rb.valid; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ uint8_t HaViMo2_Controller::color(uint8_t region_index) { if ( (region_index<16) && (hvm2rb.rb[region_index].Index>0) ) return hvm2rb.rb[region_index].Color; else return 0xFF; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ uint16_t HaViMo2_Controller::size(uint8_t region_index) { if ( (region_index<16) && (hvm2rb.rb[region_index].Index>0) ) return hvm2rb.rb[region_index].NumPix; else return 0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ uint8_t HaViMo2_Controller::avgX(uint8_t region_index) { if ( (region_index<16) && (hvm2rb.rb[region_index].Index>0) ) return (hvm2rb.rb[region_index].SumX / hvm2rb.rb[region_index].NumPix); else return 0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ uint8_t HaViMo2_Controller::avgY(uint8_t region_index) { if ( (region_index<16) && (hvm2rb.rb[region_index].Index>0) ) return (hvm2rb.rb[region_index].SumY / hvm2rb.rb[region_index].NumPix); else return 0; }
chcbaram/OpenCM9.04_IDE_1.5
hardware/robotis/OpenCM9.04/libraries/HaViMo2/HaViMo2.cpp
C++
mit
3,618
--- layout: post author: "Matt Davis" title: "Workshops for Companies" date: 2015-04-09 time: "16:00:00" category: ["Workshops"] --- <p> At our March 12, 2015 meeting, the Software Carpentry Foundation Steering Committee discussed whether and under what terms to provide workshops to for-profit corporations. There were no objections to the idea of doing workshops for corporations, but it is something new to Software Carpentry. We've decided to run a pilot program encompassing five corporate workshops so we can learn more about working with corporations. The pilot program will allow us to gauge corporate interest and collect feedback from instructors, coordinators, and others about how things go. </p> <!--more--> <p> Workshops at companies will be run on these terms: </p> <ol> <li> Hosts will pay $5000 for their first workshop and $3000 for subsequent workshops. </li> <li> As with our other workshops, instructors will be volunteers and their travel expenses will be covered by hosts. </li> <li> Three-quarters of the money directed to the SCF will be used to underwrite administrative fees for non-profit organizations. </li> <li> Fee waivers/discounts will be available to corporations on a case-by-case basis just as with non-profit organizations. </li> </ol> <p> The third point is probably the most important: each workshop at a company will effectively pay the administration fee for three workshops at universities, for under-represented groups, etc. </p> <p> We have updated <a href="{{site.baseurl}}/workshops/request/">our workshop request form</a> to reflect this new policy. At the end of the pilot program the Steering Committee will consider whether to continue doing workshops for for-profit entities, taking into account such factors as whether the instructors, coordinators, and students involved had positive experiences, and whether there seems likely to be continued interest from corporations. The Steering Committee may also elect to change the terms under which corporate workshops are provided. (Because it has already been arranged, the upcoming workshop at Monsanto will pay the lower administrative fee of $1250, but it will count toward the five-workshop sample for the pilot program.) </p> <p> Thank you to everyone in our community for sharing their perspectives on this matter&mdash;we'll report back on the pilot's progress as soon as we can. Until then, if you know of a company that would be interested in hosting a workshop, we'd be grateful for an introduction. </p>
FranciscoCanas/website
_posts/2015/04/2015-04-09-workshops-for-companies.html
HTML
mit
2,616
using System.Collections.Generic; using System.Data; using System.Web.Mvc; using Microsoft.Reporting.WebForms; namespace MvcReportViewer { public static class ReportRunnerExtensions { /// <summary> /// Creates a FileContentResult object by using Report Viewer Web Control. /// </summary> /// <param name="controller">The Controller instance that this method extends.</param> /// <param name="reportFormat">Report Viewer Web Control supported format (Excel, Word, PDF or Image)</param> /// <param name="reportPath">The path to the report on the server.</param> /// <param name="mode">Report processing mode: remote or local.</param> /// <param name="localReportDataSources">Local report data sources</param> /// <param name="filename">Output filename</param> /// <returns>The file-content result object.</returns> public static FileStreamResult Report( this Controller controller, ReportFormat reportFormat, string reportPath, ProcessingMode mode = ProcessingMode.Remote, IDictionary<string, DataTable> localReportDataSources = null, string filename = null) { var reportRunner = new ReportRunner(reportFormat, reportPath, mode, localReportDataSources, filename); return reportRunner.Run(); } /// <summary> /// Creates a FileContentResult object by using Report Viewer Web Control. /// </summary> /// <param name="controller">The Controller instance that this method extends.</param> /// <param name="reportFormat">Report Viewer Web Control supported format (Excel, Word, PDF or Image)</param> /// <param name="reportPath">The path to the report on the server.</param> /// <param name="reportParameters">The report parameter properties for the report.</param> /// <param name="mode">Report processing mode: remote or local.</param> /// <param name="localReportDataSources">Local report data sources</param> /// <param name="filename">Output filename</param> /// <returns>The file-content result object.</returns> public static FileStreamResult Report( this Controller controller, ReportFormat reportFormat, string reportPath, object reportParameters, ProcessingMode mode = ProcessingMode.Remote, IDictionary<string, DataTable> localReportDataSources = null, string filename = null) { var reportRunner = new ReportRunner( reportFormat, reportPath, HtmlHelper.AnonymousObjectToHtmlAttributes(reportParameters), mode, localReportDataSources, filename); return reportRunner.Run(); } /// <summary> /// Creates a FileContentResult object by using Report Viewer Web Control. /// </summary> /// <param name="controller">The Controller instance that this method extends.</param> /// <param name="reportFormat">Report Viewer Web Control supported format (Excel, Word, PDF or Image)</param> /// <param name="reportPath">The path to the report on the server.</param> /// <param name="reportParameters">The report parameter properties for the report.</param> /// <param name="mode">Report processing mode: remote or local.</param> /// <param name="localReportDataSources">Local report data sources</param> /// <param name="filename">Output filename</param> /// <returns>The file-content result object.</returns> public static FileStreamResult Report( this Controller controller, ReportFormat reportFormat, string reportPath, IEnumerable<KeyValuePair<string, object>> reportParameters, ProcessingMode mode = ProcessingMode.Remote, IDictionary<string, DataTable> localReportDataSources = null, string filename = null) { var reportRunner = new ReportRunner( reportFormat, reportPath, reportParameters, mode, localReportDataSources, filename); return reportRunner.Run(); } /// <summary> /// Creates a FileContentResult object by using Report Viewer Web Control. /// </summary> /// <param name="controller">The Controller instance that this method extends.</param> /// <param name="reportFormat">Report Viewer Web Control supported format (Excel, Word, PDF or Image)</param> /// <param name="reportPath">The path to the report on the server.</param> /// <param name="reportServerUrl">The URL for the report server.</param> /// <param name="username">The report server username.</param> /// <param name="password">The report server password.</param> /// <param name="reportParameters">The report parameter properties for the report.</param> /// <param name="mode">Report processing mode: remote or local.</param> /// <param name="localReportDataSources">Local report data sources</param> /// <param name="filename">Output filename</param> /// <returns>The file-content result object.</returns> public static FileStreamResult Report( this Controller controller, ReportFormat reportFormat, string reportPath, string reportServerUrl, string username = null, string password = null, object reportParameters = null, ProcessingMode mode = ProcessingMode.Remote, IDictionary<string, DataTable> localReportDataSources = null, string filename = null) { var reportRunner = new ReportRunner( reportFormat, reportPath, reportServerUrl, username, password, HtmlHelper.AnonymousObjectToHtmlAttributes(reportParameters), mode, localReportDataSources, filename); return reportRunner.Run(); } /// <summary> /// Creates a FileContentResult object by using Report Viewer Web Control. /// </summary> /// <param name="controller">The Controller instance that this method extends.</param> /// <param name="reportFormat">Report Viewer Web Control supported format (Excel, Word, PDF or Image)</param> /// <param name="reportPath">The path to the report on the server.</param> /// <param name="reportServerUrl">The URL for the report server.</param> /// <param name="reportParameters">The report parameter properties for the report.</param> /// <param name="username">The report server username.</param> /// <param name="password">The report server password.</param> /// <param name="mode">Report processing mode: remote or local.</param> /// <param name="localReportDataSources">Local report data sources</param> /// <param name="filename">Output filename</param> /// <returns>The file-content result object.</returns> public static FileStreamResult Report( this Controller controller, ReportFormat reportFormat, string reportPath, string reportServerUrl, IEnumerable<KeyValuePair<string, object>> reportParameters, string username = null, string password = null, ProcessingMode mode = ProcessingMode.Remote, IDictionary<string, DataTable> localReportDataSources = null, string filename = null) { var reportRunner = new ReportRunner( reportFormat, reportPath, reportServerUrl, username, password, reportParameters, mode, localReportDataSources, filename); return reportRunner.Run(); } } }
codedecay/MvcReportViewer
MvcReportViewer/ReportRunnerExtensions.cs
C#
mit
8,426
## ## function(atom_to_literal_assignments f atom_assignments) map_import_properties(${f} atom_index_map atom_literal_identity_map atom_literal_negated_map) map_keys(${atom_assignments}) ans(atoms) map_new() ans(result) foreach(atom ${atoms}) map_tryget(${atom_index_map} ${atom}) ans(ai) map_tryget(${atom_literal_identity_map} ${ai}) ans(li) map_tryget(${atom_literal_negated_map} ${ai}) ans(li_negated) map_tryget(${atom_assignments} ${atom}) ans(value) eval_truth(NOT value) ans(value_negated) map_set(${result} ${li} ${value}) map_set(${result} ${li_negated} ${value_negated}) endforeach() return_ref(result) endfunction()
tempbottle/cmakepp
cmake/sat/utilities/atom_to_literal_assignments.cmake
CMake
mit
693
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.vision.customvision.training.models; import java.util.UUID; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * The ImageIdCreateEntry model. */ public class ImageIdCreateEntry { /** * Id of the image. */ @JsonProperty(value = "id") private UUID id; /** * The tagIds property. */ @JsonProperty(value = "tagIds") private List<UUID> tagIds; /** * The regions property. */ @JsonProperty(value = "regions") private List<Region> regions; /** * Get the id value. * * @return the id value */ public UUID id() { return this.id; } /** * Set the id value. * * @param id the id value to set * @return the ImageIdCreateEntry object itself. */ public ImageIdCreateEntry withId(UUID id) { this.id = id; return this; } /** * Get the tagIds value. * * @return the tagIds value */ public List<UUID> tagIds() { return this.tagIds; } /** * Set the tagIds value. * * @param tagIds the tagIds value to set * @return the ImageIdCreateEntry object itself. */ public ImageIdCreateEntry withTagIds(List<UUID> tagIds) { this.tagIds = tagIds; return this; } /** * Get the regions value. * * @return the regions value */ public List<Region> regions() { return this.regions; } /** * Set the regions value. * * @param regions the regions value to set * @return the ImageIdCreateEntry object itself. */ public ImageIdCreateEntry withRegions(List<Region> regions) { this.regions = regions; return this; } }
selvasingh/azure-sdk-for-java
sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateEntry.java
Java
mit
2,042
import unittest import numpy import chainer from chainer.backends import cuda from chainer import gradient_check from chainer import links from chainer import testing from chainer.testing import attr from chainer.testing import condition @testing.with_requires('theano') class TheanoFunctionTestBase(object): forward_test_options = {} backward_test_options = {'atol': 1e-4} def setUp(self): self.input_data = [ numpy.random.uniform( -1, 1, d['shape']).astype(getattr(numpy, d['type'])) for d in self.inputs] self.grad_data = [ numpy.random.uniform( -1, 1, d['shape']).astype(getattr(numpy, d['type'])) for d in self.outputs] def make_func(self): raise NotImplementedError def expect_forward(self): raise NotImplementedError def check_forward(self, input_data): func = self.make_func() inputs = [chainer.Variable(data) for data in input_data] outputs = func(*inputs) if isinstance(outputs, chainer.Variable): outputs = (outputs,) expect = self.expect_forward() self.assertEqual(len(outputs), len(expect)) for o, e in zip(outputs, expect): testing.assert_allclose( o.data, e, **self.forward_test_options) def test_forward_cpu(self): self.check_forward(self.input_data) @attr.gpu def test_forward_gpu(self): inputs = [cuda.to_gpu(x) for x in self.input_data] self.check_forward(inputs) def check_backward(self, input_data, grad_data): func = self.make_func() gradient_check.check_backward( func, input_data, grad_data, **self.backward_test_options) @condition.retry(3) def test_backward_cpu(self): self.check_backward(self.input_data, self.grad_data) @attr.gpu @condition.retry(3) def test_backward_gpu(self): inputs = [cuda.to_gpu(x) for x in self.input_data] grads = [cuda.to_gpu(x) for x in self.grad_data] self.check_backward(inputs, grads) @testing.parameterize( {'inputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (3, 2), 'type': 'float32'}], 'outputs': [{'shape': (3, 2), 'type': 'float32'}]}, {'inputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (2,), 'type': 'float32'}], 'outputs': [{'shape': (3, 2), 'type': 'float32'}]}, {'inputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (), 'type': 'float32'}], 'outputs': [{'shape': (3, 2), 'type': 'float32'}]}, {'inputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (3, 2), 'type': 'float64'}], 'outputs': [{'shape': (3, 2), 'type': 'float64'}]}, {'inputs': [{'shape': (3, 2), 'type': 'float16'}, {'shape': (3, 2), 'type': 'float32'}], 'outputs': [{'shape': (3, 2), 'type': 'float32'}], 'forward_test_options': {'atol': 1e-3, 'rtol': 1e-3}, 'backward_test_options': {'eps': 1, 'atol': 1e-3, 'rtol': 1e-3}}, ) class TestTheanoFunction(TheanoFunctionTestBase, unittest.TestCase): def make_func(self): import theano.tensor as T x = T.TensorType(self.inputs[0]['type'], (False,) * len(self.inputs[0]['shape']))('x') y = T.TensorType(self.inputs[1]['type'], (False,) * len(self.inputs[1]['shape']))('y') z = x + y return links.TheanoFunction([x, y], [z]) def expect_forward(self): x, y = self.input_data return x + y, @testing.parameterize( {'inputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (3, 2), 'type': 'float32'}], 'outputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (3, 2), 'type': 'float32'}]}, {'inputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (2,), 'type': 'float32'}], 'outputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (3, 2), 'type': 'float32'}]}, {'inputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (), 'type': 'float32'}], 'outputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (3, 2), 'type': 'float32'}]}, ) class TestTheanoFunctionTwoOutputs(TheanoFunctionTestBase, unittest.TestCase): def make_func(self): import theano.tensor as T x = T.TensorType(self.inputs[0]['type'], (False,) * len(self.inputs[0]['shape']))('x') y = T.TensorType(self.inputs[1]['type'], (False,) * len(self.inputs[1]['shape']))('y') z = x + y w = x - y return links.TheanoFunction([x, y], [z, w]) def expect_forward(self): x, y = self.input_data return x + y, x - y @testing.parameterize( {'inputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (2,), 'type': 'int32'}], 'outputs': [{'shape': (2, 2), 'type': 'float32'}]}, {'inputs': [{'shape': (3, 2), 'type': 'float32'}, {'shape': (), 'type': 'int32'}], 'outputs': [{'shape': (2,), 'type': 'float32'}]}, ) class TestTheanoFunctionNonDifferential( TheanoFunctionTestBase, unittest.TestCase): def make_func(self): import theano.tensor as T x = T.TensorType(self.inputs[0]['type'], (False,) * len(self.inputs[0]['shape']))('x') i = T.TensorType(self.inputs[1]['type'], (False,) * len(self.inputs[1]['shape']))('y') z = x[i] return links.TheanoFunction([x, i], z) def expect_forward(self): x, i = self.input_data return x[i], testing.run_module(__name__, __file__)
aonotas/chainer
tests/chainer_tests/links_tests/theano_tests/test_theano_function.py
Python
mit
5,778
module.exports = { description: 'auto-indents with indent: true', options: { moduleName: 'foo', indent: true } };
lukeapage/rollup
test/form/indent-true/_config.js
JavaScript
mit
121
TEST('GRAPHICSMAGICK_READ_METADATA', (check) => { GRAPHICSMAGICK_READ_METADATA('UPPERCASE-CORE/sample.png', (metadata) => { console.log(metadata); }); GRAPHICSMAGICK_READ_METADATA('UPPERCASE-CORE/sample.png', { error : () => { console.log('ERROR!'); }, success : (metadata) => { console.log(metadata); } }); });
Hanul/UPPERCASE
node_modules/ubm/node_modules/uppercase-core/TEST/NODE/GRAPHICSMAGICK/GRAPHICSMAGICK_READ_METADATA.js
JavaScript
mit
334
/** * Created by Pencroff on 04-Sep-16. */ window.test = { id: '384A61CA-DA2E-4FD2-A113-080010D4A42B', name: 'object literal iteration', description: 'Performance case for iteration object properties. Comparison for StackOverflow question: How do I loop through or enumerate a JavaScript object? (<a href=\"https://goo.gl/0QEGHB\" target=\"_blank\">link</a>)', tags: ['object', 'iteration', 'basic'], url: 'tests/object-iteration.js', fill: function (suite) { return new Promise(function (resolve) { var result, a, b, c; var obj; suite.add('by Object.keys', function () { result = ''; var arr = Object.keys(obj); var len = arr.length; var i, key; for (i = 0; i < len; i += 1) { key = arr[i]; result += key + ': ' + obj[key] + ' '; } a = b; b = c; c = result; }); suite.add('by Object.keys with native forEach', function () { result = ''; Object.keys(obj).forEach(function(key) { result += key + ': ' + obj[key] + ' '; }); a = b; b = c; c = result; }); suite.add('by for..in', function () { result = ''; for (var key in obj) { result += key + ': ' + obj[key] + ' '; } a = b; b = c; c = result; }); suite.add('by for..in and hasOwnProperty', function () { result = ''; for (var key in obj) { if (obj.hasOwnProperty(key)) { result += key + ': ' + obj[key] + ' '; } } a = b; b = c; c = result; }); suite.add('lodash v4.15.0 - _.forEach', function () { result = ''; _.forEach(obj, function (value, key) { result += key + ': ' + value + ' '; }); a = b; b = c; c = result; }); suite.on('start cycle', function () { var len = 100; var i; obj = {}; for (i = 0; i < len; i += 1) { obj['prop'+i] = 'value' + i; } }); suite.on('cycle', function () { console.log('cycle', result); }); resolve(suite); }); } };
Pencroff/PerfJS
origin/tests/object-iteration.js
JavaScript
mit
2,756
<?php /* * WellCommerce Open-Source E-Commerce Platform * * This file is part of the WellCommerce package. * * (c) Adam Piotrowski <adam@wellcommerce.org> * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ namespace WellCommerce\Bundle\AppBundle\DataGrid; use WellCommerce\Bundle\CoreBundle\DataGrid\AbstractDataGrid; use WellCommerce\Component\DataGrid\Column\Column; use WellCommerce\Component\DataGrid\Column\ColumnCollection; use WellCommerce\Component\DataGrid\Column\ColumnInterface; use WellCommerce\Component\DataGrid\Column\Options\Appearance; use WellCommerce\Component\DataGrid\Column\Options\Filter; use WellCommerce\Component\DataGrid\Column\Options\Sorting; /** * Class UserGroupDataGrid * * @author Adam Piotrowski <adam@wellcommerce.org> */ class UserGroupDataGrid extends AbstractDataGrid { public function configureColumns(ColumnCollection $collection) { $collection->add(new Column([ 'id' => 'id', 'caption' => 'common.label.id', 'sorting' => new Sorting([ 'default_order' => ColumnInterface::SORT_DIR_DESC, ]), 'appearance' => new Appearance([ 'width' => 90, 'visible' => false, ]), 'filter' => new Filter([ 'type' => Filter::FILTER_BETWEEN, ]), ])); $collection->add(new Column([ 'id' => 'name', 'caption' => 'common.label.name', ])); } public function getIdentifier(): string { return 'user_group'; } }
diversantvlz/WellCommerce
src/WellCommerce/Bundle/AppBundle/DataGrid/UserGroupDataGrid.php
PHP
mit
1,707
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Socket, Server as NetServer, createConnection, createServer } from 'net'; import { Event, Emitter } from 'vs/base/common/event'; import { ClientConnectionEvent, IPCServer } from 'vs/base/parts/ipc/common/ipc'; import { join } from 'vs/base/common/path'; import { tmpdir } from 'os'; import { generateUuid } from 'vs/base/common/uuid'; import { IDisposable, Disposable } from 'vs/base/common/lifecycle'; import { VSBuffer } from 'vs/base/common/buffer'; import { ISocket, Protocol, Client, ChunkStream } from 'vs/base/parts/ipc/common/ipc.net'; export class NodeSocket implements ISocket { public readonly socket: Socket; constructor(socket: Socket) { this.socket = socket; } public dispose(): void { this.socket.destroy(); } public onData(_listener: (e: VSBuffer) => void): IDisposable { const listener = (buff: Buffer) => _listener(VSBuffer.wrap(buff)); this.socket.on('data', listener); return { dispose: () => this.socket.off('data', listener) }; } public onClose(listener: () => void): IDisposable { this.socket.on('close', listener); return { dispose: () => this.socket.off('close', listener) }; } public onEnd(listener: () => void): IDisposable { this.socket.on('end', listener); return { dispose: () => this.socket.off('end', listener) }; } public write(buffer: VSBuffer): void { // return early if socket has been destroyed in the meantime if (this.socket.destroyed) { return; } // we ignore the returned value from `write` because we would have to cached the data // anyways and nodejs is already doing that for us: // > https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback // > However, the false return value is only advisory and the writable stream will unconditionally // > accept and buffer chunk even if it has not been allowed to drain. this.socket.write(<Buffer>buffer.buffer); } public end(): void { this.socket.end(); } } const enum Constants { MinHeaderByteSize = 2 } const enum ReadState { PeekHeader = 1, ReadHeader = 2, ReadBody = 3, Fin = 4 } /** * See https://tools.ietf.org/html/rfc6455#section-5.2 */ export class WebSocketNodeSocket extends Disposable implements ISocket { public readonly socket: NodeSocket; private readonly _incomingData: ChunkStream; private readonly _onData = this._register(new Emitter<VSBuffer>()); private readonly _state = { state: ReadState.PeekHeader, readLen: Constants.MinHeaderByteSize, mask: 0 }; constructor(socket: NodeSocket) { super(); this.socket = socket; this._incomingData = new ChunkStream(); this._register(this.socket.onData(data => this._acceptChunk(data))); } public dispose(): void { this.socket.dispose(); } public onData(listener: (e: VSBuffer) => void): IDisposable { return this._onData.event(listener); } public onClose(listener: () => void): IDisposable { return this.socket.onClose(listener); } public onEnd(listener: () => void): IDisposable { return this.socket.onEnd(listener); } public write(buffer: VSBuffer): void { let headerLen = Constants.MinHeaderByteSize; if (buffer.byteLength < 126) { headerLen += 0; } else if (buffer.byteLength < 2 ** 16) { headerLen += 2; } else { headerLen += 8; } const header = VSBuffer.alloc(headerLen); header.writeUInt8(0b10000010, 0); if (buffer.byteLength < 126) { header.writeUInt8(buffer.byteLength, 1); } else if (buffer.byteLength < 2 ** 16) { header.writeUInt8(126, 1); let offset = 1; header.writeUInt8((buffer.byteLength >>> 8) & 0b11111111, ++offset); header.writeUInt8((buffer.byteLength >>> 0) & 0b11111111, ++offset); } else { header.writeUInt8(127, 1); let offset = 1; header.writeUInt8(0, ++offset); header.writeUInt8(0, ++offset); header.writeUInt8(0, ++offset); header.writeUInt8(0, ++offset); header.writeUInt8((buffer.byteLength >>> 24) & 0b11111111, ++offset); header.writeUInt8((buffer.byteLength >>> 16) & 0b11111111, ++offset); header.writeUInt8((buffer.byteLength >>> 8) & 0b11111111, ++offset); header.writeUInt8((buffer.byteLength >>> 0) & 0b11111111, ++offset); } this.socket.write(VSBuffer.concat([header, buffer])); } public end(): void { this.socket.end(); } private _acceptChunk(data: VSBuffer): void { if (data.byteLength === 0) { return; } this._incomingData.acceptChunk(data); while (this._incomingData.byteLength >= this._state.readLen) { if (this._state.state === ReadState.PeekHeader) { // peek to see if we can read the entire header const peekHeader = this._incomingData.peek(this._state.readLen); // const firstByte = peekHeader.readUInt8(0); // const finBit = (firstByte & 0b10000000) >>> 7; const secondByte = peekHeader.readUInt8(1); const hasMask = (secondByte & 0b10000000) >>> 7; const len = (secondByte & 0b01111111); this._state.state = ReadState.ReadHeader; this._state.readLen = Constants.MinHeaderByteSize + (hasMask ? 4 : 0) + (len === 126 ? 2 : 0) + (len === 127 ? 8 : 0); this._state.mask = 0; } else if (this._state.state === ReadState.ReadHeader) { // read entire header const header = this._incomingData.read(this._state.readLen); const secondByte = header.readUInt8(1); const hasMask = (secondByte & 0b10000000) >>> 7; let len = (secondByte & 0b01111111); let offset = 1; if (len === 126) { len = ( header.readUInt8(++offset) * 2 ** 8 + header.readUInt8(++offset) ); } else if (len === 127) { len = ( header.readUInt8(++offset) * 0 + header.readUInt8(++offset) * 0 + header.readUInt8(++offset) * 0 + header.readUInt8(++offset) * 0 + header.readUInt8(++offset) * 2 ** 24 + header.readUInt8(++offset) * 2 ** 16 + header.readUInt8(++offset) * 2 ** 8 + header.readUInt8(++offset) ); } let mask = 0; if (hasMask) { mask = ( header.readUInt8(++offset) * 2 ** 24 + header.readUInt8(++offset) * 2 ** 16 + header.readUInt8(++offset) * 2 ** 8 + header.readUInt8(++offset) ); } this._state.state = ReadState.ReadBody; this._state.readLen = len; this._state.mask = mask; } else if (this._state.state === ReadState.ReadBody) { // read body const body = this._incomingData.read(this._state.readLen); unmask(body, this._state.mask); this._state.state = ReadState.PeekHeader; this._state.readLen = Constants.MinHeaderByteSize; this._state.mask = 0; this._onData.fire(body); } } } } function unmask(buffer: VSBuffer, mask: number): void { if (mask === 0) { return; } let cnt = buffer.byteLength >>> 2; for (let i = 0; i < cnt; i++) { const v = buffer.readUInt32BE(i * 4); buffer.writeUInt32BE(v ^ mask, i * 4); } let offset = cnt * 4; let bytesLeft = buffer.byteLength - offset; const m3 = (mask >>> 24) & 0b11111111; const m2 = (mask >>> 16) & 0b11111111; const m1 = (mask >>> 8) & 0b11111111; if (bytesLeft >= 1) { buffer.writeUInt8(buffer.readUInt8(offset) ^ m3, offset); } if (bytesLeft >= 2) { buffer.writeUInt8(buffer.readUInt8(offset + 1) ^ m2, offset + 1); } if (bytesLeft >= 3) { buffer.writeUInt8(buffer.readUInt8(offset + 2) ^ m1, offset + 2); } } export function generateRandomPipeName(): string { const randomSuffix = generateUuid(); if (process.platform === 'win32') { return `\\\\.\\pipe\\vscode-ipc-${randomSuffix}-sock`; } else { // Mac/Unix: use socket file return join(tmpdir(), `vscode-ipc-${randomSuffix}.sock`); } } export class Server extends IPCServer { private static toClientConnectionEvent(server: NetServer): Event<ClientConnectionEvent> { const onConnection = Event.fromNodeEventEmitter<Socket>(server, 'connection'); return Event.map(onConnection, socket => ({ protocol: new Protocol(new NodeSocket(socket)), onDidClientDisconnect: Event.once(Event.fromNodeEventEmitter<void>(socket, 'close')) })); } private server: NetServer | null; constructor(server: NetServer) { super(Server.toClientConnectionEvent(server)); this.server = server; } dispose(): void { super.dispose(); if (this.server) { this.server.close(); this.server = null; } } } export function serve(port: number): Promise<Server>; export function serve(namedPipe: string): Promise<Server>; export function serve(hook: any): Promise<Server> { return new Promise<Server>((c, e) => { const server = createServer(); server.on('error', e); server.listen(hook, () => { server.removeListener('error', e); c(new Server(server)); }); }); } export function connect(options: { host: string, port: number }, clientId: string): Promise<Client>; export function connect(port: number, clientId: string): Promise<Client>; export function connect(namedPipe: string, clientId: string): Promise<Client>; export function connect(hook: any, clientId: string): Promise<Client> { return new Promise<Client>((c, e) => { const socket = createConnection(hook, () => { socket.removeListener('error', e); c(Client.fromSocket(new NodeSocket(socket), clientId)); }); socket.once('error', e); }); }
the-ress/vscode
src/vs/base/parts/ipc/node/ipc.net.ts
TypeScript
mit
9,530
<?php /** * This file is part of the Liquid package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @package Liquid */ namespace Liquid\Cache; use Liquid\TestCase; class FileTest extends TestCase { /** @var \Liquid\Cache\File */ protected $cache; protected $cacheDir; protected function setUp() { parent::setUp(); $this->cacheDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'cache_dir'; $this->cache = new File(array('cache_dir' => $this->cacheDir)); } protected function tearDown() { parent::tearDown(); // Remove tmp cache files array_map('unlink', glob($this->cacheDir . DIRECTORY_SEPARATOR . '*')); } /** * @expectedException \Liquid\LiquidException */ public function testConstructInvalidOptions() { new File(); } /** * @expectedException \Liquid\LiquidException */ public function testConstructNoSuchDirOrNotWritable() { new File(array('cache_dir' => '/no/such/dir/liquid/cache')); } public function testGetExistsNoFile() { $this->assertFalse($this->cache->exists('no_key')); } public function testGetExistsExpired() { $key = 'test'; $cacheFile = $this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_' . $key; touch($cacheFile, time() - 1000000); // long ago $this->assertFalse($this->cache->exists($key)); } public function testGetExistsNotExpired() { $key = 'test'; $cacheFile = $this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_' . $key; touch($cacheFile); $this->assertTrue($this->cache->exists($key)); } public function testFlushAll() { touch($this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_test'); touch($this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_test_two'); $this->assertCount(2, glob($this->cacheDir . DIRECTORY_SEPARATOR . '*')); $this->cache->flush(); $this->assertCount(0, glob($this->cacheDir . DIRECTORY_SEPARATOR . '*')); } public function testFlushExpired() { touch($this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_test'); touch($this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_test_two', time() - 1000000); $this->assertCount(2, glob($this->cacheDir . DIRECTORY_SEPARATOR . '*')); $this->cache->flush(true); $this->assertCount(1, glob($this->cacheDir . DIRECTORY_SEPARATOR . '*')); } public function testWriteNoSerialize() { $key = 'test'; $value = 'test_value'; $this->assertTrue($this->cache->write($key, $value, false)); $this->assertEquals($value, file_get_contents($this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_' . $key)); } public function testWriteSerialized() { $key = 'test'; $value = 'test_value'; $this->assertTrue($this->cache->write($key, $value)); $this->assertEquals(serialize($value), file_get_contents($this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_' . $key)); } public function testWriteGc() { $key = 'test'; $value = 'test_value'; // This cache file must be removed by GC touch($this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_test_two', time() - 1000000); $this->assertTrue($this->cache->write($key, $value, false)); $this->assertCount(1, glob($this->cacheDir . DIRECTORY_SEPARATOR . '*')); } public function testReadNonExisting() { $this->assertFalse($this->cache->read('no_such_key')); } public function testReadNoUnserialize() { $key = 'test'; $value = 'test_value'; file_put_contents($this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_' . $key, $value); $this->assertSame($value, $this->cache->read($key, false)); } public function testReadSerialize() { $key = 'test'; $value = 'test_value'; file_put_contents($this->cacheDir . DIRECTORY_SEPARATOR . 'liquid_' . $key, serialize($value)); $this->assertSame($value, $this->cache->read($key)); } }
claudinec/energyfreedom-pledge
vendor/liquid/liquid/tests/Liquid/Cache/FileTest.php
PHP
mit
3,777
<?php namespace net\authorize\api\contract\v1; /** * Class representing CreateCustomerPaymentProfileRequest */ class CreateCustomerPaymentProfileRequest extends ANetApiRequestType { /** * @property string $customerProfileId */ private $customerProfileId = null; /** * @property \net\authorize\api\contract\v1\CustomerPaymentProfileType * $paymentProfile */ private $paymentProfile = null; /** * @property string $validationMode */ private $validationMode = null; /** * Gets as customerProfileId * * @return string */ public function getCustomerProfileId() { return $this->customerProfileId; } /** * Sets a new customerProfileId * * @param string $customerProfileId * @return self */ public function setCustomerProfileId($customerProfileId) { $this->customerProfileId = $customerProfileId; return $this; } /** * Gets as paymentProfile * * @return \net\authorize\api\contract\v1\CustomerPaymentProfileType */ public function getPaymentProfile() { return $this->paymentProfile; } /** * Sets a new paymentProfile * * @param \net\authorize\api\contract\v1\CustomerPaymentProfileType $paymentProfile * @return self */ public function setPaymentProfile(\net\authorize\api\contract\v1\CustomerPaymentProfileType $paymentProfile) { $this->paymentProfile = $paymentProfile; return $this; } /** * Gets as validationMode * * @return string */ public function getValidationMode() { return $this->validationMode; } /** * Sets a new validationMode * * @param string $validationMode * @return self */ public function setValidationMode($validationMode) { $this->validationMode = $validationMode; return $this; } }
hyrmedia/builderengine
modules/builderpayment/controllers/authorizelib/lib/net/authorize/api/contract/v1/CreateCustomerPaymentProfileRequest.php
PHP
mit
2,070
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\View\Helper; /** * Helper for rendering a template fragment in its own variable scope; iterates * over data provided and renders for each iteration. * * @uses \Zend\View\Helper\Partial\Partial * @uses \Zend\View\Helper\Partial\Exception * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PartialLoop extends Partial { /** * Marker to where the pointer is at in the loop * @var integer */ protected $partialCounter = 0; /** * Renders a template fragment within a variable scope distinct from the * calling View object. * * If no arguments are provided, returns object instance. * * @param string $name Name of view script * @param string|array $module If $model is empty, and $module is an array, * these are the variables to populate in the * view. Otherwise, the module in which the * partial resides * @param array $model Variables to populate in the view * @return string */ public function direct($name = null, $module = null, $model = null) { if (0 == func_num_args()) { return $this; } if ((null === $model) && (null !== $module)) { $model = $module; $module = null; } if (!is_array($model) && (!$model instanceof \Traversable) && (is_object($model) && !method_exists($model, 'toArray')) ) { $e = new Partial\Exception('PartialLoop helper requires iterable data'); $e->setView($this->view); throw $e; } if (is_object($model) && (!$model instanceof \Traversable) && method_exists($model, 'toArray') ) { $model = $model->toArray(); } $content = ''; // reset the counter if it's call again $this->partialCounter = 0; foreach ($model as $item) { // increment the counter variable $this->partialCounter++; $content .= parent::direct($name, $module, $item); } return $content; } }
phphatesme/LiveTest
src/lib/Zend/View/Helper/PartialLoop.php
PHP
mit
3,106
package com.voxelwind.server.network.util; import com.google.common.base.Charsets; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import static org.junit.Assert.assertEquals; public class CompressionUtilTest { @org.junit.Test public void fullTest() throws Exception { ByteBuf toCompress = Unpooled.directBuffer(); toCompress.writeBytes("Voxelwind test".getBytes(Charsets.UTF_8)); ByteBuf asCompressed = CompressionUtil.deflate(toCompress); ByteBuf asUncompressed = CompressionUtil.inflate(asCompressed); // Reader index will be incorrect. This is intentional, so fix it. toCompress.readerIndex(0); assertEquals("Data did not properly decompress", toCompress, asUncompressed); toCompress.release(); asCompressed.release(); asUncompressed.release(); } }
minecrafter/voxelwind
server/src/test/java/com/voxelwind/server/network/util/CompressionUtilTest.java
Java
mit
868
(function(){ up.Font = Font; up.Font.NORMAL = "normal"; up.Font.ITALIC = "italic"; up.Font.OBLIQUE = "oblique"; up.Font.BOLD = "bold"; up.Font.SMALL_CAPS = "small-caps"; function Font(_family, _size, _lineHeight, _style, _weight, _variant){ this.family = "Arial"; this.size = 12; this.lineHeight = 12; this.style = up.Font.NORMAL; this.variant = up.Font.NORMAL; this.weight = up.Font.NORMAL; if(_family!=null) this.family = _family; if(_size!=null) this.size = _size; if(_lineHeight!=null) this.lineHeight = _lineHeight; else this.lineHeight = this.size; if(_style!=null) this.style = _style; if(_weight!=null) this.weight = _weight; if(_variant!=null) this.variant = _variant; }//constructor Font.prototype.toCssString = function(){ return this.style+' '+this.variant+' '+this.weight+' '+this.size+'px/'+this.lineHeight+'px '+this.family+' '; }//toCssString Font.loadFont = function(_name, _url){ var fontFace = "@font-face {"+ "font-family: '"+_name+"';"+ "src: url('"+_url+"/"+_name+".ttf') format('truetype');"+ "}"; var styleNode = document.createElement('style'); styleNode.type = "text/css"; if(styleNode.styleSheet){ styleNode.styleSheet.cssText = fontFace; }else{ styleNode.appendChild(document.createTextNode(fontFace)); } document.head.appendChild(styleNode); }//loadFont })();
cark1/_up_old
textViewObjects/Font.js
JavaScript
mit
1,526
<?php declare(strict_types=1); namespace Room11\Jeeves\Plugins; use Amp\Artax\FormBody; use Amp\Artax\HttpClient; use Amp\Artax\Request as HttpRequest; use Amp\Artax\Response as HttpResponse; use Amp\Artax\Uri; use Amp\Deferred; use Amp\Pause; use Amp\Promise; use Amp\Promisor; use Amp\Success; use Ds\Queue; use Room11\Jeeves\Chat\Command; use Room11\Jeeves\System\PluginCommandEndpoint; use Room11\StackChat\Client\Client as ChatClient; use Room11\StackChat\Client\PostFlags; use Room11\StackChat\Entities\PostedMessage; use function Amp\resolve; class EvalCode extends BasePlugin { // limit the number of requests while polling for results private const POLL_REQUEST_LIMIT = 20; private const POLL_INTERVAL_MS = 3500; private const BASE_URL = 'https://3v4l.org'; private const POST_FLAGS = PostFlags::SINGLE_LINE; private $chatClient; private $httpClient; private $queue; private $haveLoop = false; public function __construct(ChatClient $chatClient, HttpClient $httpClient) { $this->chatClient = $chatClient; $this->httpClient = $httpClient; $this->queue = new Queue; } private function normalizeCode($code) { if (strpos($code, '<?php') === false && strpos($code, '<?=') === false) { $code = "<?php {$code}"; } return $code . ';'; } private function pollUntilDone(string $url, PostedMessage $firstMessage, string $firstMessageText) { $request = (new HttpRequest) ->setUri($url) ->setHeader("Accept", "application/json") ; $postedMessages = [[$firstMessage, $firstMessageText]]; $room = $firstMessage->getRoom(); $pauseDuration = self::POLL_INTERVAL_MS; $requests = 0; do { if ($pauseDuration > 0) { yield new Pause($pauseDuration); } /** @var HttpResponse $result */ $result = yield $this->httpClient->request($request); $parsedResult = json_try_decode($result->getBody(), true); $messages = []; for ($i = 0; isset($parsedResult['output'][$i]) && $i < 4; $i++) { $messages[$i] = $this->generateMessageFromOutput($parsedResult['output'][$i], $url); } $actionStart = microtime(true); foreach ($messages as $i => $text) { if (!isset($postedMessages[$i])) { $postedMessages[$i] = [yield $this->chatClient->postMessage($room, $text, self::POST_FLAGS), $text]; } else if ($text !== $postedMessages[$i][1]) { yield $this->chatClient->editMessage($postedMessages[$i][0], $text, PostFlags::SINGLE_LINE); } } $pauseDuration = self::POLL_INTERVAL_MS - (int)floor((microtime(true) - $actionStart) * 1000); } while (++$requests < self::POLL_REQUEST_LIMIT && $parsedResult['script']['state'] === 'busy'); } private function getMessageText(string $title, string $output, string $url): string { return trim(sprintf('[ [%s](%s) ] %s', $title, $url, $output)); } private function generateMessageFromOutput(array $output, string $url): string { return $this->getMessageText($output["versions"], htmlspecialchars_decode($output["output"]), $url); } private function doEval(HttpRequest $request, Command $command): \Generator { /** @var HttpResponse $response */ $response = yield $this->httpClient->request($request); $requestUri = $request->getUri(); if ($response->getStatus() !== 200) { return $this->chatClient->postReply($command, "Got HTTP response code {$response->getStatus()} from `{$requestUri}` :-("); } $previousResponse = $response->getPreviousResponse(); if ($previousResponse === null) { return $this->chatClient->postReply($command, "I wasn't redirected by `{$requestUri}` like I expected :-("); } try { $location = $previousResponse->getHeader("Location"); } catch (\DomainException $e) { $location = []; } if (!isset($location[0])) { return $this->chatClient->postReply($command, "I didn't get a redirect location from `{$requestUri}` :-("); } $targetUri = (string)(new Uri($requestUri))->resolve($location[0]); $text = $this->getMessageText('Waiting for results', '', $targetUri); /** @var PostedMessage $chatMessage */ $chatMessage = yield $this->chatClient->postMessage($command, $text, PostFlags::SINGLE_LINE); yield from $this->pollUntilDone($targetUri, $chatMessage, $text); } private function executeActionsFromQueue() { $this->haveLoop = true; while ($this->queue->count() > 0) { /** @var HttpRequest $request */ /** @var Command $command */ /** @var Promisor $promisor */ list($request, $command, $promisor) = $this->queue->pop(); try { $promisor->succeed(yield from $this->doEval($request, $command)); } catch (\Throwable $e) { $promisor->fail($e); } } $this->haveLoop = false; } public function eval(Command $command): Promise { if (!$command->hasParameters()) { return new Success(); } $code = $this->normalizeCode($command->getCommandText()); $body = (new FormBody) ->addField("title", "") ->addField("code", $code) ; $request = (new HttpRequest) ->setUri(self::BASE_URL . "/new") ->setMethod("POST") ->setHeader("Accept", "application/json") ->setBody($body) ; $deferred = new Deferred; $this->queue->push([$request, $command, $deferred]); if (!$this->haveLoop) { resolve($this->executeActionsFromQueue())->when(function(?\Throwable $error) use($deferred) { if ($error) { $deferred->fail($error); } }); } return $deferred->promise(); } public function getName(): string { return '3v4l'; } public function getDescription(): string { return 'Executes code snippets on 3v4l.org and displays the output'; } /** * @return PluginCommandEndpoint[] */ public function getCommandEndpoints(): array { return [new PluginCommandEndpoint('Eval', [$this, 'eval'], 'eval')]; } }
DaveRandom/Jeeves
src/Plugins/EvalCode.php
PHP
mit
6,668
class Question < ActiveRecord::Base belongs_to :questionnaire, dependent: :destroy has_one :response accepts_nested_attributes_for :response end
erikcaineolson/HARE
app/models/question.rb
Ruby
mit
151
--- title: Additional Thought date: 22/12/2017 --- “The Bible shows us God’s plan. Bible truths are God’s words. The person who makes these truths a part of his life becomes a new person in every way. But God does not give this person new powers of the mind. Instead, God takes away the sin that has darkened the per-son’s mind. God’s words to us: ‘I will give you a new heart’ also mean ‘I will give you a new mind.’ God changes our heart frst. Then He gives us a clear understanding of truth and our duty as Christians. We must study the Bible with careful attention and prayer. Then we will gain clear under-standing and the skill to judge wisely in everything.”—Ellen G. White, *My Life Today*, page 24, adapted. “The Lord . . . is coming soon. We must be ready and waiting for Him to come back. Oh, how wonderful it will be to see Jesus and be welcomed as His saved ones! We have waited for a long time. But we must not let our hope grow weak or fade. What would happen if we could see the King [Jesus] in all His beauty? Then we would be blessed forever. I feel as if I must cry aloud: ‘We are going homeward!’ We are nearing the time that Jesus will come in power and glory to take His saved ones to their everlasting home.”—Ellen G. White, *Testimonies [Messages] for the Church*, volume 8, page 253, adapted. **Discussion Questions** `1. How are we to be both good citizens and good Christians at the same time? That question can be difficult to answer. What if someone were to come to you for advice about how to be a good citizen? What if taking a stand for God put this person at war with the government? What advice would you give this person?` `2. What is harder to do: to be very strict in obeying the law, or to love God and others without limits? Or would you argue that this question is unfair to begin with because it seems to say obedience and love are completely different and cannot be done at the same time? Is that idea true or false? Explain.` `3. What have you learned from Romans to help you understand the importance of the Reformation? The Reformation was a time of big religious changes that began in the 1500s. At that time, people began to “wake up” to Bible truths. These truths led to the start of the Protestant churches. So, what does the book of Romans teach us about our beliefs as Protestants and why we believe the way we do?`
imasaru/sabbath-school-lessons
src/en/2017-04-er/12/07.md
Markdown
mit
2,412
package luhn import "testing" var validTests = []struct { n string ok bool }{ {"738", false}, {"8739567", true}, {"1111", false}, {"8763", true}, {" ", false}, {"", false}, {"2323 2005 7766 3554", true}, } var addTests = []struct{ raw, luhn string }{ {"123", "1230"}, {"873956", "8739567"}, {"837263756", "8372637564"}, {"2323 2005 7766 355", "2323 2005 7766 3554"}, // bonus Unicode cases // {"2323·2005·7766·355", "2323·2005·7766·3554"}, // {"123", "1230"}, } func TestValid(t *testing.T) { for _, test := range validTests { if ok := Valid(test.n); ok != test.ok { t.Fatalf("Valid(%s) = %t, want %t.", test.n, ok, test.ok) } } } func TestAddCheck(t *testing.T) { for _, test := range addTests { if luhn := AddCheck(test.raw); luhn != test.luhn { t.Fatalf("AddCheck(%s) = %s, want %s.", test.raw, luhn, test.luhn) } } } func BenchmarkValid(b *testing.B) { for i := 0; i < b.N; i++ { Valid("2323 2005 7766 3554") } } func BenchmarkAddCheck(b *testing.B) { for i := 0; i < b.N; i++ { AddCheck("2323 2005 7766 355") } }
DanShu93/exercism
solutions/go/luhn/luhn_test.go
GO
mit
1,091
<!DOCTYPE html> <html> <head> <title>BeatPicker Live Demo</title> <link rel="stylesheet" href="documents/css/reset.css"/> <link rel="stylesheet" href="css/BeatPicker.min.css"/> <link rel="stylesheet" href="documents/css/demos.css"/> <link rel="stylesheet" href="documents/css/prism.css"/> <script src="js/jquery-1.11.0.min.js"></script> <script src="js/BeatPicker.min.js"></script> <script src="documents/js/prism.js"></script> </head> <body> <div class="demo-header"> <div class="logo"> <img src="documents/css/images/beatPicker.png"> </div> <div class="sections"> <span class="caption">Sections</span> <ul class="sector"> <li><a href="#simple">Simple</a></li> <li><a href="#pos">Position</a></li> <li><a href="#date-format">Formatting</a></li> <li><a href="#disabling-rule">Date disabling</a></li> <li><a href="#range">Range</a></li> <li><a href="#disable-module">Module disabling</a></li> <li><a href="#objective-option">Objective option</a></li> <li><a href="#global-reference">Global instance</a></li> <li><a href="#event-handling">Events</a></li> </ul> </div> </div> <div class="introduction"> <h4>Introduction:</h4> Many thanx to using BeatPicker.here you can see functionality of BeatPicker in declrative syntax mode. You can read full docs and options available of beat picker <a href="docs.html">here</a>.Download latest version <a href="https://github.com/ACT1GMR/BeatPicker/zipball/0.1.3">here</a><br> <b>Browsers support and infos <a href="/BeatPicker">here</a></b> </div> <div class="demos"> <div id="simple" class="demo"> <h1>Simple</h1> <div class="sample"> <span>simple initial</span> <input type="text" data-beatpicker="true"/> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true"/> </code> </pre> </div> </div> <div id="pos" class="demo"> <h1>Position</h1> <div class="sample"> <span>right bottom</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['right','bottom']"> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['right','bottom']"> </code> </pre> </div> <br> <br> <div class="sample"> <span>right auto</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['right','*']"> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['right','*']"> </code> </pre> </div> <br> <br> <div class="sample"> <span>right top</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['right','top']"> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['right','top']"> </code> </pre> </div> <br> <br> <div class="sample"> <span>auto position</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']"> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']"> </code> </pre> </div> <br> <br> <div class="sample"> <span>custom position realtive to input top left corner</span> <input type="text" data-beatpicker="true" data-beatpicker-position="[10,50]"> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="[10,50]"> </code> </pre> </div> </div> <div id="date-format" class="demo"> <h1>Date formatting</h1> <div class="sample"> <span>simple format</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-format="['YYYY','MM','DD']" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-format="['YYYY','MM','DD']"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>simple format and custom separator</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-format="['YYYY','MM','DD'],separator:'/'" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-format="['YYYY','MM','DD'],separator:'/'" /> </code> </pre> </div> <br> <br> <div class="sample"> <span>custom format with custom separator</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-format="['DD','MM','YYYY'],separator:'/'" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['right','*']" data-beatpicker-format="['DD','MM','YYYY'],separator:'/'"/> </code> </pre> </div> </div> <div id="disabling-rule" class="demo"> <h1>Disabling dates</h1> <div class="sample"> <span>from date to date disable</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:[2014,3,1]}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:[2014,3,1]}"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>disable any dates after 1 january of 2014</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:'>'}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:'>'}"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>disable any dates before 1 january of 2014</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:'<'}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:'<'}"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>disable february of 2014</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:[2014 , 2 , '*']}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:[2014 , 2 , '*']}"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>disable 2nd month of any years from 1 january of 2014</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:['*' , 2 , '*']}" /> </div> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:['*' , '2' , '*']}"/> </code> </pre> <br> <br> <div class="sample"> <span>disable 2nd day of 2nd month of any year from 1 january of 2014</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:['*' , '2' , '2']}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,1],to:['*' , '2' , '2']}"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>disable any date of 2014 after 6 january of 2014</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,6],to:['2014' , '*' , '*']}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014,1,6],to:['2014' , '*' , '*']}"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>disable 2nd month of any year from any date</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:'*',to:['*' , '2' , '*']}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:'*',to:['*' , '2' , '*']}"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>disable 2nd day of any month of any year from any date</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:'*',to:['*' , '*' , 2]}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:'*',to:['*' , '*' , 2]}"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>disable 2nd day of 2nd month of any year from any date</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:'*',to:['*' , 2 , 2]}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:'*',to:['*' , 2 , 2]}"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>multiple disable rules <b>note that first to last rule have high priority</b></span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014 , 2 , 2],to:[2014 , 3 , 7]},{from:[2014 , 5 , 3],to:[2014 , 7 , 4]}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:[2014 , 2 , 2],to:[2014 , 3 , 7]},{from:[2014 , 5 , 3],to:[2014 , 7 , 4]}"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>disable all dates</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:'*',to:'*'}" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from:'*',to:'*'}"/> </code> </pre> </div> </div> <div id="range" class="demo"> <h1>Range</h1> <div class="sample"> <span>simple</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-range="true" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-range="true"> </code> </pre> </div> <br> <br> <div class="sample"> <span>simple but can select disable dates in range</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from :[2014,3,16] , to:[2014,4,8]}" data-beatpicker-range="true,true" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-disable="{from :[2014,3,16] , to:[2014,4,8]}" data-beatpicker-range="true,true"> </code> </pre> </div> </div> <div id="disable-module" class="demo"> <h1>Disable module</h1> <div class="sample"> <span>Disable go to date</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-module="gotoDate" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-module="gotoDate"/> </code> </pre> </div> <br> <br> <div class="sample"> <span>Disable clear button and today button</span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-module="today,clear" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-module="today,clear" /> </code> </pre> </div> <br> <br> <div class="sample"> <span>Disable header and footer </span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-module="header,footer" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-module="header,footer" /> </code> </pre> </div> <br> <br> <div class="sample"> <span>Disable icon </span> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-module="icon" /> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-module="icon" /> </code> </pre> </div> </div> <div id="objective-option" class="demo"> <h1>Data structure options object</h1> <div class="sample"> <span>Define a global object and assign it to input like this</span> <input type="text" data-beatpicker="true" data-beatpicker-extra="customOptions" /> <script type="text/javascript"> customOptions = { view : { alwaysVisible:true }, labels: { today: "Tod", gotoDateInput: "Insert your date", gotoDateButton: "Set", clearButton: "Wipe" } } </script> <div style="margin-top: 280px"> <span class="type">Markup:</span> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-extra="customOptions"/> </code> </pre> <span class="type">Javascript:</span> <pre class="code-prev"> <code class="language-javascript"> customOptions = { view : { alwaysVisible:true }, labels: { today: "Tod", gotoDateInput: "Insert your date", gotoDateButton: "Set", clearButton: "Wipe" } } </code> </pre> </div> </div> </div> <div id="global-reference" class="demo"> <h1>Access to date picker object</h1> <div class="sample"> <span>Define an id to get instantiated date picker</span> <div> <button class="show-picker">Show</button> <button class="hide-picker">Hide</button> </div> <input type="text" data-beatpicker="true" data-beatpicker-id="myPicker"/> <script> $('.show-picker').click(function(e){ e.stopPropagation(); myPicker.show(); }); $('.hide-picker').click(function(e){ e.stopPropagation(); myPicker.hide(); }) </script> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-id="myPicker"/> </code> </pre> <span>Buttons markup</span> <pre class="code-prev"> <code class="language-markup"> &lt;button class="show-picker"&gt;Show&lt;/button&gt; &lt;button class="hide-picker"&gt;hide&lt;/button&gt; </code> </pre> <span>Buttons markup</span> <pre class="code-prev"> <code class="language-javascript"> $('.show-picker').click(function(e){ e.stopPropagation(); myPicker.show(); }); $('.hide-picker').click(function(e){ e.stopPropagation(); myPicker.hide(); }) </code> </pre> </div> </div> <div id="event-handling" class="demo"> <h1>Event handling</h1> <div class="sample"> <span>Handling event and show correspond status</span> <div class="status-box"></div> <input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-id="myDatePicker" /> <style> .status-box { background-color: rgb(214, 109, 88); color: rgb(241, 241, 241); font: bold 10px tahoma,sans-serif; height: auto; margin: 2px; padding: 5px; width: 247px; } </style> <script type="text/javascript"> $(document).ready(function(){ var statusGenerator = function (text) { var statusElem = $(".status-box"); var child = $("<span style='display: block'></span>").text(text); statusElem.append(child); }; myDatePicker.on("select", function (data) { statusGenerator(data.string + " selected") }); myDatePicker.on("change", function (data) { statusGenerator("Date picker changed current date: "+data.string); }); myDatePicker.on("show", function () { statusGenerator("Date picker show") }); myDatePicker.on("clear", function (data) { statusGenerator("Date picker cleared. cleared date: " + data.string) }); myDatePicker.on("hide", function () { statusGenerator("Date picker hide") }); }) </script> <pre class="code-prev"> <code class="language-markup"> &lt;input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-id="myDatePicker"/> </code> </pre> <span> status box markup </span> <pre class="code-prev"> <code class="language-markup"> &lt;div class="status-box">&lt;/div> </code> </pre> <span> status box javascript </span> <pre class="code-prev"> <code class="language-javascript"> $(document).ready(function(){ var statusGenerator = function (text) { var statusElem = $(".status"); var child = $("&lt;span>&lt;/span>").text(text); statusElem.append(child); }; myDatePicker.on("select", function (data) { statusGenerator(data.string + " selected") }); myDatePicker.on("change", function (data) { statusGenerator("Date picker changed current date: "+data.string); }); myDatePicker.on("show", function () { statusGenerator("Date picker show") }); myDatePicker.on("clear", function (data) { statusGenerator("Date picker cleared. cleared date: " + data.string) }); myDatePicker.on("hide", function () { statusGenerator("Date picker hide") }); }) </code> </pre> </div> </div> </div> </body> </html>
valtido/jom
public/assets/-/beatpicker/demos.html
HTML
mit
20,838
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['pending-invitation'] });
blakepettersson/dashboard.aptible.com
app/components/pending-invitation/component.js
JavaScript
mit
109
require 'test_helper' class TestTextElement < Test::Unit::TestCase def test_set_attributes [:title, :lang, :type, :value, :maxlength, :size].each do |attribute| assert ActiveForm::Element::Text.element_attribute_names.include?(attribute) end elem = ActiveForm::Element::Text.new :elem, :value => 'string', :maxlength => 20, :size => 20 expected = {"type" => "text", "name"=>"elem", "class"=>"elem_text", "id"=>"elem", "value"=>"string", "maxlength"=>20, "size"=>20} assert_equal expected, elem.element_attributes end def test_option_flag_to_html_flag form = ActiveForm::compose :form do |f| f.text_element :firstname, :readonly => true f.text_element :lastname, :disabled => true end expected = {"name"=>"form[firstname]", "readonly"=>"readonly", "class"=>"elem_text readonly", "type"=>"text", "id"=>"form_firstname", "value"=>"", "size"=>30} assert_equal expected, form[:firstname].element_attributes expected = {"name"=>"form[lastname]", "class"=>"elem_text disabled", "type"=>"text", "id"=>"form_lastname", "disabled"=>"disabled", "value"=>"", "size"=>30} assert_equal expected, form[:lastname].element_attributes end def test_frozen_value elem = ActiveForm::Element::Text.new :elem, :frozen => true, :value => "Freeze me!" assert elem.frozen? assert_equal "Freeze me!", elem.formatted_value elem.frozen_value = "I'm frozen now!" assert_equal "I'm frozen now!", elem.formatted_value assert_equal "I'm frozen now!", elem.to_html elem.frozen = false assert !elem.frozen? expected = %|<input class="elem_text" id="elem" name="elem" size="30" type="text" value="Freeze me!"/>\n| assert_equal expected, elem.to_html end def test_freeze_filter elem = ActiveForm::Element::Text.new :elem, :frozen => true, :value => "Freeze me!" elem.freeze_filter = lambda { |value| value.to_s.upcase } assert elem.frozen? assert_equal "FREEZE ME!", elem.formatted_value elem.frozen_value = "I'm frozen now!" assert_equal "I'm frozen now!", elem.formatted_value elem.frozen = false assert_equal "Freeze me!", elem.formatted_value end def test_element_to_html elem = ActiveForm::Element::Text.new :elem expected = %|<input class="elem_text" id="elem" name="elem" size="30" type="text"/>\n| assert_equal expected, elem.to_html end def test_element_with_attributes_to_html elem = ActiveForm::Element::Text.new :elem, :size => 20, :value => 'hello world' assert_equal 'hello world', elem.element_value elem.element_value = 'new value' assert_equal 'new value', elem.element_value expected = %|<input class="elem_text" id="elem" name="elem" size="20" type="text" value="new value"/>\n| assert_equal expected, elem.to_html end def test_element_with_casting_and_formatting_filters elem = ActiveForm::Element::Text.new :elem, :value => ['one', 'two', 'three'] # this is regarded as element_value elem.define_formatting_filter { |value| value.join(', ') } elem.define_casting_filter { |value| value.split(/,\s+/) } assert_equal ['one', 'two', 'three'], elem.element_value assert_equal 'one, two, three', elem.formatted_value expected = %|<input class="elem_text" id="elem" name="elem" size="30" type="text" value="one, two, three"/>\n| assert_equal expected, elem.to_html elem.value = 'a, b, c, d, e' assert_equal ['a', 'b', 'c', 'd', 'e'], elem.element_value expected = %|<input class="elem_text" id="elem" name="elem" size="30" type="text" value="a, b, c, d, e"/>\n| assert_equal expected, elem.to_html end def test_export_value_for_grouped_elements form = ActiveForm::compose :form do |f| f.text_element :elem_a, :group => :grp f.text_element :elem_b, :group => :grp f.text_element :elem_c end form.update_values(:elem_a => 'One', :elem_b => 'Two') expected = { "elem_c" => nil, "grp" => ["One", "Two"] } assert_equal expected, form.export_values end end
carbonplanet/active_form
test/elements/test_text_element.rb
Ruby
mit
4,064
/* Browser holds the browser main object */ function Browser(container){ this.$container = $(container); this.ready = false; this.rows = []; this.data = Global.data; this.parser = Global.parser; this.offline = window.location.hash == '#random' || window.location.hash == '#disney'; this.resizeTimer; this.scrollTimer; this.animationDuration = Global.animationDuration; this.allowAnimation = Global.allowAnimation; this.hiddenWidth = 5; this.entityLimit = Global.data.entityLimit; this.$rowHolder; this.$scrollUpButton; this.$scrollDownButton; this.init(); } /* INIT */ /* init browser */ Browser.prototype.init = function(){ this.build(); } /* build browser html */ Browser.prototype.build = function(){ this.$rowHolder = $(document.createElement('div')).addClass('row-holder'); this.$container.append(this.$rowHolder); this.$scrollUpButton = $(document.createElement('div')).attr('id','scrollup-button').addClass('scrollButton'); this.$scrollDownButton = $(document.createElement('div')).attr('id','scrolldown-button').addClass('scrollButton'); this.$container.append(this.$scrollUpButton); this.$container.append(this.$scrollDownButton); this.$container.attr('unselectable','on') .css({'-moz-user-select':'-moz-none', '-moz-user-select':'none', '-o-user-select':'none', '-khtml-user-select':'none', '-webkit-user-select':'none', '-ms-user-select':'none', 'user-select':'none' }).bind('selectstart', function(){ return false; }); } /* init interactions */ Browser.prototype.initInteraction = function(){ /* listen to window resize*/ $(window).resize(this.resize.bind(this)); $(window).on('deviceorientation',this.resize.bind(this)); /* listen to topbar*/ $('#topbar').on('click',this.scrollTo.bind(this,0)); /* listen to scrollupbutton*/ this.$scrollUpButton.on('click',this.scrollRowUp.bind(this)); /* listen to scrolldownbutton*/ this.$scrollDownButton.on('click',this.scrollRowDown.bind(this)); /* listen to window scroll */ $(window).scroll(this.scrollEvent.bind(this)); this.ready = true; } /* listen to window resize */ Browser.prototype.resize = function(){ clearTimeout(this.resizeTimer); this.resizeTimer = setTimeout(function(){ for (var i=0, len = this.rows.length; i<len;i++){ this.rows[i].calcMinWidth(false); this.rows[i].calcWidth(); this.rows[i].zoomAction(1, 0); if(this.rows[i].currentEntity){ this.rows[i].growEntity(this.rows[i].currentEntity); } this.dockRows(); } }.bind(this),250); } /* User is updated (login/logout) */ Browser.prototype.userUpdate =function(){ for(var i =0, len = this.rows.length; i< len; i++){ for (var j =0, elen = this.rows[i].entities.length; j<elen; j++){ if (this.rows[i].entities[j].comments) { this.rows[i].entities[j].comments.userUpdate(); } if (this.rows[i].entities[j].collections){ this.rows[i].entities[j].collections.userUpdate(); } } } } /* clear browser */ Browser.prototype.clear = function(){ while(this.rows.length){ this.removeRow(this.rows[0]); } this.rows = []; $('body').css('background-image','none'); this.$rowHolder.empty(); } /* get container */ Browser.prototype.getContainer = function(){ return this.$container; } /* ROWS */ /* add a new row */ Browser.prototype.addRow = function(entity){ // if entity row is not the last row, remove previous rows if (entity){ var position = this.rows.indexOf(entity.getRow()); var len = this.rows.length; while(position < --len){ this.rows[len].remove(); this.rows.splice(len,1); } } else{ /* clear browser */ this.clear(); } var row = new Row(this, entity); this.rows.push(row); this.$rowHolder.append(row.getContainer()); this.dockRows(); return row; } /* remove a row */ Browser.prototype.removeRow = function(row){ row.remove(); var position = this.rows.indexOf(row); this.rows.splice(position,1); } /* DOCK ROWS */ Browser.prototype.dockRows = function(){ for(var i=0,len = this.rows.length; i<len; i++){ if (i < len - 2){ this.rows[i].dock(); } else{ this.rows[i].undock(); } } } // /* INIT */ // Browser.prototype.getData = function(){ // return this.data; // } /* Add a row with related entities for an entity */ Browser.prototype.addRelated = function(entity){ console.log('add related'); if (this.offline) { this.addRandom(entity); return; } var row = this.addRow(entity); if (entity.isCollection()){ // load collection this.data.getCollection(entity.data.uid.replace('Collection:',''),row.addResults.bind(row)); } else{ // check for preloaded related entities if (entity.data.relatedEntities){ // reuse preloaded related entities row.addResults({data:entity.data.relatedEntities}); } else{ // request new related entities this.data.getRelated(entity.data.uid,0,this.entityLimit,row.addResults.bind(row),row, true); } } } /* Add a row with search results for some keywords */ Browser.prototype.addSearch = function(keywords){ if (this.offline) { this.addRandom(); return; } var row = this.addRow(); if (keywords == 'My collections'){ //row.relatedness = 'My collections'; row.relatedness = 'Search'; Global.data.getSearchCollections(Global.search.keywords,0,this.entityLimit,row.addCollectionResults.bind(row),row.finishedLoading.bind(row)); } else{ if (keywords.indexOf('Collection:')==0){ //row.relatedness = 'Collection'; row.relatedness = 'Search'; Global.data.getSearchCollections(Global.search.keywords,0,this.entityLimit,row.addCollectionResults.bind(row),row.finishedLoading.bind(row)); } else { if (keywords.indexOf('Entity:')==0){ row.relatedness = 'Search'; var entity = new Entity(this); entity.setData(new DataEntity()); row.entity = entity; row.entity.data.uid = (Global.search.keywords.replace('Entity:','')); console.log(row.entity.data); Global.data.getEntity(row.entity.data.uid,row.addResults.bind(row),true); } else{ row.relatedness = 'Search'; this.data.getSearch(keywords,0,this.entityLimit,row.addResults.bind(row)); } } } } /* Add a row with a manual selected entity/entities from a collection */ Browser.prototype.addEntities = function(entities){ var row = this.addRow(); row.relatedness = 'Collection'; for(var i =0, len = entities.length; i< len; i++){ var entity = new Entity(this); entity.setData(entities[i]); if (!row.hasEntity(entity)){ if (!row.addEntity(entity)){ break; } } } row.finishedLoading(); if (entities.length == 1){ row.growEntity(row.entities[0],true); } } /* dev: add random entities */ Browser.prototype.addRandom = function(entity){ var row = this.addRow(entity); setTimeout(function(){ for(var i =0; i< 10 + Math.random() * 15; i++){ var entity = new Entity(this); entity.setData(row.getBrowser().parser.populateEntityData({})); if (!row.hasEntity(entity)){ if (!row.addEntity(entity)){ break; } } } row.finishedLoading(); }.bind(this), 400); if (entity && entity.status == entity.STATUS_INROW){ this.scrollToBottom(); } } /* SCROLLING */ /* scroll to bottom */ Browser.prototype.scrollToBottom = function(){ if ($('body').hasClass('scrolling') || $('body').hasClass('drag-scrolling')){ return; } this.scrollTo(document.body.scrollHeight); } /* scroll vertically a certain amount */ Browser.prototype.scrollBy = function(scroll){ if ($('body').hasClass('scrolling')){ return; } window.scrollBy(0,scroll); } /* scroll vertical to a certain scrolltop position */ Browser.prototype.scrollTo = function(scrollTop){ if ($('body').hasClass('scrolling')){ return; } if ($(window).scrollTop() == scrollTop){ return;} $('body').addClass('scrolling'); if (this.allowAnimation){ $('html, body').stop().animate({ scrollTop: scrollTop }, this.animationDuration, function(){ $('body').removeClass('scrolling'); }); } else{ $('html, body').scrollTop(scrollTop); $('body').removeClass('scrolling'); } } /* scroll up a row or a screen (?) */ Browser.prototype.scrollRowUp = function(){ var newTop = 0; var scrollTop = $(window).scrollTop(); var position; var contentTop = $('#content').position().top; for (var i=0, len = this.rows.length; i <len; i++){ position = this.rows[i].getContainer().position() if (position.top + contentTop < scrollTop){ newTop = position.top + contentTop; } } this.scrollTo(newTop - $('#topbar').height()); } /* scroll up a row */ Browser.prototype.scrollRowDown = function(){ var newTop = 0; var scrollTop = $(window).scrollTop(); var position; var topbarHeight = $('#topbar').height(); var contentTop = $('#content').position().top; for (var i=0, len = this.rows.length; i <len; i++){ position = this.rows[i].getContainer().position(); if (position.top + contentTop > scrollTop + topbarHeight){ newTop = position.top + contentTop; break; } } if(!newTop){ newTop = position.top; } this.scrollTo(newTop - topbarHeight); } /* listen to browser scroll, change scroll button colors */ Browser.prototype.scrollEvent = function(){ clearTimeout(this.scrollTimer); this.scrollTimer = setTimeout(this.checkScroll.bind(this),200); } Browser.prototype.checkScroll = function(){ /* show/hide scroll buttons */ var scrollTop = $(window).scrollTop(); if (scrollTop > 50){ this.$scrollUpButton.show(); this.$scrollDownButton.show(); } /* get prev/next items to set scroll button border colors */ //if (this.rows.length < 1){ return;} var prevRow = false, nextRow = false; var position; var topbarHeight = $('#topbar').height(); var contentTop = $('#content').position().top; for (var i=0, len = this.rows.length; i <len; i++){ position = this.rows[i].getContainer().position(); if (position.top + contentTop > scrollTop){ if (i < this.rows.length - 1){ nextRow = this.rows[i+1]; } else{ nextRow = false; } if (!prevRow && scrollTop < 100){ nextRow = this.rows[0]; } break; } prevRow = this.rows[i]; } this.$scrollUpButton.removeClass(this.getBorderClass.bind(this)); this.$scrollUpButton.addClass(prevRow ? (prevRow.currentEntity ? 'border-' + prevRow.currentEntity.getType() : 'border-Search') : 'border-None'); this.$scrollDownButton.removeClass(this.getBorderClass.bind(this)); this.$scrollDownButton.addClass(nextRow ? (nextRow.currentEntity ? 'border-' + nextRow.currentEntity.getType() : 'border-Search') : 'border-None'); } Browser.prototype.getBorderClass = function(index,css){ return (css.match (/(^|\s)border-\S+/g) || []).join(' '); } Browser.prototype.show = function(){ if (!this.ready){ this.initInteraction(); } $('#gallery').hide(); Global.collectionMenu.$savePathButton.show(); Global.user.refresh(); $(this.$container).show(); } /* update entity content of changed entity */ Browser.prototype.updateEntity = function(entityId,title,description,isPublic){ var entity; for(var i = 0, len1 = this.rows.length; i < len1; i++){ for(var j = 0, len2 = Global.browser.rows[i].entities.length; j < len2; j++){ entity = this.rows[i].entities[j]; if (entity.getUID() == entityId){ entity.update(title,description,isPublic); } } } } /* update entity content of changed entity */ Browser.prototype.deleteEntity = function(entityId){ var entity; for(var i = 0, len1 = this.rows.length; i < len1; i++){ var removes = []; for(var j = 0, len2 = Global.browser.rows[i].entities.length; j < len2; j++){ entity = this.rows[i].entities[j]; if (entity.getUID() == entityId){ entity.$container.remove(); removes.push(entity); } } for (var r = 0, len3 = removes.length; r < len3; r++){ for(var j = 0, len2 = Global.browser.rows[i].entities.length; j < len2; j++){ if (removes[r] == Global.browser.rows[i].entities[j]){ Global.browser.rows[i].entities.splice(j,1); break; } } } Global.browser.rows[i].showAllEntities(); } } /* TESTS/DEV */ /* remove all images and put colors in place */ Browser.prototype.testColor = function(){ $('.visual-holder').css('backgroundImage','none').each(function(){$(this).css('backgroundColor','rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')');}); }
CrowdTruth/DIVE
web/js/Browser.js
JavaScript
mit
12,222
import React from 'react' import styles from './weather.less' function Weather (props) { const {city, icon, dateTime, temperature, name} = props return <div className={styles.weather}> <div className={styles.left}> <div className={styles.icon} style={{ backgroundImage: `url(${icon})` }} /> <p>{name}</p> </div> <div className={styles.right}> <h1 className={styles.temperature}>{temperature + '°'}</h1> <p className={styles.description}>{city},{dateTime}</p> </div> </div> } export default Weather
liufulin90/react-admin
src/routes/Dashboard/components/weather.js
JavaScript
mit
561
/** * Copyright 2013 Ionică Bizău * * A Node.JS module, which provides an object oriented wrapper for the Youtube v3 API. * Author: Ionică Bizău <bizauionica@gmail.com> * **/ var Util = require("../../util"); function list (options, callback) { var self = this; var url = Util.createUrl.apply(self, ["playlists", options]); var reqOptions = { url: url, }; self.Client.request(reqOptions, callback); } function insert (options, callback) { callback(null, {"error": "Not yet implemented"}); } function update (options, callback) { callback(null, {"error": "Not yet implemented"}); } function deleteItem (options, callback) { callback(null, {"error": "Not yet implemented"}); } module.exports = { list: list, insert: insert, update: update, delete: deleteItem };
clarkeadg/piratesails
node_modules/youtube-api/api/v3.0.0/playlists.js
JavaScript
mit
837
// Copyright 2014 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Flags: --harmony-symbols var v0 = new WeakMap; var v1 = {}; v0.set(v1, 1); var sym = Symbol(); v1[sym] = 1; var symbols = Object.getOwnPropertySymbols(v1); assertArrayEquals([sym], symbols);
imzcy/JavaScriptExecutable
thirdparty/v8/src/test/mjsunit/regress/regress-crbug-350864.js
JavaScript
mit
1,793
/*++ Copyright (c) 2011 Microsoft Corporation Module Name: pdr_manager.h Abstract: A manager class for PDR, taking care of creating of AST objects and conversions between them. Author: Krystof Hoder (t-khoder) 2011-8-25. Revision History: --*/ #ifndef PDR_MANAGER_H_ #define PDR_MANAGER_H_ #include <utility> #include <map> #include "bool_rewriter.h" #include "expr_replacer.h" #include "expr_substitution.h" #include "map.h" #include "ref_vector.h" #include "smt_kernel.h" #include "pdr_util.h" #include "pdr_sym_mux.h" #include "pdr_farkas_learner.h" #include "pdr_smt_context_manager.h" #include "dl_rule.h" namespace smt { class context; } namespace pdr { struct relation_info { func_decl_ref m_pred; func_decl_ref_vector m_vars; expr_ref m_body; relation_info(ast_manager& m, func_decl* pred, ptr_vector<func_decl> const& vars, expr* b): m_pred(pred, m), m_vars(m, vars.size(), vars.c_ptr()), m_body(b, m) {} relation_info(relation_info const& other): m_pred(other.m_pred), m_vars(other.m_vars), m_body(other.m_body) {} }; class unknown_exception {}; class inductive_property { ast_manager& m; model_converter_ref m_mc; vector<relation_info> m_relation_info; expr_ref fixup_clauses(expr* property) const; expr_ref fixup_clause(expr* clause) const; public: inductive_property(ast_manager& m, model_converter_ref& mc, vector<relation_info> const& relations): m(m), m_mc(mc), m_relation_info(relations) {} std::string to_string() const; expr_ref to_expr() const; void to_model(model_ref& md) const; void display(datalog::rule_manager& rm, ptr_vector<datalog::rule> const& rules, std::ostream& out) const; }; class manager { ast_manager& m; smt_params& m_fparams; mutable bool_rewriter m_brwr; sym_mux m_mux; expr_ref m_background; decl_vector m_o0_preds; pdr::smt_context_manager m_contexts; /** whenever we need an unique number, we get this one and increase */ unsigned m_next_unique_num; static vector<std::string> get_state_suffixes(); unsigned n_index() const { return 0; } unsigned o_index(unsigned i) const { return i+1; } void add_new_state(func_decl * s); public: manager(smt_params& fparams, unsigned max_num_contexts, ast_manager & manager); ast_manager& get_manager() const { return m; } smt_params& get_fparams() const { return m_fparams; } bool_rewriter& get_brwr() const { return m_brwr; } expr_ref mk_and(unsigned sz, expr* const* exprs); expr_ref mk_and(expr_ref_vector const& exprs) { return mk_and(exprs.size(), exprs.c_ptr()); } expr_ref mk_and(expr* a, expr* b) { expr* args[2] = { a, b }; return mk_and(2, args); } expr_ref mk_or(unsigned sz, expr* const* exprs); expr_ref mk_or(expr_ref_vector const& exprs) { return mk_or(exprs.size(), exprs.c_ptr()); } expr_ref mk_not_and(expr_ref_vector const& exprs); void get_or(expr* e, expr_ref_vector& result); //"o" predicates stand for the old states and "n" for the new states func_decl * get_o_pred(func_decl * s, unsigned idx); func_decl * get_n_pred(func_decl * s); /** Marks symbol as non-model which means it will not appear in models collected by get_state_cube_from_model function. This is to take care of auxiliary symbols introduced by the disjunction relations to relativize lemmas coming from disjuncts. */ void mark_as_non_model(func_decl * p) { m_mux.mark_as_non_model(p); } func_decl * const * begin_o0_preds() const { return m_o0_preds.begin(); } func_decl * const * end_o0_preds() const { return m_o0_preds.end(); } bool is_state_pred(func_decl * p) const { return m_mux.is_muxed(p); } func_decl * to_o0(func_decl * p) { return m_mux.conv(m_mux.get_primary(p), 0, o_index(0)); } bool is_o(func_decl * p, unsigned idx) const { return m_mux.has_index(p, o_index(idx)); } bool is_o(expr* e, unsigned idx) const { return is_app(e) && is_o(to_app(e)->get_decl(), idx); } bool is_o(func_decl * p) const { unsigned idx; return m_mux.try_get_index(p, idx) && idx!=n_index(); } bool is_o(expr* e) const { return is_app(e) && is_o(to_app(e)->get_decl()); } bool is_n(func_decl * p) const { return m_mux.has_index(p, n_index()); } bool is_n(expr* e) const { return is_app(e) && is_n(to_app(e)->get_decl()); } /** true if p should not appead in models propagates into child relations */ bool is_non_model_sym(func_decl * p) const { return m_mux.is_non_model_sym(p); } /** true if f doesn't contain any n predicates */ bool is_o_formula(expr * f) const { return !m_mux.contains(f, n_index()); } /** true if f contains only o state preds of index o_idx */ bool is_o_formula(expr * f, unsigned o_idx) const { return m_mux.is_homogenous_formula(f, o_index(o_idx)); } /** true if f doesn't contain any o predicates */ bool is_n_formula(expr * f) const { return m_mux.is_homogenous_formula(f, n_index()); } func_decl * o2n(func_decl * p, unsigned o_idx) const { return m_mux.conv(p, o_index(o_idx), n_index()); } func_decl * o2o(func_decl * p, unsigned src_idx, unsigned tgt_idx) const { return m_mux.conv(p, o_index(src_idx), o_index(tgt_idx)); } func_decl * n2o(func_decl * p, unsigned o_idx) const { return m_mux.conv(p, n_index(), o_index(o_idx)); } void formula_o2n(expr * f, expr_ref & result, unsigned o_idx, bool homogenous=true) const { m_mux.conv_formula(f, o_index(o_idx), n_index(), result, homogenous); } void formula_n2o(expr * f, expr_ref & result, unsigned o_idx, bool homogenous=true) const { m_mux.conv_formula(f, n_index(), o_index(o_idx), result, homogenous); } void formula_n2o(unsigned o_idx, bool homogenous, expr_ref & result) const { m_mux.conv_formula(result.get(), n_index(), o_index(o_idx), result, homogenous); } void formula_o2o(expr * src, expr_ref & tgt, unsigned src_idx, unsigned tgt_idx, bool homogenous=true) const { m_mux.conv_formula(src, o_index(src_idx), o_index(tgt_idx), tgt, homogenous); } /** Return true if all state symbols which e contains are of one kind (either "n" or one of "o"). */ bool is_homogenous_formula(expr * e) const { return m_mux.is_homogenous_formula(e); } /** Collect indices used in expression. */ void collect_indices(expr* e, unsigned_vector& indices) const { m_mux.collect_indices(e, indices); } /** Collect used variables of each index. */ void collect_variables(expr* e, vector<ptr_vector<app> >& vars) const { m_mux.collect_variables(e, vars); } /** Return true iff both s1 and s2 are either "n" or "o" of the same index. If one (or both) of them are not state symbol, return false. */ bool have_different_state_kinds(func_decl * s1, func_decl * s2) const { unsigned i1, i2; return m_mux.try_get_index(s1, i1) && m_mux.try_get_index(s2, i2) && i1!=i2; } /** Increase indexes of state symbols in formula by dist. The 'N' index becomes 'O' index with number dist-1. */ void formula_shift(expr * src, expr_ref & tgt, unsigned dist) const { SASSERT(n_index()==0); SASSERT(o_index(0)==1); m_mux.shift_formula(src, dist, tgt); } void mk_model_into_cube(const expr_ref_vector & mdl, expr_ref & res); void mk_core_into_cube(const expr_ref_vector & core, expr_ref & res); void mk_cube_into_lemma(expr * cube, expr_ref & res); void mk_lemma_into_cube(expr * lemma, expr_ref & res); /** Remove from vec all atoms that do not have an "o" state. The order of elements in vec may change. An assumption is that atoms having "o" state of given index do not have "o" states of other indexes or "n" states. */ void filter_o_atoms(expr_ref_vector& vec, unsigned o_idx) const { m_mux.filter_idx(vec, o_index(o_idx)); } void filter_n_atoms(expr_ref_vector& vec) const { m_mux.filter_idx(vec, n_index()); } /** Partition literals into o_lits and others. */ void partition_o_atoms(expr_ref_vector const& lits, expr_ref_vector& o_lits, expr_ref_vector& other, unsigned o_idx) const { m_mux.partition_o_idx(lits, o_lits, other, o_index(o_idx)); } void filter_out_non_model_atoms(expr_ref_vector& vec) const { m_mux.filter_non_model_lits(vec); } bool try_get_state_and_value_from_atom(expr * atom, app *& state, app_ref& value); bool try_get_state_decl_from_atom(expr * atom, func_decl *& state); std::string pp_model(const model_core & mdl) const { return m_mux.pp_model(mdl); } void set_background(expr* b) { m_background = b; } expr* get_background() const { return m_background; } /** Return true if we can show that lhs => rhs. The function can have false negatives (i.e. when smt::context returns unknown), but no false positives. bg is background knowledge and can be null */ bool implication_surely_holds(expr * lhs, expr * rhs, expr * bg=0); unsigned get_unique_num() { return m_next_unique_num++; } pdr::smt_context* mk_fresh() { return m_contexts.mk_fresh(); } void collect_statistics(statistics& st) const { m_contexts.collect_statistics(st); } void reset_statistics() { m_contexts.reset_statistics(); } }; } #endif
jirislaby/z3
src/muz/pdr/pdr_manager.h
C
mit
11,027
{% extends "base.html" %} {% block heading %} <h1>Registrierung</h1> {% endblock %} {% block content %} <form method="post" action=".">{% csrf_token %} <table border="0"> {{ form.as_table }} </table> <input type="submit" value="Register" class="btn btn-default"/> </form> <p> <br> <a href="/account">Login</a> </p> {% endblock %}
alexandrcoin/site
login/templates/registration/register.html
HTML
mit
370
// Copyright (C) 2011 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_OBJECT_DeTECTOR_Hh_ #define DLIB_OBJECT_DeTECTOR_Hh_ #include "object_detector_abstract.h" #include "../geometry.h" #include <vector> #include "box_overlap_testing.h" #include "full_object_detection.h" namespace dlib { // ---------------------------------------------------------------------------------------- struct rect_detection { double detection_confidence; unsigned long weight_index; rectangle rect; bool operator<(const rect_detection& item) const { return detection_confidence < item.detection_confidence; } }; struct full_detection { double detection_confidence; unsigned long weight_index; full_object_detection rect; bool operator<(const full_detection& item) const { return detection_confidence < item.detection_confidence; } }; // ---------------------------------------------------------------------------------------- template <typename image_scanner_type> struct processed_weight_vector { processed_weight_vector(){} typedef typename image_scanner_type::feature_vector_type feature_vector_type; void init ( const image_scanner_type& ) /*! requires - w has already been assigned its value. Note that the point of this function is to allow an image scanner to overload the processed_weight_vector template and provide some different kind of object as the output of get_detect_argument(). For example, the scan_fhog_pyramid object uses an overload that causes get_detect_argument() to return the special fhog_filterbank object instead of a feature_vector_type. This avoids needing to construct the fhog_filterbank during each call to detect and therefore speeds up detection. !*/ {} // return the first argument to image_scanner_type::detect() const feature_vector_type& get_detect_argument() const { return w; } feature_vector_type w; }; // ---------------------------------------------------------------------------------------- template < typename image_scanner_type_ > class object_detector { public: typedef image_scanner_type_ image_scanner_type; typedef typename image_scanner_type::feature_vector_type feature_vector_type; object_detector ( ); object_detector ( const object_detector& item ); object_detector ( const image_scanner_type& scanner_, const test_box_overlap& overlap_tester_, const feature_vector_type& w_ ); object_detector ( const image_scanner_type& scanner_, const test_box_overlap& overlap_tester_, const std::vector<feature_vector_type>& w_ ); explicit object_detector ( const std::vector<object_detector>& detectors ); unsigned long num_detectors ( ) const { return w.size(); } const feature_vector_type& get_w ( unsigned long idx = 0 ) const { return w[idx].w; } const processed_weight_vector<image_scanner_type>& get_processed_w ( unsigned long idx = 0 ) const { return w[idx]; } const test_box_overlap& get_overlap_tester ( ) const; const image_scanner_type& get_scanner ( ) const; object_detector& operator= ( const object_detector& item ); template < typename image_type > std::vector<rectangle> operator() ( const image_type& img, double adjust_threshold = 0 ); template < typename image_type > void operator() ( const image_type& img, std::vector<std::pair<double, rectangle> >& final_dets, double adjust_threshold = 0 ); template < typename image_type > void operator() ( const image_type& img, std::vector<std::pair<double, full_object_detection> >& final_dets, double adjust_threshold = 0 ); template < typename image_type > void operator() ( const image_type& img, std::vector<full_object_detection>& final_dets, double adjust_threshold = 0 ); // These typedefs are here for backwards compatibility with previous versions of // dlib. typedef ::dlib::rect_detection rect_detection; typedef ::dlib::full_detection full_detection; template < typename image_type > void operator() ( const image_type& img, std::vector<rect_detection>& final_dets, double adjust_threshold = 0 ); template < typename image_type > void operator() ( const image_type& img, std::vector<full_detection>& final_dets, double adjust_threshold = 0 ); template <typename T> friend void serialize ( const object_detector<T>& item, std::ostream& out ); template <typename T> friend void deserialize ( object_detector<T>& item, std::istream& in ); public: bool overlaps_any_box ( const std::vector<rect_detection>& rects, const dlib::rectangle& rect ) const { for (unsigned long i = 0; i < rects.size(); ++i) { if (boxes_overlap(rects[i].rect, rect)) return true; } return false; } test_box_overlap boxes_overlap; std::vector<processed_weight_vector<image_scanner_type> > w; image_scanner_type scanner; }; // ---------------------------------------------------------------------------------------- template <typename T> void serialize ( const object_detector<T>& item, std::ostream& out ) { int version = 2; serialize(version, out); T scanner; scanner.copy_configuration(item.scanner); serialize(scanner, out); serialize(item.boxes_overlap, out); // serialize all the weight vectors serialize(item.w.size(), out); for (unsigned long i = 0; i < item.w.size(); ++i) serialize(item.w[i].w, out); } // ---------------------------------------------------------------------------------------- template <typename T> void deserialize ( object_detector<T>& item, std::istream& in ) { int version = 0; deserialize(version, in); if (version == 1) { deserialize(item.scanner, in); item.w.resize(1); deserialize(item.w[0].w, in); item.w[0].init(item.scanner); deserialize(item.boxes_overlap, in); } else if (version == 2) { deserialize(item.scanner, in); deserialize(item.boxes_overlap, in); unsigned long num_detectors = 0; deserialize(num_detectors, in); item.w.resize(num_detectors); for (unsigned long i = 0; i < item.w.size(); ++i) { deserialize(item.w[i].w, in); item.w[i].init(item.scanner); } } else { throw serialization_error("Unexpected version encountered while deserializing a dlib::object_detector object."); } } // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // object_detector member functions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > object_detector<image_scanner_type>:: object_detector ( ) { } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > object_detector<image_scanner_type>:: object_detector ( const object_detector& item ) { boxes_overlap = item.boxes_overlap; w = item.w; scanner.copy_configuration(item.scanner); } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > object_detector<image_scanner_type>:: object_detector ( const image_scanner_type& scanner_, const test_box_overlap& overlap_tester, const feature_vector_type& w_ ) : boxes_overlap(overlap_tester) { // make sure requires clause is not broken DLIB_ASSERT(scanner_.get_num_detection_templates() > 0 && w_.size() == scanner_.get_num_dimensions() + 1, "\t object_detector::object_detector(scanner_,overlap_tester,w_)" << "\n\t Invalid inputs were given to this function " << "\n\t scanner_.get_num_detection_templates(): " << scanner_.get_num_detection_templates() << "\n\t w_.size(): " << w_.size() << "\n\t scanner_.get_num_dimensions(): " << scanner_.get_num_dimensions() << "\n\t this: " << this ); scanner.copy_configuration(scanner_); w.resize(1); w[0].w = w_; w[0].init(scanner); } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > object_detector<image_scanner_type>:: object_detector ( const image_scanner_type& scanner_, const test_box_overlap& overlap_tester, const std::vector<feature_vector_type>& w_ ) : boxes_overlap(overlap_tester) { // make sure requires clause is not broken DLIB_ASSERT(scanner_.get_num_detection_templates() > 0 && w_.size() > 0, "\t object_detector::object_detector(scanner_,overlap_tester,w_)" << "\n\t Invalid inputs were given to this function " << "\n\t scanner_.get_num_detection_templates(): " << scanner_.get_num_detection_templates() << "\n\t w_.size(): " << w_.size() << "\n\t this: " << this ); #ifdef ENABLE_ASSERTS for (unsigned long i = 0; i < w_.size(); ++i) { DLIB_ASSERT(w_[i].size() == scanner_.get_num_dimensions() + 1, "\t object_detector::object_detector(scanner_,overlap_tester,w_)" << "\n\t Invalid inputs were given to this function " << "\n\t scanner_.get_num_detection_templates(): " << scanner_.get_num_detection_templates() << "\n\t w_["<<i<<"].size(): " << w_[i].size() << "\n\t scanner_.get_num_dimensions(): " << scanner_.get_num_dimensions() << "\n\t this: " << this ); } #endif scanner.copy_configuration(scanner_); w.resize(w_.size()); for (unsigned long i = 0; i < w.size(); ++i) { w[i].w = w_[i]; w[i].init(scanner); } } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > object_detector<image_scanner_type>:: object_detector ( const std::vector<object_detector>& detectors ) { DLIB_ASSERT(detectors.size() != 0, "\t object_detector::object_detector(detectors)" << "\n\t Invalid inputs were given to this function " << "\n\t this: " << this ); std::vector<feature_vector_type> weights; weights.reserve(detectors.size()); for (unsigned long i = 0; i < detectors.size(); ++i) { for (unsigned long j = 0; j < detectors[i].num_detectors(); ++j) weights.push_back(detectors[i].get_w(j)); } *this = object_detector(detectors[0].get_scanner(), detectors[0].get_overlap_tester(), weights); } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > object_detector<image_scanner_type>& object_detector<image_scanner_type>:: operator= ( const object_detector& item ) { if (this == &item) return *this; boxes_overlap = item.boxes_overlap; w = item.w; scanner.copy_configuration(item.scanner); return *this; } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > template < typename image_type > void object_detector<image_scanner_type>:: operator() ( const image_type& img, std::vector<rect_detection>& final_dets, double adjust_threshold ) { scanner.load(img); std::vector<std::pair<double, rectangle> > dets; std::vector<rect_detection> dets_accum; for (unsigned long i = 0; i < w.size(); ++i) { const double thresh = w[i].w(scanner.get_num_dimensions()); scanner.detect(w[i].get_detect_argument(), dets, thresh + adjust_threshold); for (unsigned long j = 0; j < dets.size(); ++j) { rect_detection temp; temp.detection_confidence = dets[j].first-thresh; temp.weight_index = i; temp.rect = dets[j].second; dets_accum.push_back(temp); } } // Do non-max suppression final_dets.clear(); if (w.size() > 1) std::sort(dets_accum.rbegin(), dets_accum.rend()); for (unsigned long i = 0; i < dets_accum.size(); ++i) { if (overlaps_any_box(final_dets, dets_accum[i].rect)) continue; final_dets.push_back(dets_accum[i]); } } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > template < typename image_type > void object_detector<image_scanner_type>:: operator() ( const image_type& img, std::vector<full_detection>& final_dets, double adjust_threshold ) { std::vector<rect_detection> dets; (*this)(img,dets,adjust_threshold); final_dets.resize(dets.size()); // convert all the rectangle detections into full_object_detections. for (unsigned long i = 0; i < dets.size(); ++i) { final_dets[i].detection_confidence = dets[i].detection_confidence; final_dets[i].weight_index = dets[i].weight_index; final_dets[i].rect = scanner.get_full_object_detection(dets[i].rect, w[dets[i].weight_index].w); } } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > template < typename image_type > std::vector<rectangle> object_detector<image_scanner_type>:: operator() ( const image_type& img, double adjust_threshold ) { std::vector<rect_detection> dets; (*this)(img,dets,adjust_threshold); std::vector<rectangle> final_dets(dets.size()); for (unsigned long i = 0; i < dets.size(); ++i) final_dets[i] = dets[i].rect; return final_dets; } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > template < typename image_type > void object_detector<image_scanner_type>:: operator() ( const image_type& img, std::vector<std::pair<double, rectangle> >& final_dets, double adjust_threshold ) { std::vector<rect_detection> dets; (*this)(img,dets,adjust_threshold); final_dets.resize(dets.size()); for (unsigned long i = 0; i < dets.size(); ++i) final_dets[i] = std::make_pair(dets[i].detection_confidence,dets[i].rect); } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > template < typename image_type > void object_detector<image_scanner_type>:: operator() ( const image_type& img, std::vector<std::pair<double, full_object_detection> >& final_dets, double adjust_threshold ) { std::vector<rect_detection> dets; (*this)(img,dets,adjust_threshold); final_dets.clear(); final_dets.reserve(dets.size()); // convert all the rectangle detections into full_object_detections. for (unsigned long i = 0; i < dets.size(); ++i) { final_dets.push_back(std::make_pair(dets[i].detection_confidence, scanner.get_full_object_detection(dets[i].rect, w[dets[i].weight_index].w))); } } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > template < typename image_type > void object_detector<image_scanner_type>:: operator() ( const image_type& img, std::vector<full_object_detection>& final_dets, double adjust_threshold ) { std::vector<rect_detection> dets; (*this)(img,dets,adjust_threshold); final_dets.clear(); final_dets.reserve(dets.size()); // convert all the rectangle detections into full_object_detections. for (unsigned long i = 0; i < dets.size(); ++i) { final_dets.push_back(scanner.get_full_object_detection(dets[i].rect, w[dets[i].weight_index].w)); } } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > const test_box_overlap& object_detector<image_scanner_type>:: get_overlap_tester ( ) const { return boxes_overlap; } // ---------------------------------------------------------------------------------------- template < typename image_scanner_type > const image_scanner_type& object_detector<image_scanner_type>:: get_scanner ( ) const { return scanner; } // ---------------------------------------------------------------------------------------- } #endif // DLIB_OBJECT_DeTECTOR_Hh_
Pastor/videotools
lib/3rdParty/dlib/include/dlib/image_processing/object_detector.h
C
mit
19,586
package madgik.exareme.master.engine.parser; import junit.framework.TestCase; import madgik.exareme.common.schema.expression.SQLQuery; import madgik.exareme.common.schema.expression.SQLScript; import java.io.ByteArrayInputStream; import java.rmi.ServerException; public class ParserTest extends TestCase { public void test() throws Exception { String queryScript = "distributed create table a \n as select 'a', \"aa;\" from a;\n" + "distributed create table b \n as select 'b;' from b;\n"; SQLScript sQLScript = null; try { ByteArrayInputStream stream = new ByteArrayInputStream(queryScript.getBytes()); AdpDBQueryParser parser = new AdpDBQueryParser(stream); sQLScript = parser.parseScript(); } catch (Exception e) { throw new ServerException("Cannot parse script", e); } for (SQLQuery q : sQLScript.getQueries()) { System.out.println(q.getSql()); } } }
XristosMallios/cache
exareme-master/src/test/java/madgik/exareme/master/engine/parser/ParserTest.java
Java
mit
996
/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "StageHome.h" #include "CocosGUI.h" #include "cocostudio/ActionTimeline/CSLoader.h" #include "WidgetUserMenu.h" USING_NS_CC; using namespace ui; void StageHome::initialize() { _rootNode = CSLoader::createNode("MainScreen.csb"); g_posMenu = _rootNode->getChildByName("ProjectNode_7")->getPosition(); g_posInfo = _rootNode->getChildByName("ProjectNode_8")->getPosition(); auto userMenu = _rootNode->getChildByName("ProjectNode_7"); WidgetUserMenu::initialize(userMenu, StageType::HOME); } Vec2 StageHome::g_posInfo; Vec2 StageHome::g_posMenu;
sandyway/CocosStudioSamples
DemoMicroCardGame/Classes/StageHome.cpp
C++
mit
1,815
module.exports = { description: 'throw an error when accessing members of null or undefined' };
corneliusweig/rollup
test/form/samples/nested-member-access/_config.js
JavaScript
mit
97
import "reflect-metadata"; import {createTestingConnections, closeTestingConnections, reloadTestingDatabases} from "../../utils/test-utils"; import {Connection} from "../../../src/connection/Connection"; import {Post} from "./entity/Post"; import {Author} from "./entity/Author"; import {Abbreviation} from "./entity/Abbreviation"; describe("github issues > #215 invalid replacements of join conditions", () => { let connections: Connection[]; before(async () => connections = await createTestingConnections({ entities: [__dirname + "/entity/*{.js,.ts}"], schemaCreate: true, dropSchemaOnConnection: true, })); beforeEach(() => reloadTestingDatabases(connections)); after(() => closeTestingConnections(connections)); it("should not do invalid replacements of join conditions", () => Promise.all(connections.map(async connection => { const author = new Author(); author.name = "John Doe"; await connection.entityManager.persist(author); const abbrev = new Abbreviation(); abbrev.name = "test"; await connection.entityManager.persist(abbrev); const post = new Post(); post.author = author; post.abbreviation = abbrev; await connection.entityManager.persist(post); // generated query should end with "ON p.abbreviation_id = ab.id" // not with ON p.abbreviation.id = ab.id (notice the dot) which would // produce an error. const loadedPosts = await connection.entityManager .createQueryBuilder(Post, "p") .leftJoinAndMapOne("p.author", Author, "n", "p.author_id = n.id") .leftJoinAndMapOne("p.abbreviation", Abbreviation, "ab", "p.abbreviation_id = ab.id") .getMany(); loadedPosts.length.should.be.equal(1); }))); });
ReaxDev/typeorm
test/github-issues/215/issue-215.ts
TypeScript
mit
1,843
<?php return array ( '%displayName% created a new post.' => '%displayName%さんは、新しい投稿を行いました。', );
ProfilerTeam/Profiler
protected/modules_core/post/messages/ja/views_activities_PostCreated.php
PHP
mit
130
#include <gloperate-osg/OsgRenderStage.h> #include <glm/glm.hpp> #include <osg/Node> #include <osgViewer/Viewer> #include <osgDB/ReadFile> #include <gloperate-osg/OsgMouseHandler.h> #include <gloperate-osg/OsgKeyboardHandler.h> using namespace gloperate; namespace gloperate_osg { void OsgRenderStage::osg_loadScene(const std::string & filename) { setScene(osgDB::readNodeFile(filename)); } void OsgRenderStage::osg_setScene(osg::Node * scene) { // Release old scene if (m_scene) { m_scene->unref(); } // Set new scene m_scene = scene; m_scene->ref(); if (m_viewer) { m_viewer->setSceneData(m_scene); } } void OsgRenderStage::osg_initialize() { // Release old data if (m_viewer) { m_viewer->unref(); } if (m_embedded) { m_embedded->unref(); } // Create OSG viewer m_viewer = new osgViewer::Viewer; m_viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded); m_viewer->ref(); // Setup viewer using the already created window and OpenGL context m_embedded = m_viewer->setUpViewerAsEmbeddedInWindow(0, 0, 800, 600); m_embedded->ref(); // Initialize camera m_viewer->getCamera()->setProjectionMatrixAsPerspective(30.0f, 1.0, 0.01f, 10000.0f); m_viewer->getCamera()->setViewMatrix(osg::Matrix::lookAt(osg::Vec3(0, 0, 50), osg::Vec3(0, 0, 0), osg::Vec3(0, 1, 0))); // Initialize viewer if (m_scene) { m_viewer->setSceneData(m_scene); } m_viewer->realize(); } void OsgRenderStage::osg_process() { // Check if painter has been initialized correctly if (m_viewer && m_embedded) { // Send resize-event if (m_viewportX != m_viewport.data().x || m_viewportY != m_viewport.data().y || m_viewportW != m_viewport.data().z || m_viewportH != m_viewport.data().w ) { // Set new viewport m_viewportX = m_viewport.data().x; m_viewportY = m_viewport.data().y; m_viewportW = m_viewport.data().z; m_viewportH = m_viewport.data().w; m_embedded->resized(m_viewportX, m_viewportY, m_viewportW, m_viewportH); m_embedded->getEventQueue()->windowResize(m_viewportX, m_viewportY, m_viewportW, m_viewportH); // Inform sub-classes about changed viewport handleViewportChanged(); } // Draw OSG scene m_viewer->frame(); // Update view and projection matrices m_projectionMatrix = convertMatrix( m_viewer->getCamera()->getProjectionMatrix() ); m_viewMatrix = convertMatrix( m_viewer->getCamera()->getViewMatrix() ); // Invoke post-render callback postOsgRendering(); } } void OsgRenderStage::osg_cleanup() { if (m_scene) { m_scene->unref(); } if (m_embedded) { m_embedded->unref(); } if (m_viewer) { m_viewer->unref(); } } glm::mat4 OsgRenderStage::convertMatrix(const osg::Matrixd & mat) const { const double * data = mat.ptr(); return glm::mat4( (float)data[ 0], (float)data[ 1], (float)data[ 2], (float)data[ 3], (float)data[ 4], (float)data[ 5], (float)data[ 6], (float)data[ 7], (float)data[ 8], (float)data[ 9], (float)data[10], (float)data[11], (float)data[12], (float)data[13], (float)data[14], (float)data[15] ); } } // namespace gloperate_osg
lanice/gloperate
source/gloperate-osg/source/OsgRenderStage_osg.cpp
C++
mit
3,451
# How To Contribute 1. Fork the repository on Github 2. Create a named feature branch (i.e. `add-new-recipe`) 3. Write you change 4. Write tests for your change (if applicable) 5. Run the tests, ensuring they all pass 6. Submit a Pull Request
CrossRef/lagotto
vendor/cookbooks/consul/CONTRIBUTING.md
Markdown
mit
243
var $path = require('path'); module.exports = function(grunt) { grunt.initConfig({ localBase : $path.resolve(__dirname), pkg: grunt.file.readJSON('package.json'), litheConcat : { options : { cwd: '<%=localBase%>' }, publish : { src : 'public/js/', dest : 'public/js/dist/', walk : true, alias : 'config.js', global : 'conf/global.js', withoutGlobal : [ ], target : 'conf/' } }, litheCompress : { options : { cwd: '<%=localBase%>' }, publish : { src : 'public/js/dist/', dest : 'public/js/dist/' } } }); grunt.loadTasks('tasks/lithe'); grunt.registerTask( 'publish', '[COMMON] pack and compress files, then distribute', [ 'litheConcat:publish', 'litheCompress:publish' ] ); grunt.registerTask( 'default', 'the default task is publish', [ 'publish' ] ); };
tabspace/vrhd
gruntfile.js
JavaScript
mit
932
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Common.Core.Diagnostics; namespace Microsoft.Common.Core.Disposables { /// <summary> /// Provides a set of static methods for creating Disposables. /// </summary> public static class Disposable { /// <summary> /// Creates a disposable object that invokes the specified action when disposed. /// </summary> /// <param name="dispose">Action to run during the first call to <see cref="M:System.IDisposable.Dispose" />. The action is guaranteed to be run at most once.</param> /// <returns>The disposable object that runs the given action upon disposal.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="dispose" /> is null.</exception> public static IDisposable Create(Action dispose) { Check.ArgumentNull(nameof(dispose), dispose); return new AnonymousDisposable(dispose); } /// <summary> /// Creates a disposable wrapper for a disposable that will be invoked at most once. /// </summary> /// <param name="disposable">Disposable that will be wrapped. Disposable is guaranteed to be run at most once.</param> /// <returns>The disposable object that disposes wrapped object.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="disposable" /> is null.</exception> public static IDisposable Create(IDisposable disposable) { Check.ArgumentNull(nameof(disposable), disposable); return new DisposableWrapper(disposable); } /// <summary> /// Gets the disposable that does nothing when disposed. /// </summary> public static IDisposable Empty => DefaultDisposable.Instance; public static Task<IDisposable> EmptyTask { get; } = Task.FromResult<IDisposable>(DefaultDisposable.Instance); /// <summary> /// Represents an Action-based disposable. /// </summary> private sealed class AnonymousDisposable : IDisposable { private Action _dispose; /// <summary> /// Constructs a new disposable with the given action used for disposal. /// </summary> /// <param name="dispose">Disposal action which will be run upon calling Dispose.</param> public AnonymousDisposable(Action dispose) { _dispose = dispose; } /// <summary> /// Calls the disposal action if and only if the current instance hasn't been disposed yet. /// </summary> public void Dispose() { Action action = Interlocked.Exchange(ref _dispose, null); action?.Invoke(); } } /// <summary> /// Represents a disposable wrapper. /// </summary> private sealed class DisposableWrapper : IDisposable { private IDisposable _disposable; public DisposableWrapper(IDisposable disposable) { _disposable = disposable; } /// <summary> /// Disposes wrapped object if and only if the current instance hasn't been disposed yet. /// </summary> public void Dispose() { var disposable = Interlocked.Exchange(ref _disposable, null); disposable?.Dispose(); } } } }
AlexanderSher/RTVS
src/Common/Core/Impl/Disposables/Disposable.cs
C#
mit
3,634