text
stringlengths
2
1.04M
meta
dict
#ifndef LINKEDLIST_H #define LINKEDLIST_H #define ll_iter_get_as(it, type) ((type)ll_iter_get(it)) typedef struct ll_list_type *ll_list_t; typedef struct ll_iter_type *ll_iter_t; ll_list_t ll_new_list(); void ll_free(ll_list_t list); void ll_push_front(ll_list_t list, void *item); void ll_push_back(ll_list_t list, void *item); void* ll_pop_front(ll_list_t list); void* ll_pop_back(ll_list_t list); unsigned long ll_size(ll_list_t list); int ll_empty(ll_list_t list); void ll_clear(ll_list_t list); ll_iter_t ll_find(ll_list_t list, void *item); void ll_copy(ll_list_t src, ll_list_t dst); /** * perform a stable inplace sort of list. smallest items first. * */ void ll_sort(ll_list_t list, int (*cmp)(void *a, void *b)); ll_iter_t ll_iter(ll_list_t list); ll_iter_t ll_iter_reverse(ll_list_t list); void ll_iter_free(ll_iter_t iter); void* ll_iter_get(ll_iter_t iter); void ll_iter_advance(ll_iter_t iter); void ll_iter_remove(ll_iter_t iter); void ll_iter_insert_before(ll_iter_t iter, void *item); #endif /* LINKEDLIST_H */
{ "content_hash": "752e5d1139c3e5d406a75c01268e32ba", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 63, "avg_line_length": 28.86111111111111, "alnum_prop": 0.6939364773820982, "repo_name": "donlorenzo/linkedlist", "id": "5ba9feaa03b8ab9b10bc7410859d7ad6b38e50a8", "size": "1039", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/linkedlist.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "8763" }, { "name": "Makefile", "bytes": "409" } ], "symlink_target": "" }
#include "DeclarationNodeHandler.h" #include<lang/log/LogLevel.h> #include <commonlib/commonlib.h> #include <lang/model/allmodel.h> #include "../CallbackRegister.h" #include "../ExecStore.h" #include <lang/interpreter/exe/dec/VariableDeclaration.h> namespace IAS { namespace Lang { namespace Interpreter { namespace Proc { namespace Dec { /*************************************************************************/ DeclarationNodeHandler::DeclarationNodeHandler(){} /*************************************************************************/ DeclarationNodeHandler::~DeclarationNodeHandler() throw(){ IAS_TRACER; } /*************************************************************************/ void DeclarationNodeHandler::call(const Model::Node* pNode, CallbackCtx *pCtx, CallbackSignature::Result& aResult){ IAS_TRACER; IAS_TYPEID_CHECK(Model::Dec::DeclarationNode, pNode); const Model::Dec::DeclarationNode *pDeclarationNode = IAS_DYNAMICCAST_CONST(Model::Dec::DeclarationNode, pNode); handle(pDeclarationNode,pCtx,aResult); } /*************************************************************************/ void DeclarationNodeHandler::handle(const Model::Dec::DeclarationNode* pDeclarationNode, CallbackCtx *pCtx, CallbackSignature::Result& aResult){ IAS_TRACER; const DM::DataFactory *pDataFactory = pCtx->getDataFactory(); String strNamespace(pDeclarationNode->getNamespace()); String strName(pDeclarationNode->getType()); const DM::Type *pType = pCtx->getExecStore()->resolveType(strName,strNamespace); IAS_DFT_FACTORY<Exe::Dec::VariableDeclaration>::PtrHolder ptrVariableDeclaration; ptrVariableDeclaration=IAS_DFT_FACTORY<Exe::Dec::VariableDeclaration>::Create(pDeclarationNode->getVariable(), pType, pDeclarationNode->isArray()); IAS_LOG(::IAS::Lang::LogLevel::INSTANCE.isInfo(),"DeclarationNodeHandler: "<<pDeclarationNode->getVariable()<<", "<<(void*)ptrVariableDeclaration); aResult.pVariableDeclaration=ptrVariableDeclaration.pass(); } /*************************************************************************/ } } } } }
{ "content_hash": "f9717231bde4cd87315e4fbac213eb8c", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 148, "avg_line_length": 34.095238095238095, "alnum_prop": 0.6094040968342644, "repo_name": "InvenireAude/IAS-Base-OSS", "id": "be2348aa2acb1e4bc7446ff0f9020adb3636fda4", "size": "2834", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "IAS-LangLib/src/lang/interpreter/proc/dec/DeclarationNodeHandler.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "20541" }, { "name": "C++", "bytes": "5910026" }, { "name": "Makefile", "bytes": "29521" }, { "name": "Shell", "bytes": "31721" }, { "name": "Yacc", "bytes": "144670" } ], "symlink_target": "" }
package org.apache.activemq.artemis.api.core.client.loadbalance; import org.apache.activemq.artemis.utils.Random; /** * {@link RandomConnectionLoadBalancingPolicy#select(int)} chooses a the initial node randomly then subsequent requests return the same node */ public final class RandomStickyConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy { private final Random random = new Random(); private int pos = -1; /** * @see java.util.Random#nextInt(int) */ public int select(final int max) { if (pos == -1) { pos = random.getRandom().nextInt(max); } return pos; } }
{ "content_hash": "5b66ac56d1718bff946443bcc6f20621", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 140, "avg_line_length": 25.72, "alnum_prop": 0.702954898911353, "repo_name": "glaucio-melo-movile/activemq-artemis", "id": "556d33ff805e3aef7c32053781f235a960a8c1fe", "size": "1442", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/loadbalance/RandomStickyConnectionLoadBalancingPolicy.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5879" }, { "name": "C", "bytes": "23262" }, { "name": "C++", "bytes": "1032" }, { "name": "CMake", "bytes": "4260" }, { "name": "CSS", "bytes": "11732" }, { "name": "HTML", "bytes": "19113" }, { "name": "Java", "bytes": "22822527" }, { "name": "Shell", "bytes": "11911" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Auth.AccessControlPolicy.ActionIdentifiers { /// <summary> /// The available AWS access control policy actions for Amazon SQS. /// </summary> /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/> public class SQSActionIdentifiers { public static readonly ActionIdentifier AllSQSActions = new ActionIdentifier("sqs:*"); public static readonly ActionIdentifier AddPermission = new ActionIdentifier("sqs:AddPermission"); public static readonly ActionIdentifier ChangeMessageVisibility = new ActionIdentifier("sqs:ChangeMessageVisibility"); public static readonly ActionIdentifier ChangeMessageVisibilityBatch = new ActionIdentifier("sqs:ChangeMessageVisibilityBatch"); public static readonly ActionIdentifier CreateQueue = new ActionIdentifier("sqs:CreateQueue"); public static readonly ActionIdentifier DeleteMessage = new ActionIdentifier("sqs:DeleteMessage"); public static readonly ActionIdentifier DeleteMessageBatch = new ActionIdentifier("sqs:DeleteMessageBatch"); public static readonly ActionIdentifier DeleteQueue = new ActionIdentifier("sqs:DeleteQueue"); public static readonly ActionIdentifier GetQueueAttributes = new ActionIdentifier("sqs:GetQueueAttributes"); public static readonly ActionIdentifier GetQueueUrl = new ActionIdentifier("sqs:GetQueueUrl"); public static readonly ActionIdentifier ListQueues = new ActionIdentifier("sqs:ListQueues"); public static readonly ActionIdentifier ReceiveMessage = new ActionIdentifier("sqs:ReceiveMessage"); public static readonly ActionIdentifier RemovePermission = new ActionIdentifier("sqs:RemovePermission"); public static readonly ActionIdentifier SendMessage = new ActionIdentifier("sqs:SendMessage"); public static readonly ActionIdentifier SendMessageBatch = new ActionIdentifier("sqs:SendMessageBatch"); public static readonly ActionIdentifier SetQueueAttributes = new ActionIdentifier("sqs:SetQueueAttributes"); } }
{ "content_hash": "c791e78ae7aada769e1bc67539f798f2", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 136, "avg_line_length": 66.78125, "alnum_prop": 0.7781937295273749, "repo_name": "emcvipr/dataservices-sdk-dotnet", "id": "fc59a82673cdb45494f3cea6c855632784ea76ab", "size": "2724", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AWSSDK/Amazon.Auth/AccessControlPolicy/ActionIdentifiers/SQSActionIdentifiers.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "30500772" }, { "name": "Shell", "bytes": "1726" }, { "name": "XSLT", "bytes": "337772" } ], "symlink_target": "" }
package ee.ria.xroad.signer.protocol.message; import ee.ria.xroad.common.identifier.ClientId; import lombok.Value; import java.io.Serializable; /** * Signer API message. */ @Value public class GetMemberCerts implements Serializable { private final ClientId memberId; }
{ "content_hash": "fea21254920509612ac8d11515c84bac", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 53, "avg_line_length": 16.529411764705884, "alnum_prop": 0.7651245551601423, "repo_name": "vrk-kpa/X-Road", "id": "793aa5ebf4b97c231f7723519e7d206d9f57f515", "size": "1482", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/signer-protocol/src/main/java/ee/ria/xroad/signer/protocol/message/GetMemberCerts.java", "mode": "33188", "license": "mit", "language": [ { "name": "AMPL", "bytes": "1602" }, { "name": "C", "bytes": "54401" }, { "name": "CSS", "bytes": "62804" }, { "name": "HTML", "bytes": "135934" }, { "name": "Java", "bytes": "4233585" }, { "name": "JavaScript", "bytes": "407789" }, { "name": "Makefile", "bytes": "4405" }, { "name": "Perl", "bytes": "1376" }, { "name": "Python", "bytes": "238897" }, { "name": "Roff", "bytes": "2170" }, { "name": "Ruby", "bytes": "1007868" }, { "name": "Scala", "bytes": "14352" }, { "name": "Shell", "bytes": "142230" }, { "name": "XSLT", "bytes": "1244" } ], "symlink_target": "" }
@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=python -msphinx ) set SOURCEDIR=. set BUILDDIR=_build set SPHINXPROJ=behave-webdriver if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The Sphinx module was not found. Make sure you have Sphinx installed, echo.then set the SPHINXBUILD environment variable to point to the full echo.path of the 'sphinx-build' executable. Alternatively you may add the echo.Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd
{ "content_hash": "9c957a12f3cb0b2cf781f51d47ab71be", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 75, "avg_line_length": 21.61111111111111, "alnum_prop": 0.7365038560411311, "repo_name": "spyoungtech/behave-webdriver", "id": "16f646b1180e9c0bb37569cd24461099708657a5", "size": "778", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/make.bat", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "498" }, { "name": "Gherkin", "bytes": "2435" }, { "name": "HTML", "bytes": "9430" }, { "name": "JavaScript", "bytes": "5659" }, { "name": "Python", "bytes": "75920" } ], "symlink_target": "" }
package desmoj.extensions.applicationDomains.harbour; import desmoj.core.advancedModellingFeatures.Res; import desmoj.core.advancedModellingFeatures.WaitQueue; import desmoj.core.simulator.Queue; public class HoldingArea extends WaitQueue { /** * the number of the lanes of this HoldingArea . */ private int nLanes; /** * the lanes as Res of this Holding Area. */ private Res lanes; /** * the queue of the lanes of this HoldingArea . */ private Queue<Lane> laneQueue; /** * Constructor for a HoldingArea. There are two waiting-queues constructed, * one internal <code>QueueList</code> for the * <code>InternalTransporter</code> s (masters) and one separate * <code>ProcessQueue</code> for the <code>Truck</code> s (slave) * processes . The queueing discipline and the capacity limit of the * underlying queues can be chosen. Highest priority are always first in the * queues. * * @param owner * desmoj.Model : The model this HoldingArea is associated to. * @param name * java.lang.String : The name of this HoldingArea. * @param mSortOrder * int : determines the sort order of the underlying master queue * implementation. Choose a constant from <code>QueueBased</code> * like <code>QueueBased.FIFO</code> or * <code>QueueBased.LIFO</code> or ... * @param mQCapacity * int : The capacity of the master queue, that is how many * processes can be enqueued. Zero (0) means unlimited capacity. * @param sSortOrder * int : determines the sort order of the underlying slave queue * implementation. Choose a constant from <code>QueueBased</code> * like <code>QueueBased.FIFO</code> or * <code>QueueBased.LIFO</code> or ... * @param sQCapacity * int : The capacity of the slave queue, that is how many * processes can be enqueued. Zero (0) means unlimited capacity. * @param int * nLanes: the number of the lanes of this HoldingArea. * @param showInReport * boolean : Flag, if this HoldingArea should produce a report or * not. * @param showInTrace * boolean : Flag, if trace messages of this HoldingArea should * be displayed in the trace file. */ public HoldingArea(desmoj.core.simulator.Model owner, String name, int mSortOrder, int mQCapacity, int sSortOrder, int sQCapacity, int nLanes, boolean showInReport, boolean showInTrace) { // make a WaitQueue super(owner, name, mSortOrder, mQCapacity, sSortOrder, sQCapacity, showInReport, showInTrace); // check the number of the lanes if (nLanes <= 0) { sendWarning( "The given number of the lanes is " + "wrong.", getClass().getName() + ": " + getQuotedName() + ", Constructor: Holding Area(Model owner, String name, " + "int mSortOrder, int mQCapacity, int sSortOrder, int sQCapacity, int nLanes, boolean showInTrace)", "Tne number of the lanes that is negative or zero does not make sense.", "Make sure to provide a valid value for the number of the lanes " + "for the Holding Area to be constructed."); return; } this.nLanes = nLanes; // make lanes as Res this.lanes = new Res(owner, "Lanes", sSortOrder, sQCapacity, nLanes, true, false); // make the Queue of the lanes this.laneQueue = new Queue<Lane>(owner, "LaneQueue", 0, nLanes, false, false); // make lanes and insert them in the laneQueue Lane lane; for (int i = 0; i < this.nLanes; i++) { lane = new Lane(owner, "Lane", i + 1, false); this.laneQueue.insert(lane); } } // end of constructor /** * Gets a Line from the HoldingArea and provides it to the sim-process to use * it. As not enough lanes are available at the moment the sim-process has to * wait in a queue until a lane is available again. * * @return <code>Lane</code>: The available lane of this HoldingArea. */ public Lane getLane() { // check if there're available lanes if (!this.lanes.provide(1)) return null; // get the lane from the queue of the lanes Lane lane = this.laneQueue.first(); // trace that a lane was taken from this HO if (currentlySendTraceNotes()) sendTraceNote("takes " + lane.getName() + " from the " + this.getName()); // remove lane from the Queue this.laneQueue.remove(lane); return lane; } /** * A process is using this method to put lane it has used back in the * HoldingArea. * * @param l * <code>Lane</code>: The lane which should be returned to the * HoldingArea. */ public void takeBack(Lane l) { // take back the lane as Res this.lanes.takeBack(1); // insert the line to the lanes queue this.laneQueue.insert(l); if (currentlySendTraceNotes()) sendTraceNote("releases " + l.getName() + " to the " + this.getName()); } }
{ "content_hash": "daebd941850db414a6dc305265c0505d", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 108, "avg_line_length": 34.110344827586204, "alnum_prop": 0.6581075616659927, "repo_name": "muhd7rosli/desmoj", "id": "03d4966832d36f6fc6c00457bf92b37b0d77271c", "size": "7090", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/desmoj/extensions/applicationDomains/harbour/HoldingArea.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "5269138" }, { "name": "XSLT", "bytes": "32889" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/menu_1" android:title="Menu 1" app:showAsAction="never" /> <group android:id="@id/md_menu_default_group"> <item android:id="@+id/menu_2" android:title="Menu 2" app:showAsAction="never"> <menu> <item android:id="@+id/sub_menu_1" android:title="Submenu 1" app:showAsAction="never" /> <item android:id="@+id/sub_menu_2" android:title="Submenu 2" app:showAsAction="never" /> <item android:id="@+id/sub_menu_3" android:title="Submenu 3" app:showAsAction="never" /> </menu> </item> <item android:id="@+id/menu_3" android:title="Menu 3" app:showAsAction="never" /> <item android:id="@+id/menu_4" android:title="Menu 4" app:showAsAction="never"> <menu> <item android:id="@+id/sub_menu2_1" android:title="Submenu 1" app:showAsAction="never" /> <item android:id="@+id/sub_menu2_2" android:title="Submenu 2" app:showAsAction="never" /> </menu> </item> </group> <group android:id="@+id/md_menu_second_group"> <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="@string/action_settings" app:showAsAction="ifRoom" /> </group> </menu>
{ "content_hash": "8c53582593eea2d13b6b5a971c30169a", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 64, "avg_line_length": 33.578947368421055, "alnum_prop": 0.45454545454545453, "repo_name": "RacZo/MaterialDrawer", "id": "d797b99ee450f3db1089c7f10145bb460ee691ca", "size": "1914", "binary": false, "copies": "9", "ref": "refs/heads/develop", "path": "app/src/main/res/menu/example_menu.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "364262" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Loading...</div> <div class="SRResult" id="SR_buffered_5fchar"> <div class="SREntry"> <a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="../structbuffered__char.html" target="_parent">buffered_char</a> </div> </div> <div class="SRStatus" id="Searching">Searching...</div> <div class="SRStatus" id="NoMatches">No Matches</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
{ "content_hash": "c171c6990da87d2504b141a383fccd61", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 240, "avg_line_length": 45.6, "alnum_prop": 0.7166666666666667, "repo_name": "fenek/riak-c-driver", "id": "6972cbe5b32493d3f9228f614692ea783dfd947f", "size": "1140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/html/search/classes_62.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "119053" }, { "name": "JavaScript", "bytes": "21345" }, { "name": "Perl", "bytes": "2582" } ], "symlink_target": "" }
package org.apache.hive.hcatalog.templeton.tool; import java.io.IOException; import java.util.List; import org.apache.hadoop.conf.Configuration; /** * An interface to handle different Templeton storage methods, including * ZooKeeper and HDFS. Any storage scheme must be able to handle being * run in an HDFS environment, where specific file systems and virtual * machines may not be available. * * Storage is done individually in a hierarchy: type (the data type, * as listed below), then the id (a given jobid, jobtrackingid, etc.), * then the key/value pairs. So an entry might look like: * * JOB * jobid00035 * user -&gt; rachel * datecreated -&gt; 2/5/12 * etc. * * Each field must be available to be fetched/changed individually. */ public interface TempletonStorage { // These are the possible types referenced by 'type' below. public enum Type { UNKNOWN, JOB, JOBTRACKING } public static final String STORAGE_CLASS = "templeton.storage.class"; public static final String STORAGE_ROOT = "templeton.storage.root"; /** * Start the cleanup process for this storage type. * @param config */ public void startCleanup(Configuration config); /** * Save a single key/value pair for a specific job id. * @param type The data type (as listed above) * @param id The String id of this data grouping (jobid, etc.) * @param key The name of the field to save * @param val The value of the field to save */ public void saveField(Type type, String id, String key, String val) throws NotFoundException; /** * Get the value of one field for a given data type. If the type * is UNKNOWN, search for the id in all types. * @param type The data type (as listed above) * @param id The String id of this data grouping (jobid, etc.) * @param key The name of the field to retrieve * @return The value of the field requested, or null if not * found. */ public String getField(Type type, String id, String key); /** * Delete a data grouping (all data for a jobid, all tracking data * for a job, etc.). If the type is UNKNOWN, search for the id * in all types. * * @param type The data type (as listed above) * @param id The String id of this data grouping (jobid, etc.) * @return True if successful, false if not, throws NotFoundException * if the id wasn't found. */ public boolean delete(Type type, String id) throws NotFoundException; /** * Get the id of each data grouping of a given type in the storage * system. * @param type The data type (as listed above) * @return A list of ids. */ public List<String> getAllForType(Type type); /** * For storage methods that require a connection, this is a hint * that it's time to open a connection. */ public void openStorage(Configuration config) throws IOException; /** * For storage methods that require a connection, this is a hint * that it's time to close the connection. */ public void closeStorage() throws IOException; }
{ "content_hash": "e547d1315208403bafc4acfd28b898bb", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 74, "avg_line_length": 32.59574468085106, "alnum_prop": 0.691579634464752, "repo_name": "vergilchiu/hive", "id": "4bd73d98bb401d1b3f5d4566550a324c025558fd", "size": "3874", "binary": false, "copies": "2", "ref": "refs/heads/branch-2.3-htdc", "path": "hcatalog/webhcat/svr/src/main/java/org/apache/hive/hcatalog/templeton/tool/TempletonStorage.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "54494" }, { "name": "Batchfile", "bytes": "845" }, { "name": "C", "bytes": "28218" }, { "name": "C++", "bytes": "76808" }, { "name": "CSS", "bytes": "4263" }, { "name": "GAP", "bytes": "155326" }, { "name": "HTML", "bytes": "50822" }, { "name": "Java", "bytes": "39751326" }, { "name": "JavaScript", "bytes": "25851" }, { "name": "M4", "bytes": "2276" }, { "name": "PHP", "bytes": "148097" }, { "name": "PLSQL", "bytes": "8797" }, { "name": "PLpgSQL", "bytes": "339745" }, { "name": "Perl", "bytes": "319842" }, { "name": "PigLatin", "bytes": "12333" }, { "name": "Protocol Buffer", "bytes": "8769" }, { "name": "Python", "bytes": "386664" }, { "name": "Roff", "bytes": "5379" }, { "name": "SQLPL", "bytes": "20290" }, { "name": "Shell", "bytes": "313510" }, { "name": "Thrift", "bytes": "107584" }, { "name": "XSLT", "bytes": "7619" } ], "symlink_target": "" }
class Members::RegistrationsController < Devise::RegistrationsController # before_filter :configure_sign_up_params, only: [:create] # before_filter :configure_account_update_params, only: [:update] # GET /resource/sign_up # def new # super # end # POST /resource # def create # super # end # GET /resource/edit # def edit # super # end # PUT /resource # def update # super # end # DELETE /resource # def destroy # super # end # GET /resource/cancel # Forces the session data which is usually expired after sign # in to be expired now. This is useful if the user wants to # cancel oauth signing in/up in the middle of the process, # removing all OAuth session data. # def cancel # super # end # protected # If you have extra params to permit, append them to the sanitizer. # def configure_sign_up_params # devise_parameter_sanitizer.for(:sign_up) << :attribute # end # If you have extra params to permit, append them to the sanitizer. # def configure_account_update_params # devise_parameter_sanitizer.for(:account_update) << :attribute # end # The path used after sign up. # def after_sign_up_path_for(resource) # super(resource) # end # The path used after sign up for inactive accounts. # def after_inactive_sign_up_path_for(resource) # super(resource) # end end
{ "content_hash": "adb834609efa556ab1eb5c29dfa159cd", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 72, "avg_line_length": 23.1, "alnum_prop": 0.6753246753246753, "repo_name": "NUSComputingDev/beta.nuscomputing.com", "id": "6aa4d21d35f10dbf78d25d61fbe45a5f7e952a6d", "size": "1386", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "app/controllers/members/registrations_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "63445" }, { "name": "CoffeeScript", "bytes": "8566" }, { "name": "HTML", "bytes": "207830" }, { "name": "JavaScript", "bytes": "5100" }, { "name": "Ruby", "bytes": "204143" }, { "name": "Shell", "bytes": "287" } ], "symlink_target": "" }
import json import libvirt import sys from lxml import etree from . import virt_ifaces def _handle_event(conn, domain, event, detail, opaque): msg = dict( type='libvirt', vm=dict( name=domain.name(), uuid=domain.UUIDString(), uri=opaque['uri'], ), ) if event == libvirt.VIR_DOMAIN_EVENT_DEFINED: xml_s = domain.XMLDesc(flags=0) tree = etree.fromstring(xml_s) ifaces = virt_ifaces.get_interfaces(tree) ifaces = list(ifaces) msg['vm']['interfaces'] = ifaces elif event == libvirt.VIR_DOMAIN_EVENT_UNDEFINED: pass else: print >>sys.stderr, \ ('unknown event:' + ' Domain {name} event={event} detail={detail}'.format( name=domain.name(), event=event, detail=detail, ) ) return opaque['callback'](msg) def getAllDomains(conn): """ List and get all domains, active or not. The python bindings don't seem to have this at version 0.9.8-2ubuntu17.1 and a combination of listDefinedDomains and listDomainsID is just miserable. http://libvirt.org/html/libvirt-libvirt.html#virConnectListAllDomains Also fetch the actual domain object, as we'll need the xml. """ for name in conn.listDefinedDomains(): try: domain = conn.lookupByName(name) except libvirt.libvirtError as e: if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN: # lost a race, someone undefined the domain # between listing names and fetching details pass else: raise else: yield domain for id_ in conn.listDomainsID(): try: domain = conn.lookupByID(id_) except libvirt.libvirtError as e: if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN: # lost a race, someone undefined the domain # between listing names and fetching details pass else: raise else: yield domain def monitor(uris, callback): libvirt.virEventRegisterDefaultImpl() conns = {} for uri in uris: conn = libvirt.openReadOnly(uri) conns[uri] = conn conn.setKeepAlive(5, 3) conn.domainEventRegisterAny( dom=None, eventID=libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE, cb=_handle_event, opaque=dict(uri=uri, callback=callback), ) for uri, conn in conns.iteritems(): for domain in getAllDomains(conn): # inject fake defined event for each domain that # exists at startup _handle_event( conn=conn, domain=domain, event=libvirt.VIR_DOMAIN_EVENT_DEFINED, detail=None, opaque=dict(uri=uri, callback=callback), ) # signal that all current vms have been observed; that is, pruning # old entries is safe callback(dict(type='libvirt_complete')) while True: libvirt.virEventRunDefaultImpl() for uri, conn in conns.iteritems(): if not conn.isAlive() == 1: # conn.close() tends to fail at this point, so don't # even try raise RuntimeError( 'Lost connection to {uri}'.format(uri=uri), ) def main(): def cb(msg): sys.stdout.write(json.dumps(msg) + '\n') sys.stdout.flush() uris = sys.argv[1:] monitor(uris, callback=cb) if __name__ == "__main__": main()
{ "content_hash": "14e804d2188b63d7dbd88fdb05ac956a", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 73, "avg_line_length": 28.119402985074625, "alnum_prop": 0.5448513800424628, "repo_name": "ceph/propernoun", "id": "d54b642cb4ef14023be7fc26ca8f9a842e6fd206", "size": "3768", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "propernoun/virt_mon.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "36804" }, { "name": "Shell", "bytes": "272" } ], "symlink_target": "" }
require 'has_distance' require 'rails' module HasDistance class Railtie < ::Rails::Railtie initializer 'has_distance.insert_into_active_record' do ActiveSupport.on_load :active_record do ActiveRecord::Base.send(:include, HasDistance::Distance::Glue) end end end end
{ "content_hash": "62b722981efbc09b4d5b2b1451601c29", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 70, "avg_line_length": 21.5, "alnum_prop": 0.7043189368770764, "repo_name": "fernyb/has_distance", "id": "7054052b0f35cd5208dc843dfc79d77eef1a6238", "size": "301", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/has_distance/railtie.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "17515" } ], "symlink_target": "" }
define(['jquery', 'underscore', 'backbone', 'app', 'entities/element/element_model' ], function($, _, Backbone, StudentManager, Element) { var Elements = Backbone.Collection.extend({ model: Element }); var elementCollectionFromHtml = function() { var lessonDataFromHtml = JSON.parse($('#data-session').html()); var idLesson = lessonDataFromHtml._id; var activities = new ActivityCollection(lessonDataFromHtml.activities, idLesson); return activities; }; var initializeElementCollection = function() { var initializeElements = [ { "resourceUrl": "../../plugins/randomizer/randomizer.html", "gotAnswer": "true", "questionText": "Test Question 1", "answer": "a", "answerTextA":"Question 1 Text for Answer A", "answerTextB":"Question 1 Text for Answer B", "answerTextC":"Question 1 Text for Answer C", "answerTextD":"Question 1 Text for Answer D" }, {"resourceUrl": "../../plugins/airweb/index_b.html", "gotAnswer": "true", "questionText": "Test Question 2", "answer": "b", "answerTextA":"Question 2 Text for Answer A", "answerTextB":"Question 2 Text for Answer B", "answerTextC":"Question 2 Text for Answer C", "answerTextD":"Question 2 Text for Answer D" }, {"resourceUrl": "https://docs.google.com/document/d/1HeNsERfR37ulbmshKaxvhWzkZFvoMIv5vB02YikswuQ/preview", "gotAnswer": "true", "questionText": "Test Question 3", "answer": "c", "answerTextA":"Question 3 Text for Answer A", "answerTextB":"Question 3 Text for Answer B", "answerTextC":"Question 3 Text for Answer C", "answerTextD":"Question 3 Text for Answer D" }, {"resourceUrl": "https://docs.google.com/document/d/1HeNsERfR37ulbmshKaxvhWzkZFvoMIv5vB02YikswuQ/preview", "gotAnswer": "true", "questionText": "Test Question 4", "answer": "d", "answerTextA":"Question 4 Text for Answer A", "answerTextB":"Question 4 Text for Answer B", "answerTextC":"Question 4 Text for Answer C", "answerTextD":"Question 4 Text for Answer D" }, {"resourceUrl": "https://docs.google.com/document/d/1HeNsERfR37ulbmshKaxvhWzkZFvoMIv5vB02YikswuQ/preview", "gotAnswer": "false", "questionText": "Test Question 5", "answer": ""} ]; var elementsInJSON = JSON.parse(JSON.stringify(initializeElements)); return new Elements(elementsInJSON); }; var initializeTestElementCollection = function() { var element1 = new Element({gotAnswer:"false",questionText: "Test Question 1"}); var element2 = new Element({gotAnswer:"false",questionText: "Test Question 2"}); var element3 = new Element({gotAnswer:"false",questionText: "Test Question 3"}); return new Elements([element1,element2,element3]); }; API = { getElementEntities: function() { //Get it from the activities collection }, getElementEntititesFromHTML: function() { //Initialized the first time can get it from the HTML return initializeElementCollection(); } }; StudentManager.reqres.setHandler("element:entities", function() { return API.getElementEntities(); }); StudentManager.reqres.setHandler("element:entities:initialize", function() { return API.getElementEntititesFromHTML(); }); return Elements; } );
{ "content_hash": "90d800e0cd2c2bb0fe9473c6b40a6822", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 191, "avg_line_length": 43.90217391304348, "alnum_prop": 0.5516216885367665, "repo_name": "pointable/hitcamp", "id": "86cb3615ae55256566c3a90af450f8e1342d1dae", "size": "4039", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/webappSession/js/entities/element/element_collection.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "477060" }, { "name": "HTML", "bytes": "686756" }, { "name": "JavaScript", "bytes": "5737745" }, { "name": "PHP", "bytes": "2199" }, { "name": "Shell", "bytes": "321" } ], "symlink_target": "" }
package com.lightbend.lagom.scaladsl.broker.kafka import com.lightbend.lagom.internal.scaladsl.broker.kafka.ScaladslRegisterTopicProducers import com.lightbend.lagom.scaladsl.api.ServiceLocator import com.lightbend.lagom.scaladsl.projection.ProjectionComponents import com.lightbend.lagom.scaladsl.server.LagomServer import com.lightbend.lagom.spi.persistence.OffsetStore /** * Components for including Kafka into a Lagom application. * * Extending this trait will automatically start all topic producers. */ trait LagomKafkaComponents extends LagomKafkaClientComponents with ProjectionComponents { def lagomServer: LagomServer def offsetStore: OffsetStore def serviceLocator: ServiceLocator override def topicPublisherName: Option[String] = super.topicPublisherName match { case Some(other) => sys.error( s"Cannot provide the kafka topic factory as the default topic publisher since a default topic publisher has already been mixed into this cake: $other" ) case None => Some("kafka") } // Eagerly start topic producers new ScaladslRegisterTopicProducers( lagomServer, topicFactory, serviceInfo, actorSystem, offsetStore, serviceLocator, projectionRegistry )( executionContext, materializer ) }
{ "content_hash": "4aa6a535e6ad52524b3f4d075667ff2a", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 158, "avg_line_length": 30.666666666666668, "alnum_prop": 0.7771739130434783, "repo_name": "lagom/lagom", "id": "5e8b4ccc5e50b08610100eb8b9d3f6942cf5dfe7", "size": "1354", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "service/scaladsl/kafka/server/src/main/scala/com/lightbend/lagom/scaladsl/broker/kafka/LagomKafkaComponents.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "559" }, { "name": "Java", "bytes": "1037365" }, { "name": "JavaScript", "bytes": "48" }, { "name": "Less", "bytes": "348" }, { "name": "Perl", "bytes": "1102" }, { "name": "Roff", "bytes": "6976" }, { "name": "Scala", "bytes": "1961298" }, { "name": "Shell", "bytes": "8238" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.execution; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListenableFuture; import io.trino.Session; import io.trino.connector.CatalogName; import io.trino.execution.warnings.WarningCollector; import io.trino.metadata.Metadata; import io.trino.metadata.QualifiedObjectName; import io.trino.security.AccessControl; import io.trino.security.InjectedConnectorAccessControl; import io.trino.spi.TrinoException; import io.trino.spi.block.BlockBuilder; import io.trino.spi.connector.ConnectorAccessControl; import io.trino.spi.connector.ConnectorSession; import io.trino.spi.eventlistener.RoutineInfo; import io.trino.spi.procedure.Procedure; import io.trino.spi.procedure.Procedure.Argument; import io.trino.spi.type.Type; import io.trino.sql.planner.ParameterRewriter; import io.trino.sql.tree.Call; import io.trino.sql.tree.CallArgument; import io.trino.sql.tree.Expression; import io.trino.sql.tree.ExpressionTreeRewriter; import io.trino.sql.tree.NodeRef; import io.trino.sql.tree.Parameter; import io.trino.transaction.TransactionManager; import java.lang.invoke.MethodType; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.function.Predicate; import static com.google.common.base.Throwables.throwIfInstanceOf; import static com.google.common.base.Verify.verify; import static com.google.common.util.concurrent.Futures.immediateVoidFuture; import static io.trino.metadata.MetadataUtil.createQualifiedObjectName; import static io.trino.spi.StandardErrorCode.CATALOG_NOT_FOUND; import static io.trino.spi.StandardErrorCode.INVALID_ARGUMENTS; import static io.trino.spi.StandardErrorCode.INVALID_PROCEDURE_ARGUMENT; import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED; import static io.trino.spi.StandardErrorCode.PROCEDURE_CALL_FAILED; import static io.trino.spi.type.TypeUtils.writeNativeValue; import static io.trino.sql.ParameterUtils.parameterExtractor; import static io.trino.sql.analyzer.SemanticExceptions.semanticException; import static io.trino.sql.planner.ExpressionInterpreter.evaluateConstantExpression; import static java.util.Arrays.asList; public class CallTask implements DataDefinitionTask<Call> { @Override public String getName() { return "CALL"; } @Override public ListenableFuture<Void> execute( Call call, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters, WarningCollector warningCollector) { if (!transactionManager.isAutoCommit(stateMachine.getSession().getRequiredTransactionId())) { throw new TrinoException(NOT_SUPPORTED, "Procedures cannot be called within a transaction (use autocommit mode)"); } Session session = stateMachine.getSession(); QualifiedObjectName procedureName = createQualifiedObjectName(session, call, call.getName()); CatalogName catalogName = metadata.getCatalogHandle(stateMachine.getSession(), procedureName.getCatalogName()) .orElseThrow(() -> semanticException(CATALOG_NOT_FOUND, call, "Catalog '%s' does not exist", procedureName.getCatalogName())); Procedure procedure = metadata.getProcedureRegistry().resolve(catalogName, procedureName.asSchemaTableName()); // map declared argument names to positions Map<String, Integer> positions = new HashMap<>(); for (int i = 0; i < procedure.getArguments().size(); i++) { positions.put(procedure.getArguments().get(i).getName(), i); } // per specification, do not allow mixing argument types Predicate<CallArgument> hasName = argument -> argument.getName().isPresent(); boolean anyNamed = call.getArguments().stream().anyMatch(hasName); boolean allNamed = call.getArguments().stream().allMatch(hasName); if (anyNamed && !allNamed) { throw semanticException(INVALID_ARGUMENTS, call, "Named and positional arguments cannot be mixed"); } // get the argument names in call order Map<String, CallArgument> names = new LinkedHashMap<>(); for (int i = 0; i < call.getArguments().size(); i++) { CallArgument argument = call.getArguments().get(i); if (argument.getName().isPresent()) { String name = argument.getName().get(); if (names.put(name, argument) != null) { throw semanticException(INVALID_ARGUMENTS, argument, "Duplicate procedure argument: %s", name); } if (!positions.containsKey(name)) { throw semanticException(INVALID_ARGUMENTS, argument, "Unknown argument name: %s", name); } } else if (i < procedure.getArguments().size()) { names.put(procedure.getArguments().get(i).getName(), argument); } else { throw semanticException(INVALID_ARGUMENTS, call, "Too many arguments for procedure"); } } procedure.getArguments().stream() .filter(Argument::isRequired) .filter(argument -> !names.containsKey(argument.getName())) .map(Argument::getName) .findFirst() .ifPresent(argument -> { throw semanticException(INVALID_ARGUMENTS, call, "Required procedure argument '%s' is missing", argument); }); // get argument values Object[] values = new Object[procedure.getArguments().size()]; Map<NodeRef<Parameter>, Expression> parameterLookup = parameterExtractor(call, parameters); for (Entry<String, CallArgument> entry : names.entrySet()) { CallArgument callArgument = entry.getValue(); int index = positions.get(entry.getKey()); Argument argument = procedure.getArguments().get(index); Expression expression = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(parameterLookup), callArgument.getValue()); Type type = argument.getType(); Object value = evaluateConstantExpression(expression, type, metadata, session, accessControl, parameterLookup); values[index] = toTypeObjectValue(session, type, value); } // fill values with optional arguments defaults for (int i = 0; i < procedure.getArguments().size(); i++) { Argument argument = procedure.getArguments().get(i); if (!names.containsKey(argument.getName())) { verify(argument.isOptional()); values[i] = toTypeObjectValue(session, argument.getType(), argument.getDefaultValue()); } } // validate arguments MethodType methodType = procedure.getMethodHandle().type(); for (int i = 0; i < procedure.getArguments().size(); i++) { if ((values[i] == null) && methodType.parameterType(i).isPrimitive()) { String name = procedure.getArguments().get(i).getName(); throw new TrinoException(INVALID_PROCEDURE_ARGUMENT, "Procedure argument cannot be null: " + name); } } // insert session argument List<Object> arguments = new ArrayList<>(); Iterator<Object> valuesIterator = asList(values).iterator(); for (Class<?> type : methodType.parameterList()) { if (ConnectorSession.class.equals(type)) { arguments.add(session.toConnectorSession(catalogName)); } else if (ConnectorAccessControl.class.equals(type)) { arguments.add(new InjectedConnectorAccessControl(accessControl, session.toSecurityContext(), catalogName.getCatalogName())); } else { arguments.add(valuesIterator.next()); } } accessControl.checkCanExecuteProcedure(session.toSecurityContext(), procedureName); stateMachine.setRoutines(ImmutableList.of(new RoutineInfo(procedureName.getObjectName(), session.getUser()))); try { procedure.getMethodHandle().invokeWithArguments(arguments); } catch (Throwable t) { if (t instanceof InterruptedException) { Thread.currentThread().interrupt(); } throwIfInstanceOf(t, TrinoException.class); throw new TrinoException(PROCEDURE_CALL_FAILED, t); } return immediateVoidFuture(); } private static Object toTypeObjectValue(Session session, Type type, Object value) { BlockBuilder blockBuilder = type.createBlockBuilder(null, 1); writeNativeValue(type, blockBuilder, value); return type.getObjectValue(session.toConnectorSession(), blockBuilder, 0); } }
{ "content_hash": "0d94510bcb3c28dd7988373b8468409f", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 142, "avg_line_length": 45.17370892018779, "alnum_prop": 0.679692371648306, "repo_name": "losipiuk/presto", "id": "9c5c3d5eeb8f82709ecef9196d6a3c1896de5753", "size": "9622", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "core/trino-main/src/main/java/io/trino/execution/CallTask.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "17768" }, { "name": "HTML", "bytes": "44136" }, { "name": "Java", "bytes": "11610150" }, { "name": "JavaScript", "bytes": "1431" }, { "name": "Makefile", "bytes": "6819" }, { "name": "PLSQL", "bytes": "3849" }, { "name": "Python", "bytes": "4481" }, { "name": "SQLPL", "bytes": "6363" }, { "name": "Shell", "bytes": "2069" } ], "symlink_target": "" }
#include "UnitTestPCH.h" #include <assimp/IOStreamBuffer.h> #include "TestIOStream.h" #include "UnitTestFileGenerator.h" class IOStreamBufferTest : public ::testing::Test { // empty }; using namespace Assimp; TEST_F( IOStreamBufferTest, creationTest ) { bool ok( true ); try { IOStreamBuffer<char> myBuffer; } catch ( ... ) { ok = false; } EXPECT_TRUE( ok ); } TEST_F( IOStreamBufferTest, accessCacheSizeTest ) { IOStreamBuffer<char> myBuffer1; EXPECT_NE( 0U, myBuffer1.cacheSize() ); IOStreamBuffer<char> myBuffer2( 100 ); EXPECT_EQ( 100U, myBuffer2.cacheSize() ); } const char data[]{"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Qui\ sque luctus sem diam, ut eleifend arcu auctor eu. Vestibulum id est vel nulla l\ obortis malesuada ut sed turpis. Nulla a volutpat tortor. Nunc vestibulum portt\ itor sapien ornare sagittis volutpat."}; TEST_F( IOStreamBufferTest, open_close_Test ) { IOStreamBuffer<char> myBuffer; EXPECT_FALSE( myBuffer.open( nullptr ) ); EXPECT_FALSE( myBuffer.close() ); const auto dataSize = sizeof(data); const auto dataCount = dataSize / sizeof(*data); char fname[]={ "octest.XXXXXX" }; auto* fs = MakeTmpFile(fname); ASSERT_NE(nullptr, fs); auto written = std::fwrite( data, sizeof(*data), dataCount, fs ); EXPECT_NE( 0U, written ); auto flushResult = std::fflush( fs ); ASSERT_EQ(0, flushResult); std::fclose( fs ); fs = std::fopen(fname, "r"); ASSERT_NE(nullptr, fs); { TestDefaultIOStream myStream( fs, fname ); EXPECT_TRUE( myBuffer.open( &myStream ) ); EXPECT_FALSE( myBuffer.open( &myStream ) ); EXPECT_TRUE( myBuffer.close() ); } remove(fname); } TEST_F( IOStreamBufferTest, readlineTest ) { const auto dataSize = sizeof(data); const auto dataCount = dataSize / sizeof(*data); char fname[]={ "readlinetest.XXXXXX" }; auto* fs = MakeTmpFile(fname); ASSERT_NE(nullptr, fs); auto written = std::fwrite( data, sizeof(*data), dataCount, fs ); EXPECT_NE( 0U, written ); auto flushResult = std::fflush(fs); ASSERT_EQ(0, flushResult); std::fclose(fs); fs = std::fopen(fname, "r"); ASSERT_NE(nullptr, fs); const auto tCacheSize = 26u; IOStreamBuffer<char> myBuffer( tCacheSize ); EXPECT_EQ(tCacheSize, myBuffer.cacheSize() ); TestDefaultIOStream myStream( fs, fname ); auto size = myStream.FileSize(); auto numBlocks = size / myBuffer.cacheSize(); if ( size % myBuffer.cacheSize() > 0 ) { numBlocks++; } EXPECT_TRUE( myBuffer.open( &myStream ) ); EXPECT_EQ( numBlocks, myBuffer.getNumBlocks() ); EXPECT_TRUE( myBuffer.close() ); } TEST_F( IOStreamBufferTest, accessBlockIndexTest ) { }
{ "content_hash": "92cad0644ed08217188f91a4682d04c7", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 80, "avg_line_length": 26.61904761904762, "alnum_prop": 0.6536672629695885, "repo_name": "jlukacs/aqua", "id": "41575fa59475874be1129ba87d85c469a3132db1", "size": "4582", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/assimp/test/unit/utIOStreamBuffer.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "89079" }, { "name": "Assembly", "bytes": "138199" }, { "name": "Batchfile", "bytes": "10385" }, { "name": "C", "bytes": "1793320" }, { "name": "C#", "bytes": "54013" }, { "name": "C++", "bytes": "16282798" }, { "name": "CMake", "bytes": "307574" }, { "name": "COBOL", "bytes": "2921725" }, { "name": "CSS", "bytes": "30394" }, { "name": "D", "bytes": "175405" }, { "name": "DIGITAL Command Language", "bytes": "901" }, { "name": "GLSL", "bytes": "5111" }, { "name": "HLSL", "bytes": "620" }, { "name": "HTML", "bytes": "15024192" }, { "name": "Inno Setup", "bytes": "7722" }, { "name": "Java", "bytes": "311787" }, { "name": "JavaScript", "bytes": "285639" }, { "name": "M4", "bytes": "19880" }, { "name": "Makefile", "bytes": "20288" }, { "name": "Objective-C", "bytes": "112041" }, { "name": "Objective-C++", "bytes": "29142" }, { "name": "Pascal", "bytes": "55467" }, { "name": "Python", "bytes": "601980" }, { "name": "RPC", "bytes": "2952312" }, { "name": "Roff", "bytes": "3323" }, { "name": "Ruby", "bytes": "4830" }, { "name": "ShaderLab", "bytes": "718" }, { "name": "Shell", "bytes": "22444" }, { "name": "Smarty", "bytes": "169" }, { "name": "UnrealScript", "bytes": "1273" } ], "symlink_target": "" }
package uk.co.johnjtaylor.events; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; import uk.co.johnjtaylor.events.generic.Event; import uk.co.johnjtaylor.events.listeners.Listener; import uk.co.johnjtaylor.events.listeners.ListenerList; /** * Handles Listener registration, de-registration and * the dispatching of events * @author John * */ public class EventDispatcher { private static HashMap<EventType, ListenerList> eventListeners = new HashMap<>(); private static Queue<Event> eventQueue = new LinkedList<Event>(); /** * EventDispatcher eventListener list construction; * Populates the eventListeners HashMap with every possible * event having an empty list of listeners (ListenerList) * associated with it. */ public static void prepareEventListenerRegister() { for(EventType evtType : EventType.values()) { eventListeners.put(evtType, new ListenerList()); } //startDispatchingQueuedEvents(); } /** * Registers a new listener to a particular type of event * @param event EventType(enum) - The given type of event to attach this listener to * @param listener The event handler/listener to be attached to the given event type */ public static void registerListener(EventType event, Listener listener) { ListenerList currentlisteners = eventListeners.get(event); currentlisteners.add(listener); // Update current ListenerList eventListeners.remove(event); eventListeners.put(event, currentlisteners); } /** * Remove a registered listener from a particular set of events * @param event The event that the target listener is attached to * @param listener The target listener to be removed from this event */ public static void unregisterListener(EventType event, Listener listener) { ListenerList currentListeners = eventListeners.get(event); currentListeners.remove(listener); eventListeners.remove(event); eventListeners.put(event, currentListeners); } public static void requestInvoke(Event e) { eventQueue.add(e); } /** * Handles the dispatching of events to all appropriate listeners * @param event the event to dispatch * @deprecated replaced by startDisaptchingQueuedEvents and event queueing methods */ @Deprecated private static synchronized void dispatch(Event event) { for(Listener currListener : eventListeners.get(event.getEventType())) { event.getEventType().invoke(event, currListener); } } private static void startDispatchingQueuedEvents() { Timer scheduler = new Timer(); TimerTask invokeEvents = new TimerTask() { @Override public void run() { if(eventQueue.peek() != null) { Event targetEvent = eventQueue.poll(); for(Listener currListener : eventListeners.get(targetEvent.getEventType())) { targetEvent.getEventType().invoke(targetEvent, currListener); } } } }; scheduler.scheduleAtFixedRate(invokeEvents, 0L, 000000000000000000000000000001L); } }
{ "content_hash": "5ddc005d036faffb50f17ae09eec0e59", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 85, "avg_line_length": 34.422222222222224, "alnum_prop": 0.7307940606843124, "repo_name": "YcleptJohn/SortAnalytics", "id": "62f2010f96c7c1718040cf71b49b3ab8d2831ae3", "size": "3098", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/uk/co/johnjtaylor/events/EventDispatcher.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "48622" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>es.upm.fi.oeg.anp</groupId> <artifactId>jRIDER</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>jama</groupId> <artifactId>jama</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.1.1</version> <scope>test</scope> </dependency> <dependency> <groupId>thewebsemantic</groupId> <artifactId>jenabean</artifactId> <version>1.0.7</version> </dependency> </dependencies> <repositories> <repository> <id>mbari-maven-repository</id> <name>MBARI</name> <url>http://mbari-maven-repository.googlecode.com/svn/repository/</url> </repository> <repository> <id>Jenabean</id> <url>http://jenabean.googlecode.com/svn/repo</url> </repository> </repositories> </project>
{ "content_hash": "d0c4c6179a4cfc75921c3e5dee2349b8", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 104, "avg_line_length": 27.452380952380953, "alnum_prop": 0.6617519514310495, "repo_name": "filiprd/jRIDER", "id": "05e753fecf57882ba10e7dea05cffaafe0f80edf", "size": "1153", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "156690" } ], "symlink_target": "" }
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Rare Crowds Inc"> // Copyright 2012-2013 Rare Crowds, 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. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AppNexusClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rare Crowds Inc")] [assembly: AssemblyProduct("AppNexusClient")] [assembly: AssemblyCopyright("Copyright © Rare Crowds Inc 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3f5edd21-d186-4be1-ae43-a2b280becd25")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("AppNexusClientUnitTests")] [assembly: InternalsVisibleTo("AppNexusActivitiesUnitTests")] [assembly: InternalsVisibleTo("AppNexusClientE2ETests")] [assembly: InternalsVisibleTo("AppNexusActivitiesE2ETests")] [assembly: InternalsVisibleTo("AppNexusTestUtilities")] [assembly: InternalsVisibleTo("AppNexusSegments")] [assembly: InternalsVisibleTo("AppNexusDataCosts")] [assembly: InternalsVisibleTo("RuntimeIoc.WorkerRole")]
{ "content_hash": "32fe1cfb52be1a3846a98040a2c9e120", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 84, "avg_line_length": 43.34920634920635, "alnum_prop": 0.7151226656902233, "repo_name": "chinnurtb/OpenAdStack", "id": "9de21f960e8beb61c996e0a6e3fab6233ccf471e", "size": "2734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AppNexusActivities/AppNexusClient/Properties/AssemblyInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System.Collections; namespace Igloo.Clinic.Domain { public interface ICart : IList { } }
{ "content_hash": "e410b25616b17cb75cb2943fd2682a91", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 34, "avg_line_length": 12.11111111111111, "alnum_prop": 0.6697247706422018, "repo_name": "castleproject/castle-READONLY-SVN-dump", "id": "9877e789db7f2915e2aa6d04390ffdeba1498444", "size": "109", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Experiments/Castle.Igloo/Igloo.Clinic.Domain/ICart.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "11215" }, { "name": "Boo", "bytes": "46194" }, { "name": "C#", "bytes": "2922166" }, { "name": "JavaScript", "bytes": "138530" }, { "name": "Python", "bytes": "187" } ], "symlink_target": "" }
<?php namespace Database\Factories; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; class UserFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = User::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'name' => $this->faker->name(), 'email' => $this->faker->unique()->safeEmail(), 'email_verified_at' => now(), 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 'remember_token' => Str::random(10), ]; } /** * Indicate that the model's email address should be unverified. * * @return \Illuminate\Database\Eloquent\Factories\Factory */ public function unverified() { return $this->state(function (array $attributes) { return [ 'email_verified_at' => null, ]; }); } }
{ "content_hash": "6a8e158bb103d9736f006184d4a41ee3", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 101, "avg_line_length": 23.80851063829787, "alnum_prop": 0.5558534405719392, "repo_name": "bugsnag/bugsnag-laravel", "id": "a24ce53f5372e30f04d79b56b436102441095465", "size": "1119", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "features/fixtures/laravel8/database/factories/UserFactory.php", "mode": "33188", "license": "mit", "language": [ { "name": "Blade", "bytes": "67259" }, { "name": "Dockerfile", "bytes": "2330" }, { "name": "Gherkin", "bytes": "26528" }, { "name": "JavaScript", "bytes": "1006" }, { "name": "Makefile", "bytes": "666" }, { "name": "PHP", "bytes": "1074653" }, { "name": "Ruby", "bytes": "7244" }, { "name": "SCSS", "bytes": "144" }, { "name": "Shell", "bytes": "11829" }, { "name": "Vue", "bytes": "1669" } ], "symlink_target": "" }
 #pragma once #include <aws/apprunner/AppRunner_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace AppRunner { namespace Model { enum class Runtime { NOT_SET, PYTHON_3, NODEJS_12, NODEJS_14, CORRETTO_8, CORRETTO_11, NODEJS_16, GO_1, DOTNET_6, PHP_81, RUBY_31 }; namespace RuntimeMapper { AWS_APPRUNNER_API Runtime GetRuntimeForName(const Aws::String& name); AWS_APPRUNNER_API Aws::String GetNameForRuntime(Runtime value); } // namespace RuntimeMapper } // namespace Model } // namespace AppRunner } // namespace Aws
{ "content_hash": "7d6223f8a3ab28f35491944567a875d4", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 69, "avg_line_length": 16.833333333333332, "alnum_prop": 0.6914191419141914, "repo_name": "aws/aws-sdk-cpp", "id": "1d69edd295d69372c062d3c939607f2471056cbe", "size": "725", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "aws-cpp-sdk-apprunner/include/aws/apprunner/model/Runtime.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309797" }, { "name": "C++", "bytes": "476866144" }, { "name": "CMake", "bytes": "1245180" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "8056" }, { "name": "Java", "bytes": "413602" }, { "name": "Python", "bytes": "79245" }, { "name": "Shell", "bytes": "9246" } ], "symlink_target": "" }
/** * * @author mg * @module */ function PlainPropertiesTest() { var self = this, model = P.loadModel(this.constructor.name); var comps = [new P.AbsolutePane() , new P.AnchorsPane() , new P.BorderPane() , new P.BoxPane() , new P.Button() , new P.CardPane() , new P.CheckBox() , new P.DesktopPane() , new P.DropDownButton() , new P.FlowPane() , new P.FormattedField() , new P.GridPane(10, 10) , new P.HtmlArea() , new P.Label() , new P.ModelCheckBox() , new P.ModelCombo() , new P.ModelDate() , new P.ModelFormattedField() , new P.ModelGrid() //, new P.ModelImage() //, new P.ModelMap() //, new P.ModelScheme() , new P.ModelSpin() , new P.ModelTextArea() , new P.PasswordField() , new P.ProgressBar() , new P.RadioButton() , new P.ScrollPane() , new P.SplitPane() , new P.TabbedPane() , new P.TextArea() , new P.TextField() , new P.ToggleButton() , new P.ToolBar() , new P.Menu() , new P.MenuItem() , new P.MenuSeparator() , new P.CheckMenuItem() , new P.RadioMenuItem() ]; for (var c in comps) { var comp = comps[c]; comp.visible = true; if (!comp.visible) throw 'comp.visible mismatch'; comp.visible = false; if (comp.visible) throw 'comp.visible mismatch'; comp.enabled = true; if (!comp.enabled) throw 'comp.enabled mismatch'; comp.enabled = false; if (comp.enabled) throw 'comp.enabled mismatch'; comp.toolTipText = 'some tooltip text'; if (comp.toolTipText !== 'some tooltip text') throw 'comp.toolTipText mismatch'; comp.toolTipText = null; if (comp.toolTipText) throw 'comp.toolTipText mismatch'; comp.background = P.Color.BLUE; if (comp.background !== P.Color.BLUE) throw 'comp.background mismatch'; comp.background = null; if (comp.background) throw 'comp.background mismatch'; comp.foreground = P.Color.RED; if (comp.foreground !== P.Color.RED) throw 'comp.foreground mismatch'; comp.foreground = null; if (comp.foreground) throw 'comp.foreground mismatch'; comp.opaque = true; if (!comp.opaque) throw 'comp.opaque mismatch'; comp.opaque = false; if (comp.opaque) throw 'comp.opaque mismatch'; var compFont = new P.Font('arial', P.FontStyle.BOLD, 12); comp.font = compFont; if (comp.font !== compFont) throw 'comp.font mismatch'; comp.font = null; if (comp.font) throw 'comp.font mismatch'; comp.cursor = P.Cursor.WAIT; if (comp.cursor !== P.Cursor.WAIT) throw 'comp.cursor mismatch'; comp.cursor = null; if (comp.cursor) throw 'comp.cursor mismatch'; comp.left = 25; if (comp.left !== 25) throw 'comp.left mismatch'; comp.left = 0; if (comp.left) throw 'comp.left mismatch'; comp.top = 58; if (comp.top !== 58) throw 'comp.top mismatch'; comp.top = 0; if (comp.top) throw 'comp.top mismatch'; comp.width = 89; if (comp.width !== 89) throw 'comp.width mismatch'; comp.width = 0; if (comp.width) throw 'comp.width mismatch'; comp.height = 96; if (comp.height !== 96) throw 'comp.height mismatch'; comp.height = 0; if (comp.height) throw 'comp.height mismatch'; if (!(comp instanceof P.Menu) && !(comp instanceof P.PopupMenu) && !(comp instanceof P.MenuItem) && !(comp instanceof P.MenuSeparator) && !(comp instanceof P.CheckMenuItem) && !(comp instanceof P.RadioMenuItem)) { var compMenu = new P.PopupMenu(); comp.componentPopupMenu = compMenu; if (comp.componentPopupMenu !== compMenu) throw 'comp.componentPopupMenu mmismatch'; comp.componentPopupMenu = null; if (comp.componentPopupMenu) throw 'comp.componentPopupMenu mmismatch'; } /// if (P.agent === P.HTML5 && !comp.element) throw 'comp.element mismatch'; if (P.agent === P.J2SE && !comp.component){ var c = comp.component; throw 'comp.component mismatch'; } /// var f = function() { }; comp.onActionPerformed = f; if (comp.onActionPerformed !== f) { throw 'comp.onActionPerformed mismatch'; } comp.onActionPerformed = null; if (comp.onActionPerformed) throw 'comp.onActionPerformed mismatch'; comp.onMouseExited = f; if (comp.onMouseExited !== f) throw 'comp.onMouseExited mismatch'; comp.onMouseExited = null; if (comp.onMouseExited) throw 'comp.onMouseExited mismatch'; comp.onMouseClicked = f; if (comp.onMouseClicked !== f) throw 'comp.onMouseClicked mismatch'; comp.onMouseClicked = null; if (comp.onMouseClicked) throw 'comp.onMouseClicked mismatch'; comp.onMousePressed = f; if (comp.onMousePressed !== f) throw 'comp.onMousePressed mismatch'; comp.onMousePressed = null; if (comp.onMousePressed) throw 'comp.onMousePressed mismatch'; comp.onMouseReleased = f; if (comp.onMouseReleased !== f) throw 'comp.onMouseReleased mismatch'; comp.onMouseReleased = null; if (comp.onMouseReleased) throw 'comp.onMouseReleased mismatch'; comp.onMouseEntered = f; if (comp.onMouseEntered !== f) throw 'comp.onMouseEntered mmismatch'; comp.onMouseEntered = null; if (comp.onMouseEntered) throw 'comp.onMouseEntered mmismatch'; comp.onMouseWheelMoved = f; if (comp.onMouseWheelMoved !== f) throw 'comp.onMouseWheelMoved mismatch'; comp.onMouseWheelMoved = null; if (comp.onMouseWheelMoved) throw 'comp.onMouseWheelMoved mismatch'; comp.onMouseDragged = f; if (comp.onMouseDragged !== f) throw 'comp.onMouseDragged mismatch'; comp.onMouseDragged = null; if (comp.onMouseDragged) throw 'comp.onMouseDragged mismatch'; comp.onMouseMoved = f; if (comp.onMouseMoved !== f) throw 'comp.onMouseMoved mismatch'; comp.onMouseMoved = null; if (comp.onMouseMoved) throw 'comp.onMouseMoved mismatch'; comp.onComponentResized = f; if (comp.onComponentResized !== f) throw 'comp.onComponentResized mismatch' comp.onComponentResized = null; if (comp.onComponentResized) throw 'comp.onComponentResized mismatch' comp.onComponentMoved = f; if (comp.onComponentMoved !== f) throw 'comp.onComponentMoved mismatch'; comp.onComponentMoved = null; if (comp.onComponentMoved) throw 'comp.onComponentMoved mismatch'; comp.onComponentShown = f; if (comp.onComponentShown !== f) throw 'comp.onComponentShown mismatch'; comp.onComponentShown = null; if (comp.onComponentShown) throw 'comp.onComponentShown mismatch'; comp.onComponentHidden = f; if (comp.onComponentHidden !== f) throw 'comp.onComponentHidden mismatch'; comp.onComponentAdded = f; if (comp.onComponentAdded !== f) throw 'comp.onComponentAdded mismatch'; comp.onComponentAdded = null; if (comp.onComponentAdded) throw 'comp.onComponentAdded mismatch'; comp.onComponentRemoved = f; if (comp.onComponentRemoved !== f) throw 'comp.onComponentRemoved mismatch'; comp.onComponentRemoved = null; if (comp.onComponentRemoved) throw 'comp.onComponentRemoved mismatch'; comp.onFocusGained = f; if (comp.onFocusGained !== f) throw 'comp.onFocusGained mismatch'; comp.onFocusGained = null; if (comp.onFocusGained) throw 'comp.onFocusGained mismatch'; comp.onFocusLost = f; if (comp.onFocusLost !== f) throw 'comp.onFocusLost mismatch'; comp.onFocusLost = null; if (comp.onFocusLost) throw 'comp.onFocusLost mismatch'; comp.onKeyTyped = f; if (comp.onKeyTyped !== f) throw 'comp.onKeyTyped mismatch'; comp.onKeyTyped = null; if (comp.onKeyTyped) throw 'comp.onKeyTyped mismatch'; comp.onKeyPressed = f; if (comp.onKeyPressed !== f) throw 'comp.onKeyPressed mismatch'; comp.onKeyPressed = null; if (comp.onKeyPressed) throw 'comp.onKeyPressed mismatch'; comp.onKeyReleased = f; if (comp.onKeyReleased !== f) throw 'comp.onKeyReleased mismatch'; comp.onKeyReleased = null; if (comp.onKeyReleased) throw 'comp.onKeyReleased mismatch'; /// comp.focus(); } var comp = new P.DropDownButton(); var menu = new P.PopupMenu(); comp.dropDownMenu = menu; if (comp.dropDownMenu !== menu) { throw 'comp.dropDownMenu mismatch'; } comp.dropDownMenu = null; if (comp.dropDownMenu) { throw 'comp.dropDownMenu mismatch'; } var alignedTextComps = [ new P.Label() , new P.Button() , new P.DropDownButton() , new P.ToggleButton() , new P.MenuItem() ]; for (var c in alignedTextComps) { var comp = alignedTextComps[c]; // horizontalTextPosition comp.horizontalTextPosition = P.HorizontalPosition.LEFT; if (comp.horizontalTextPosition !== P.HorizontalPosition.LEFT) throw 'comp.horizontalTextPosition mismatch'; comp.horizontalTextPosition = P.HorizontalPosition.CENTER; if (comp.horizontalTextPosition !== P.HorizontalPosition.CENTER) throw 'comp.horizontalTextPosition mismatch'; comp.horizontalTextPosition = P.HorizontalPosition.RIGHT; if (comp.horizontalTextPosition !== P.HorizontalPosition.RIGHT) throw 'comp.horizontalTextPosition mismatch'; //verticalTextPosition comp.verticalTextPosition = P.VerticalPosition.TOP; if (comp.verticalTextPosition !== P.VerticalPosition.TOP) throw 'comp.verticalTextPosition mismatch'; comp.verticalTextPosition = P.VerticalPosition.CENTER; if (comp.verticalTextPosition !== P.VerticalPosition.CENTER) throw 'comp.verticalTextPosition mismatch'; comp.verticalTextPosition = P.VerticalPosition.BOTTOM; if (comp.verticalTextPosition !== P.VerticalPosition.BOTTOM) throw 'comp.verticalTextPosition mismatch'; //horizontalAlignment comp.horizontalAlignment = P.HorizontalPosition.LEFT; if (comp.horizontalAlignment !== P.HorizontalPosition.LEFT) throw 'comp.horizontalAlignment mismatch'; comp.horizontalAlignment = P.HorizontalPosition.CENTER; if (comp.horizontalAlignment !== P.HorizontalPosition.CENTER) throw 'comp.horizontalAlignment mismatch'; comp.horizontalAlignment = P.HorizontalPosition.RIGHT; if (comp.horizontalAlignment !== P.HorizontalPosition.RIGHT) throw 'comp.horizontalAlignment mismatch'; //verticalAlignment comp.verticalAlignment = P.VerticalPosition.TOP; if (comp.verticalAlignment !== P.VerticalPosition.TOP) throw 'comp.verticalAlignment mismatch'; comp.verticalAlignment = P.VerticalPosition.CENTER; if (comp.verticalAlignment !== P.VerticalPosition.CENTER) throw 'comp.verticalAlignment mismatch'; comp.verticalAlignment = P.VerticalPosition.BOTTOM; if (comp.verticalAlignment !== P.VerticalPosition.BOTTOM) throw 'comp.verticalAlignment mismatch'; //iconTexGap comp.iconTextGap = 6; if (comp.iconTextGap !== 6) throw 'comp.iconTextGap mismatch'; //icon var compIcon = P.Icon.load('UI tests/point.png'); comp.icon = compIcon; if (comp.icon !== compIcon) throw 'comp.icon mismatch'; comp.icon = null; if (comp.icon) throw 'comp.icon mismatch'; } (function() { if (self.onSuccess) { self.onSuccess(); } else { P.Logger.severe("self.onSuccess is absent. So unable to report about test's result"); } }).invokeLater(); }
{ "content_hash": "f3ea91fefa37b861652b1ac9b445a037", "timestamp": "", "source": "github", "line_count": 352, "max_line_length": 97, "avg_line_length": 39.39488636363637, "alnum_prop": 0.552751135790005, "repo_name": "marat-gainullin/PlatypusJS", "id": "68af64f7f808a9d7cf068cf9f412d66a81ae569d", "size": "13867", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "platypus-js-tests/src/main/webapp/app/UI tests/Cases/plain properties test.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "45399" }, { "name": "HTML", "bytes": "4781642" }, { "name": "Java", "bytes": "6407589" }, { "name": "JavaScript", "bytes": "474478" }, { "name": "PLSQL", "bytes": "31351" }, { "name": "TSQL", "bytes": "372284" } ], "symlink_target": "" }
@interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
{ "content_hash": "d5e0efb5403a920dce3f689844fbe485", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 60, "avg_line_length": 16.857142857142858, "alnum_prop": 0.7796610169491526, "repo_name": "iversonwool/GItStudy", "id": "0dd0494576ba7ec6a5265a97ae1c3e964ee7a8b8", "size": "271", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GitStudy/GitStudy/AppDelegate.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1497" }, { "name": "Objective-C", "bytes": "93120" } ], "symlink_target": "" }
Two kind of nodes, manager node and compute node. Manager node is both the job manager, database server and web server. Compute node is the job worker (We can actually scale to many compute nodes). ## Web * Back-end: PHP? ## Job management and security * Use ubuntu as system * Use slurm as job management system * Use cgroup as time, memory control * Use apparmor as fs access control ## Key processes ### Problem submission * Web back-end on manager node save description, standard input, standard output and register the submission in database ### Solution submission * Web back-end on manager node save the source code and register the submission in database * Web back-end calls a module to test the source code via `slurm` - The module is actually located on compute nodes - The module check if the standard input/output can be found locally, and `GET` them from manager node if necessary - The module `GET` source code from the manager node via web service on the manager node - The module test the source code - The module `POST` test result back to manager node * Web back-end receive the `POST` and register test result in the database * User front-end constantly ask if the job is finished (like every 3 seconds), and get the result once back-end on manager node receives result from compute node ### Solution testing * Apparmor + cgroups
{ "content_hash": "e206870629ed5a4fd033a4ff0de6d514", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 161, "avg_line_length": 38.361111111111114, "alnum_prop": 0.7574221578566256, "repo_name": "Jeff1995/oj", "id": "9600d7f5b857849b31a9c852f717090f57924090", "size": "1396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "man/design.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "8996" }, { "name": "Python", "bytes": "13521" }, { "name": "Shell", "bytes": "632" } ], "symlink_target": "" }
<h1><%= title %></h1> <form id="js-form"> <input type="text" placeholder="<%= username_placeholder %>" name="username"> <input type="password" placeholder="<%= password_placeholder %>" name="password"> <button type="submit"><%= button %></button> </form>
{ "content_hash": "9bebfd379a531a40239151acc90dca8e", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 82, "avg_line_length": 42.833333333333336, "alnum_prop": 0.6498054474708171, "repo_name": "baguetteapps/gitchat_web", "id": "02f38c6dc989da4570b4a722f2600b2ffac353ec", "size": "257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/templates/login.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "248778" }, { "name": "Python", "bytes": "1549" } ], "symlink_target": "" }
@interface APProgressViewExampleTests : XCTestCase @end @implementation APProgressViewExampleTests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } - (void)testPerformanceExample { // This is an example of a performance test case. [self measureBlock:^{ // Put the code you want to measure the time of here. }]; } @end
{ "content_hash": "0fcabb71db4ecfa07ab95901f0b4faca", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 107, "avg_line_length": 26.20689655172414, "alnum_prop": 0.7052631578947368, "repo_name": "ton252/APProgressView", "id": "fd70b82b234544409c7a848709455d84ed3b66b5", "size": "947", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "APProgressViewExample/APProgressViewExampleTests/APProgressViewExampleTests.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "28495" } ], "symlink_target": "" }
EDN::Type::Symbol.new('hello/world')
{ "content_hash": "a096b58753a7d331670baecc9edc3eda", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 37, "avg_line_length": 38, "alnum_prop": 0.6842105263157895, "repo_name": "gusai-francelabs/datafari", "id": "d6531f531b0f822c6d2d8b7c789af829371918f9", "size": "38", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "debian7/elk/logstash/vendor/bundle/jruby/1.9/gems/edn-1.1.0/spec/exemplars/symbol_with_namespace.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "291" }, { "name": "Batchfile", "bytes": "166948" }, { "name": "C", "bytes": "3555735" }, { "name": "C#", "bytes": "8440" }, { "name": "C++", "bytes": "1659325" }, { "name": "CSS", "bytes": "986977" }, { "name": "F#", "bytes": "2310" }, { "name": "Forth", "bytes": "506" }, { "name": "GLSL", "bytes": "1040" }, { "name": "Groff", "bytes": "4051512" }, { "name": "HTML", "bytes": "3892242" }, { "name": "Inno Setup", "bytes": "15300" }, { "name": "Java", "bytes": "4076115" }, { "name": "JavaScript", "bytes": "11510499" }, { "name": "Makefile", "bytes": "38845" }, { "name": "Mako", "bytes": "13678" }, { "name": "Mask", "bytes": "969" }, { "name": "Objective-C", "bytes": "27837" }, { "name": "PLSQL", "bytes": "115000" }, { "name": "PLpgSQL", "bytes": "343922" }, { "name": "Perl", "bytes": "226860" }, { "name": "Perl6", "bytes": "72008" }, { "name": "PowerShell", "bytes": "38303" }, { "name": "Python", "bytes": "19597957" }, { "name": "R", "bytes": "2528" }, { "name": "Ruby", "bytes": "40275" }, { "name": "SQLPL", "bytes": "81817" }, { "name": "Shell", "bytes": "764791" }, { "name": "Tcl", "bytes": "2150885" }, { "name": "Thrift", "bytes": "40240" }, { "name": "Visual Basic", "bytes": "481" }, { "name": "XS", "bytes": "132994" }, { "name": "XSLT", "bytes": "13301" } ], "symlink_target": "" }
<?php namespace Wlm\Bundle\ScannerBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DefaultControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/hello/Fabien'); $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0); } }
{ "content_hash": "14f520c64ed06def9810b8795f72b1dc", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 90, "avg_line_length": 23.941176470588236, "alnum_prop": 0.6781326781326781, "repo_name": "deuxnids/Wiloma", "id": "9350271f071d6314a23346019a00b7eb9632aea6", "size": "407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Wlm/ScannerBundle/Tests/Controller/DefaultControllerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "15982" }, { "name": "C", "bytes": "1" }, { "name": "C++", "bytes": "1" }, { "name": "CSS", "bytes": "466003" }, { "name": "JavaScript", "bytes": "2582477" }, { "name": "Logos", "bytes": "708305" }, { "name": "PHP", "bytes": "4938168" }, { "name": "Perl", "bytes": "2403" }, { "name": "Shell", "bytes": "7411" } ], "symlink_target": "" }
void progress_layer_init(Layer* layer, GRect frame); // Sets the number of steps that can be displayed by this progress layer. void progress_layer_set_num_steps(Layer* layer, unsigned int steps); // Sets the number of steps completed to be displayed by this progress layer. // If this number is larger than the maximum number of steps, it will be // clipped. void progress_layer_set_num_steps_completed(Layer* layer, unsigned int steps);
{ "content_hash": "7c38cc31d77bc332c423b1ce9956d2af", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 78, "avg_line_length": 40.18181818181818, "alnum_prop": 0.7647058823529411, "repo_name": "jonspeicher/Pomade", "id": "cf1f71cfe973d9daa52a4def4f02cd1f4d9589a1", "size": "869", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/progress_layer.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "29797" }, { "name": "C++", "bytes": "2271" }, { "name": "Objective-C", "bytes": "6820" } ], "symlink_target": "" }
package com.emitrom.touch4j.client.core.handlers.nestedlist; import com.emitrom.touch4j.client.core.EventObject; import com.emitrom.touch4j.client.core.handlers.AbstractHandler; import com.emitrom.touch4j.client.ui.ListDataView; import com.emitrom.touch4j.client.ui.NestedListDataView; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.GWT.UncaughtExceptionHandler; import com.google.gwt.core.client.JavaScriptObject; public abstract class NestedListItemDoubleTapHandler extends AbstractHandler { final JavaScriptObject jsoPeer = createPeer(this); private static native JavaScriptObject createPeer(NestedListItemDoubleTapHandler listener) /*-{ return function(source, listView, index, item, event, eOpts) { var nestedList = @com.emitrom.touch4j.client.ui.NestedListDataView::new(Lcom/google/gwt/core/client/JavaScriptObject;)(source); var listViewObject = @com.emitrom.touch4j.client.ui.ListDataView::new(Lcom/google/gwt/core/client/JavaScriptObject;)(listView); var e = @com.emitrom.touch4j.client.core.EventObject::new(Lcom/google/gwt/core/client/JavaScriptObject;)(event); listener.@com.emitrom.touch4j.client.core.handlers.nestedlist.NestedListItemDoubleTapHandler::fireOnEvent(Lcom/emitrom/touch4j/client/ui/NestedListDataView;Lcom/emitrom/touch4j/client/ui/ListDataView;ILjava/lang/Object;Lcom/emitrom/touch4j/client/core/EventObject;Ljava/lang/Object;)(nestedList, listViewObject, index, item, e, eOpts); }; }-*/; // Called from JSNI private final void fireOnEvent(NestedListDataView nestedListView, ListDataView listView, int index, Object item, EventObject event, Object eOpts) { UncaughtExceptionHandler handler = GWT.getUncaughtExceptionHandler(); if (handler != null) { fireOnEventAndCatch(nestedListView, listView, index, item, event, eOpts, handler); } else { onItemDoubleTap(nestedListView, listView, index, item, event, eOpts); } } private void fireOnEventAndCatch(NestedListDataView nestedListView, ListDataView listView, int index, Object item, EventObject event, Object eOpts, UncaughtExceptionHandler handler) { try { onItemDoubleTap(nestedListView, listView, index, item, event, eOpts); } catch (Throwable e) { handler.onUncaughtException(e); } } @Override public JavaScriptObject getJsoPeer() { return jsoPeer; } public abstract void onItemDoubleTap(NestedListDataView nestedListView, ListDataView listView, int index, Object item, EventObject event, Object eOpts); }
{ "content_hash": "f029cd2afdf9df9fe044e55b76434192", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 338, "avg_line_length": 51.16981132075472, "alnum_prop": 0.7300884955752213, "repo_name": "paulvi/touch4j", "id": "70bd62ead64dd17bd0690822632e4b967f9b15ca", "size": "3525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/emitrom/touch4j/client/core/handlers/nestedlist/NestedListItemDoubleTapHandler.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
$: << File.expand_path('../lib', File.dirname(__FILE__)) require 'rr' require 'roundtrip' require 'minitest/autorun' require 'timecop' class MiniTest::Unit::TestCase include RR::Adapters::MiniTest end
{ "content_hash": "6513b89f5f3536fedb12ad5c95e8ea20", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 56, "avg_line_length": 18.727272727272727, "alnum_prop": 0.7087378640776699, "repo_name": "jondot/roundtrip", "id": "b9eaaf0d79f6810be49bb5686f6ed7576cee5821", "size": "206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "18227" } ], "symlink_target": "" }
<!doctype html> <title>invoking resource selection by inserting &lt;source></title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <div id=log></div> <video></video> <script> async_test(function(t) { var v = document.querySelector('video'); v.onloadstart = t.step_func(function() { t.done(); }); v.appendChild(document.createElement('source')); window.onload = t.step_func(function() { assert_unreached(); }); }); </script>
{ "content_hash": "ba47de3ec11cb72b1f388b1fb4e832a9", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 67, "avg_line_length": 35.07142857142857, "alnum_prop": 0.6985743380855397, "repo_name": "Samsung/ChromiumGStreamerBackend", "id": "969daad6231d08bf77855f0f992c56935f4dd347", "size": "491", "binary": false, "copies": "279", "ref": "refs/heads/master", "path": "third_party/WebKit/LayoutTests/imported/wpt/html/semantics/embedded-content/media-elements/loading-the-media-resource/resource-selection-invoke-insert-source.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <!-- saved from url=(0014)about:internet --> <title>Selecting and Saving Sample Results (Select Samples Toolbar)</title> <link rel="StyleSheet" href="css/rembrandt1.5_View%20Results.css" type="text/css" media="all" /> <link rel="StyleSheet" href="css/webworks.css" type="text/css" media="all" /> <script type="text/javascript" language="JavaScript1.2" src="wwhdata/common/context.js"></script> <script type="text/javascript" language="JavaScript1.2" src="wwhdata/common/towwhdir.js"></script> <script type="text/javascript" language="JavaScript1.2" src="wwhdata/common/wwhpagef.js"></script> <script type="text/javascript" language="JavaScript1.2"> <!-- var WebWorksRootPath = ""; // --> </script> <script type="text/javascript" language="JavaScript1.2"> <!-- // Set reference to top level help frame // var WWHFrame = WWHGetWWHFrame("", true); // --> </script> <script type="text/javascript" language="JavaScript1.2" src="scripts/expand.js"></script> </head> <body style="" onLoad="WWHUpdate();" onUnload="WWHUnload();" onKeyDown="WWHHandleKeyDown((document.all||document.getElementById||document.layers)?event:null);" onKeyPress="WWHHandleKeyPress((document.all||document.getElementById||document.layers)?event:null);" onKeyUp="WWHHandleKeyUp((document.all||document.getElementById||document.layers)?event:null);"> <br /> <div class="WebWorks_Breadcrumbs" style="text-align: left;"> <a class="WebWorks_Breadcrumb_Link" href="rembrandt1.5_View%20Results.8.1.html#1083438">Viewing Results</a> &gt; <a class="WebWorks_Breadcrumb_Link" href="rembrandt1.5_View%20Results.8.3.html#1083438">Advanced Search or Query Results</a> &gt; <a class="WebWorks_Breadcrumb_Link" href="rembrandt1.5_View%20Results.8.4.html#1083438">Gene Expression Sample Report</a> &gt; Selecting and Saving Sample Results (Select Samples Toolbar)</div> <hr align="left" /> <div class="WebWorks_Breadcrumbs"> <a href="JavaScript:history.back(1)">Back</a> <a href="JavaScript:history.forward(1)">Forward</a> </div> <blockquote> <div class="Heading3"><a name="1083438">Selecting and Saving Sample Results (Select Samples Toolbar)</a></div> <div class="Body_Text"><a name="1083440">You can save samples to a PatientDID list stored in the Manage Lists function. </a>PatientDID lists enable you to further filter advanced queries. To save samples, follow these steps: </div> <div class="Numbered_List_1_outer" style="margin-left: 18pt;"> <table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1083441"> <tr style="vertical-align: baseline;"> <td> <div class="Numbered_List_1_inner" style="width: 18pt; white-space: nowrap;"> <span class="Bold">1. </span> </div> </td> <td width="100%"> <div class="Numbered_List_1_inner"><a name="1083441">On the sample report, there are several ways to select samples.</a></div> </td> </tr> </table> </div> <div class="Bullet_Indent_outer" style="margin-left: 36pt;"> <table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1096871"> <tr style="vertical-align: baseline;"> <td> <div class="Bullet_Indent_inner" style="width: 18pt; white-space: nowrap;"> <span style="color: Black; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: normal;">–</span> </div> </td> <td width="100%"> <div class="Bullet_Indent_inner"><a name="1096871">To select all the listed samples on the </a><span class="Bold">Select Samples</span> toolbar, click the <span class="Bold">Check All</span> link. To deselect all the listed samples, click the <span class="Bold">Uncheck All </span>link.</div> </td> </tr> </table> </div> <div class="Bullet_Indent_outer" style="margin-left: 36pt;"> <table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1083457"> <tr style="vertical-align: baseline;"> <td> <div class="Bullet_Indent_inner" style="width: 18pt; white-space: nowrap;"> <span style="color: Black; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: normal;">–</span> </div> </td> <td width="100%"> <div class="Bullet_Indent_inner"><a name="1083457">To select (or deselect) all the samples in a sample group, click the box next </a>to the sample group name, for example the box next to <span class="Bold">ASTROCYTOMA </span><span class="Bold">Samples</span>. All the samples in the group are selected</div> </td> </tr> </table> </div> <div class="Bullet_Indent_outer" style="margin-left: 36pt;"> <table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1083461"> <tr style="vertical-align: baseline;"> <td> <div class="Bullet_Indent_inner" style="width: 18pt; white-space: nowrap;"> <span style="color: Black; font-size: 12pt; font-style: normal; font-variant: normal; font-weight: normal;">–</span> </div> </td> <td width="100%"> <div class="Bullet_Indent_inner"><a name="1083461">To select (or deselect) an individual sample within a group, click the box in </a>the column next to the sample name.</div> </td> </tr> </table> </div> <div class="Numbered_List_outer" style="margin-left: 18pt;"> <table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1115206"> <tr style="vertical-align: baseline;"> <td> <div class="Numbered_List_inner" style="width: 18pt; white-space: nowrap;"> <span class="Bold">2. </span> </div> </td> <td width="100%"> <div class="Numbered_List_inner"><a name="1115206">To save the selected samples, enter a unique name for the PatientDID list next </a>to <span class="Bold">Select Samples</span>, or maintain the current name.</div> </td> </tr> </table> </div> <div class="Numbered_List_outer" style="margin-left: 18pt;"> <table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1114971"> <tr style="vertical-align: baseline;"> <td> <div class="Numbered_List_inner" style="width: 18pt; white-space: nowrap;"> <span class="Bold">3. </span> </div> </td> <td width="100%"> <div class="Numbered_List_inner"><a name="1114971">Click the </a><span class="Bold">Save Samples </span>button. </div> </td> </tr> </table> </div> <div class="Body_Text_Indent_2"><a name="1114975">Once saved, the sample set is listed in red type under PatientDID List in the </a>blue panel. </div> <div class="Note_outer" style="margin-left: 50.25pt;"> <table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1083492"> <tr style="vertical-align: baseline;"> <td> <div class="Note_inner" style="width: 25px; white-space: nowrap;"> <img src="Lightbulb.gif" alt="*" id="bullet1083492" border="0" width="36" height="36" /> </div> </td> <td width="100%"> <div class="Note_inner"><a name="1083492">The sample set name will also appear on the Refine Query page, in the </a><span class="Bold">Select the Result set to apply the above query</span> drop-down list. This enables you to add the saved sample set to another query.</div> </td> </tr> </table> </div> <script type="text/javascript" language="JavaScript1.2"> <!-- // Clear related topics // WWHClearRelatedTopics(); // Add related topics // WWHAddRelatedTopic("Gene Expression Sample Report", "REMBRANDT_Online_Help", "rembrandt1.5_View%20Results.8.4.html#1101944"); WWHAddRelatedTopic("Copy Number Sample Report", "REMBRANDT_Online_Help", "rembrandt1.5_View%20Results.8.11.html#1114118"); WWHAddRelatedTopic("Gene Expression Sample Report", "REMBRANDT_Online_Help", "rembrandt1.5_View%20Results.8.4.html#1101944"); WWHAddRelatedTopic("Copy Number Sample Report", "REMBRANDT_Online_Help", "rembrandt1.5_View%20Results.8.11.html#1114118"); document.writeln(WWHRelatedTopicsInlineHTML()); // --> </script> </blockquote> <script type="text/javascript" language="JavaScript1.2"> <!-- document.write(WWHRelatedTopicsDivTag() + WWHPopupDivTag() + WWHALinksDivTag()); // --> </script> </body> </html>
{ "content_hash": "d91026a1b00df7f78ac177a89889fa43", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 442, "avg_line_length": 58.46913580246913, "alnum_prop": 0.6112753378378378, "repo_name": "NCIP/rembrandt", "id": "b15ec49347d539482359a0ad06d0a74d3481523e", "size": "9478", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebRoot/helpDocs/REMBRANDT_Online_Help/rembrandt1.5_View Results.8.7.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1261358" }, { "name": "Java", "bytes": "5096659" }, { "name": "JavaScript", "bytes": "1404934" }, { "name": "PHP", "bytes": "370" }, { "name": "Perl", "bytes": "77" }, { "name": "R", "bytes": "1977" }, { "name": "Shell", "bytes": "119" }, { "name": "XSLT", "bytes": "80724" } ], "symlink_target": "" }
<html> <head> <title>User agent detail - Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; Full AOSP on Rk29sdk Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; Full AOSP on Rk29sdk Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>piwik/device-detector<br /><small>/Tests/fixtures/unknown.yml</small></td><td>Android Browser </td><td>Android 4.0.3</td><td>WebKit </td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a> <!-- Modal Structure --> <div id="modal-test" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Testsuite result detail</h4> <p><pre><code class="php">Array ( [user_agent] => Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; Full AOSP on Rk29sdk Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 [os] => Array ( [name] => Android [short_name] => AND [version] => 4.0.3 [platform] => ) [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [device] => Array ( [type] => [brand] => [model] => ) [os_family] => Android [browser_family] => Android Browser ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Android 4.0</td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.023</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-215ac98d-ccf8-4615-916e-5a819d6a59c9">Detail</a> <!-- Modal Structure --> <div id="modal-215ac98d-ccf8-4615-916e-5a819d6a59c9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.0.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android?4.0* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => 4.0 [platform_description] => Android OS [platform_bits] => 32 [platform_maker] => Google Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => 1 [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [cssversion] => 3 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>Android Browser 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661">Detail</a> <!-- Modal Structure --> <div id="modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Android [browser] => Android Browser [version] => 4.0 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">Proscan</td><td>Full AOSP on Rk29sdk</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.258</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc">Detail</a> <!-- Modal Structure --> <div id="modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 600 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => Proscan [mobile_model] => Full AOSP on Rk29sdk [version] => 4.0 [is_android] => 1 [browser_name] => Android Webkit [operating_system_family] => Android [operating_system_version] => 4.0.3 [is_ios] => [producer] => Google Inc. [operating_system] => Android 4.0.x Ice Cream Sandwich [mobile_screen_width] => 1024 [mobile_browser] => Android Webkit ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.2</small></td><td>Android Browser </td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.006</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-21638055-738d-46ba-a1b1-f5114bc26475">Detail</a> <!-- Modal Structure --> <div id="modal-21638055-738d-46ba-a1b1-f5114bc26475" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [operatingSystem] => Array ( [name] => Android [short_name] => AND [version] => 4.0 [platform] => ) [device] => Array ( [brand] => [brandName] => [model] => [device] => [deviceName] => ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => [isTablet] => [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td><td>Navigator 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c">Detail</a> <!-- Modal Structure --> <div id="modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; Full AOSP on Rk29sdk Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) [name:Sinergi\BrowserDetector\Browser:private] => Navigator [version:Sinergi\BrowserDetector\Browser:private] => 4.0 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Android [version:Sinergi\BrowserDetector\Os:private] => 4.0.3 [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; Full AOSP on Rk29sdk Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; Full AOSP on Rk29sdk Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>Android 4.0.3</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"></td><td>Full AOSP on Rk29sdk</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.004</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b">Detail</a> <!-- Modal Structure --> <div id="modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 4 [minor] => 0 [patch] => 3 [family] => Android ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 4 [minor] => 0 [patch] => 3 [patchMinor] => [family] => Android ) [device] => UAParser\Result\Device Object ( [brand] => Generic_Android [model] => Full AOSP on Rk29sdk [family] => Full AOSP on Rk29sdk ) [originalUserAgent] => Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; Full AOSP on Rk29sdk Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.122</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4">Detail</a> <!-- Modal Structure --> <div id="modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Android Webkit Browser [agent_version] => -- [os_type] => Android [os_name] => Android [os_versionName] => [os_versionNumber] => 4.0.3 [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => English - United States [agent_languageTag] => en-us ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small></td><td>Android Browser 4.0</td><td>WebKit 534.30</td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.419</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9795f66f-7271-430e-973a-a5c0e14dc35a">Detail</a> <!-- Modal Structure --> <div id="modal-9795f66f-7271-430e-973a-a5c0e14dc35a" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Android [simple_sub_description_string] => [simple_browser_string] => Android Browser 4 on Android (Ice Cream Sandwich) [browser_version] => 4 [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => stdClass Object ( [System Build] => IML74K ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => android-browser [operating_system_version] => Ice Cream Sandwich [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 534.30 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Android (Ice Cream Sandwich) [operating_system_version_full] => 4.0.3 [operating_platform_code] => [browser_name] => Android Browser [operating_system_name_code] => android [user_agent] => Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; Full AOSP on Rk29sdk Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 [browser_version_full] => 4.0 [browser] => Android Browser 4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>2.0.10</small></td><td>Android Browser </td><td>Webkit 534.30</td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">Rockchip</td><td>RK29 based device</td><td>devboard</td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.004</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4">Detail</a> <!-- Modal Structure --> <div id="modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Android Browser ) [engine] => Array ( [name] => Webkit [version] => 534.30 ) [os] => Array ( [name] => Android [version] => 4.0.3 ) [device] => Array ( [type] => devboard [manufacturer] => Rockchip [model] => RK29 based device ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3f285ff5-314b-4db4-9948-54572e92e7b6">Detail</a> <!-- Modal Structure --> <div id="modal-3f285ff5-314b-4db4-9948-54572e92e7b6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [name] => Safari [vendor] => Apple [version] => 4.0 [category] => smartphone [os] => Android [os_version] => 4.0.3 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0</td><td style="border-left: 1px solid #555">Proscan</td><td>Full AOSP on Rk29sdk</td><td>Tablet</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.045</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-1a1aee36-7ce7-4111-a391-8e2c501f1532">Detail</a> <!-- Modal Structure --> <div id="modal-1a1aee36-7ce7-4111-a391-8e2c501f1532" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => true [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => true [is_mobile] => true [is_robot] => false [is_smartphone] => false [is_touchscreen] => true [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Android [advertised_device_os_version] => 4.0 [advertised_browser] => Android Webkit [advertised_browser_version] => 4.0 [complete_device_name] => Proscan Full AOSP on Rk29sdk [form_factor] => Tablet [is_phone] => false [is_app_webview] => false ) [all] => Array ( [brand_name] => Proscan [model_name] => Full AOSP on Rk29sdk [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => Android [mobile_browser] => Android Webkit [mobile_browser_version] => [device_os_version] => 4.0 [pointing_method] => touchscreen [release_date] => 2012_november [marketing_name] => [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => false [is_tablet] => true [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => true [xhtml_supports_css_cell_table_coloring] => true [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => true [xhtml_document_title_support] => true [xhtml_preferred_charset] => iso-8859-1 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => true [xhtml_send_sms_string] => sms: [xhtml_send_mms_string] => mms: [xhtml_file_upload] => supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => none [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => w3c_api [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 1024 [resolution_height] => 600 [columns] => 60 [max_image_width] => 320 [max_image_height] => 480 [rows] => 40 [physical_screen_width] => 154 [physical_screen_height] => 90 [dual_orientation] => true [density_class] => 1.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => false [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => true [transparent_png_index] => true [svgt_1_1] => true [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => true [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 3600 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 2000000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => true [inline_support] => false [oma_support] => true [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => true [streaming_3gpp] => true [streaming_mp4] => true [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => 10 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => 2 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => 3.0 [streaming_acodec_amr] => nb [streaming_acodec_aac] => lc [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => apple_live_streaming [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => true [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => true [mp3] => true [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => true [css_supports_width_as_percentage] => true [css_border_image] => webkit [css_rounded_corners] => webkit [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => 10 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => 0 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => 3.0 [playback_real_media] => none [playback_3gpp] => true [playback_3g2] => false [playback_mp4] => true [playback_mov] => false [playback_acodec_amr] => nb [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => true [html_preferred_dtd] => html4 [viewport_supported] => true [viewport_width] => device_width_token [viewport_userscalable] => no [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => full [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => A [is_sencha_touch_ok] => false [controlcap_is_smartphone] => default [controlcap_is_ios] => default [controlcap_is_android] => default [controlcap_is_robot] => default [controlcap_is_app] => default [controlcap_advertised_device_os] => default [controlcap_advertised_device_os_version] => default [controlcap_advertised_browser] => default [controlcap_advertised_browser_version] => default [controlcap_is_windows_phone] => default [controlcap_is_full_desktop] => default [controlcap_is_largescreen] => default [controlcap_is_mobile] => default [controlcap_is_touchscreen] => default [controlcap_is_wml_preferred] => default [controlcap_is_xhtmlmp_preferred] => default [controlcap_is_html_preferred] => default [controlcap_form_factor] => default [controlcap_complete_device_name] => default ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-02-13 13:39:10</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
{ "content_hash": "1d13fdc212a01244f58d5a5ff83a9af2", "timestamp": "", "source": "github", "line_count": 1144, "max_line_length": 748, "avg_line_length": 41.11276223776224, "alnum_prop": 0.5368783620011481, "repo_name": "ThaDafinser/UserAgentParserComparison", "id": "ae30ba6a5a575dcb58124761ef90c4019a80490d", "size": "47034", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "v4/user-agent-detail/c3/cb/c3cbd5e8-0b3d-4d55-8090-4571fe04ec8d.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2060859160" } ], "symlink_target": "" }
namespace ui { namespace { // To test the handling of |EventRewriter|s through |EventSource|, // we rewrite and test event types. class TestEvent : public Event { public: explicit TestEvent(EventType type) : Event(type, base::TimeTicks(), 0), unique_id_(next_unique_id_++) {} ~TestEvent() override {} int unique_id() const { return unique_id_; } private: static int next_unique_id_; int unique_id_; }; int TestEvent::next_unique_id_ = 0; // TestEventRewriteProcessor is set up with a sequence of event types, // and fails if the events received via OnEventFromSource() do not match // this sequence. These expected event types are consumed on receipt. class TestEventRewriteProcessor : public test::TestEventProcessor { public: TestEventRewriteProcessor() {} ~TestEventRewriteProcessor() override { CheckAllReceived(); } void AddExpectedEvent(EventType type) { expected_events_.push_back(type); } // Test that all expected events have been received. void CheckAllReceived() { EXPECT_TRUE(expected_events_.empty()); } // EventProcessor: EventDispatchDetails OnEventFromSource(Event* event) override { EXPECT_FALSE(expected_events_.empty()); EXPECT_EQ(expected_events_.front(), event->type()); expected_events_.pop_front(); return EventDispatchDetails(); } private: std::list<EventType> expected_events_; DISALLOW_COPY_AND_ASSIGN(TestEventRewriteProcessor); }; // Trivial EventSource that does nothing but send events. class TestEventRewriteSource : public EventSource { public: explicit TestEventRewriteSource(EventProcessor* processor) : processor_(processor) {} EventProcessor* GetEventProcessor() override { return processor_; } void Send(EventType type) { std::unique_ptr<Event> event(new TestEvent(type)); (void)SendEventToProcessor(event.get()); } private: EventProcessor* processor_; }; // This EventRewriter always returns the same status, and if rewriting, the // same event type; it is used to test simple rewriting, and rewriter addition, // removal, and sequencing. Consequently EVENT_REWRITE_DISPATCH_ANOTHER is not // supported here (calls to NextDispatchEvent() would continue indefinitely). class TestConstantEventRewriter : public EventRewriter { public: TestConstantEventRewriter(EventRewriteStatus status, EventType type) : status_(status), type_(type) { CHECK_NE(EVENT_REWRITE_DISPATCH_ANOTHER, status); } EventRewriteStatus RewriteEvent( const Event& event, std::unique_ptr<Event>* rewritten_event) override { if (status_ == EVENT_REWRITE_REWRITTEN) rewritten_event->reset(new TestEvent(type_)); return status_; } EventRewriteStatus NextDispatchEvent( const Event& last_event, std::unique_ptr<Event>* new_event) override { NOTREACHED(); return status_; } private: EventRewriteStatus status_; EventType type_; }; // This EventRewriter runs a simple state machine; it is used to test // EVENT_REWRITE_DISPATCH_ANOTHER. class TestStateMachineEventRewriter : public EventRewriter { public: TestStateMachineEventRewriter() : last_rewritten_event_(0), state_(0) {} void AddRule(int from_state, EventType from_type, int to_state, EventType to_type, EventRewriteStatus to_status) { RewriteResult r = {to_state, to_type, to_status}; rules_.insert(std::pair<RewriteCase, RewriteResult>( RewriteCase(from_state, from_type), r)); } EventRewriteStatus RewriteEvent( const Event& event, std::unique_ptr<Event>* rewritten_event) override { RewriteRules::iterator find = rules_.find(RewriteCase(state_, event.type())); if (find == rules_.end()) return EVENT_REWRITE_CONTINUE; if ((find->second.status == EVENT_REWRITE_REWRITTEN) || (find->second.status == EVENT_REWRITE_DISPATCH_ANOTHER)) { last_rewritten_event_ = new TestEvent(find->second.type); rewritten_event->reset(last_rewritten_event_); } else { last_rewritten_event_ = 0; } state_ = find->second.state; return find->second.status; } EventRewriteStatus NextDispatchEvent( const Event& last_event, std::unique_ptr<Event>* new_event) override { EXPECT_TRUE(last_rewritten_event_); const TestEvent* arg_last = static_cast<const TestEvent*>(&last_event); EXPECT_EQ(last_rewritten_event_->unique_id(), arg_last->unique_id()); const TestEvent* arg_new = static_cast<const TestEvent*>(new_event->get()); EXPECT_FALSE(arg_new && arg_last->unique_id() == arg_new->unique_id()); return RewriteEvent(last_event, new_event); } private: typedef std::pair<int, EventType> RewriteCase; struct RewriteResult { int state; EventType type; EventRewriteStatus status; }; typedef std::map<RewriteCase, RewriteResult> RewriteRules; RewriteRules rules_; TestEvent* last_rewritten_event_; int state_; }; } // namespace TEST(EventRewriterTest, EventRewriting) { // TestEventRewriter r0 always rewrites events to ET_CANCEL_MODE; // it is placed at the beginning of the chain and later removed, // to verify that rewriter removal works. TestConstantEventRewriter r0(EVENT_REWRITE_REWRITTEN, ET_CANCEL_MODE); // TestEventRewriter r1 always returns EVENT_REWRITE_CONTINUE; // it is placed at the beginning of the chain to verify that a // later rewriter sees the events. TestConstantEventRewriter r1(EVENT_REWRITE_CONTINUE, ET_UNKNOWN); // TestEventRewriter r2 has a state machine, primarily to test // |EVENT_REWRITE_DISPATCH_ANOTHER|. TestStateMachineEventRewriter r2; // TestEventRewriter r3 always rewrites events to ET_CANCEL_MODE; // it is placed at the end of the chain to verify that previously // rewritten events are not passed further down the chain. TestConstantEventRewriter r3(EVENT_REWRITE_REWRITTEN, ET_CANCEL_MODE); TestEventRewriteProcessor p; TestEventRewriteSource s(&p); s.AddEventRewriter(&r0); s.AddEventRewriter(&r1); s.AddEventRewriter(&r2); // These events should be rewritten by r0 to ET_CANCEL_MODE. p.AddExpectedEvent(ET_CANCEL_MODE); s.Send(ET_MOUSE_DRAGGED); p.AddExpectedEvent(ET_CANCEL_MODE); s.Send(ET_MOUSE_PRESSED); p.CheckAllReceived(); // Remove r0, and verify that it's gone and that events make it through. s.AddEventRewriter(&r3); s.RemoveEventRewriter(&r0); r2.AddRule(0, ET_SCROLL_FLING_START, 0, ET_SCROLL_FLING_CANCEL, EVENT_REWRITE_REWRITTEN); p.AddExpectedEvent(ET_SCROLL_FLING_CANCEL); s.Send(ET_SCROLL_FLING_START); p.CheckAllReceived(); s.RemoveEventRewriter(&r3); // Verify EVENT_REWRITE_DISPATCH_ANOTHER using a state machine // (that happens to be analogous to sticky keys). r2.AddRule(0, ET_KEY_PRESSED, 1, ET_KEY_PRESSED, EVENT_REWRITE_CONTINUE); r2.AddRule(1, ET_MOUSE_PRESSED, 0, ET_MOUSE_PRESSED, EVENT_REWRITE_CONTINUE); r2.AddRule(1, ET_KEY_RELEASED, 2, ET_KEY_RELEASED, EVENT_REWRITE_DISCARD); r2.AddRule(2, ET_MOUSE_RELEASED, 3, ET_MOUSE_RELEASED, EVENT_REWRITE_DISPATCH_ANOTHER); r2.AddRule(3, ET_MOUSE_RELEASED, 0, ET_KEY_RELEASED, EVENT_REWRITE_REWRITTEN); p.AddExpectedEvent(ET_KEY_PRESSED); s.Send(ET_KEY_PRESSED); s.Send(ET_KEY_RELEASED); p.AddExpectedEvent(ET_MOUSE_PRESSED); s.Send(ET_MOUSE_PRESSED); // Removing rewriters r1 and r3 shouldn't affect r2. s.RemoveEventRewriter(&r1); s.RemoveEventRewriter(&r3); // Continue with the state-based rewriting. p.AddExpectedEvent(ET_MOUSE_RELEASED); p.AddExpectedEvent(ET_KEY_RELEASED); s.Send(ET_MOUSE_RELEASED); p.CheckAllReceived(); } } // namespace ui
{ "content_hash": "b10edad25038b9ec30e938afb90940a6", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 79, "avg_line_length": 35.31336405529954, "alnum_prop": 0.7135586584888425, "repo_name": "danakj/chromium", "id": "73cad4406f436de9e9049739e675f8a08dd1a911", "size": "8056", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "ui/events/event_rewriter_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
using System.Collections.Generic; using Microsoft.Extensions.FileProviders; using Nancy.ModelBinding; using Nancy.Responses.Negotiation; using Nancy.Swagger.Demo.Models; using Nancy.Swagger.Annotations.Attributes; using Swagger.ObjectModel; namespace Nancy.Swagger.Demo.Modules { public class HomeModule : NancyModule { public HomeModule() { Head("/", _ => HttpStatusCode.OK, null, "Head"); Get("/", _ => GetPetStoreUrl(), null, "Home"); Get("/users", _ => GetUsers(), null, "GetUsers"); Post("/users", _ => { var user = this.Bind<User>(); return PostUser(user); }); } private Response GetPetStoreUrl() { var port = Request.Url.Port ?? 80; return Response.AsRedirect($"http://petstore.swagger.io/?url=http://localhost:{port}/api-docs"); } [Route("Head")] [Route(HttpMethod.Head, "/")] [Route(Summary = "Example head method")] [SwaggerResponse(HttpStatusCode.OK)] private Response Head() { return HttpStatusCode.OK; } [Route("GetUsers")] [Route(HttpMethod.Get, "/users")] [Route(Summary = "Get All Users")] [SwaggerResponse(HttpStatusCode.OK, Message = "OK", Model = typeof(IEnumerable<User>))] [Route(Tags = new[] { "Users" })] private IEnumerable<User> GetUsers() { return new[] {new User {Name = "Vincent Vega", Age = 45}}; } [Route(HttpMethod.Post, "/users")] [Route(Summary = "Post New User")] [SwaggerResponse(HttpStatusCode.OK, Message = "OK", Model = typeof(User))] [SwaggerResponse(HttpStatusCode.InternalServerError, Message = "Internal Server Error")] [Route(Produces = new[] { "application/json" })] [Route(Consumes = new[] { "application/json", "application/xml" })] [Route(Tags = new[] { "Users" })] [RouteSecurity(SecuritySchemes.Basic)] private User PostUser([RouteParam(ParameterIn.Body)] User user) { return user; } } }
{ "content_hash": "2aef10a9d4ad2c79f33a93bf0b7179a8", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 108, "avg_line_length": 33, "alnum_prop": 0.5684113865932048, "repo_name": "yahehe/Nancy.Swagger", "id": "31baca243e26fd8a1b48937f40e5b79d5fc756ed", "size": "2180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/Nancy.Swagger.Annotations.Demo/Modules/HomeModule.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "338" }, { "name": "C#", "bytes": "430715" } ], "symlink_target": "" }
namespace blink { struct IndexedDBDatabaseMetadata; struct IndexedDBIndexMetadata; struct IndexedDBObjectStoreMetadata; } // namespace blink namespace content { class TransactionalLevelDBDatabase; class TransactionalLevelDBTransaction; // A fake implementation of IndexedDBMetadataCoding, for testing. class FakeIndexedDBMetadataCoding : public IndexedDBMetadataCoding { public: FakeIndexedDBMetadataCoding(); FakeIndexedDBMetadataCoding(const FakeIndexedDBMetadataCoding&) = delete; FakeIndexedDBMetadataCoding& operator=(const FakeIndexedDBMetadataCoding&) = delete; ~FakeIndexedDBMetadataCoding() override; leveldb::Status ReadDatabaseNames( TransactionalLevelDBDatabase* db, const std::string& origin_identifier, std::vector<std::u16string>* names) override; leveldb::Status ReadMetadataForDatabaseName( TransactionalLevelDBDatabase* db, const std::string& origin_identifier, const std::u16string& name, blink::IndexedDBDatabaseMetadata* metadata, bool* found) override; leveldb::Status CreateDatabase( TransactionalLevelDBDatabase* database, const std::string& origin_identifier, const std::u16string& name, int64_t version, blink::IndexedDBDatabaseMetadata* metadata) override; leveldb::Status SetDatabaseVersion( TransactionalLevelDBTransaction* transaction, int64_t row_id, int64_t version, blink::IndexedDBDatabaseMetadata* metadata) override; leveldb::Status FindDatabaseId(TransactionalLevelDBDatabase* db, const std::string& origin_identifier, const std::u16string& name, int64_t* id, bool* found) override; leveldb::Status CreateObjectStore( TransactionalLevelDBTransaction* transaction, int64_t database_id, int64_t object_store_id, std::u16string name, blink::IndexedDBKeyPath key_path, bool auto_increment, blink::IndexedDBObjectStoreMetadata* metadata) override; leveldb::Status RenameObjectStore( TransactionalLevelDBTransaction* transaction, int64_t database_id, std::u16string new_name, std::u16string* old_name, blink::IndexedDBObjectStoreMetadata* metadata) override; leveldb::Status DeleteObjectStore( TransactionalLevelDBTransaction* transaction, int64_t database_id, const blink::IndexedDBObjectStoreMetadata& object_store) override; leveldb::Status CreateIndex(TransactionalLevelDBTransaction* transaction, int64_t database_id, int64_t object_store_id, int64_t index_id, std::u16string name, blink::IndexedDBKeyPath key_path, bool is_unique, bool is_multi_entry, blink::IndexedDBIndexMetadata* metadata) override; leveldb::Status RenameIndex(TransactionalLevelDBTransaction* transaction, int64_t database_id, int64_t object_store_id, std::u16string new_name, std::u16string* old_name, blink::IndexedDBIndexMetadata* metadata) override; leveldb::Status DeleteIndex( TransactionalLevelDBTransaction* transaction, int64_t database_id, int64_t object_store_id, const blink::IndexedDBIndexMetadata& metadata) override; }; } // namespace content #endif // CONTENT_BROWSER_INDEXED_DB_FAKE_INDEXED_DB_METADATA_CODING_H_
{ "content_hash": "fdb9ab8383384fec07d61c9b4de56c09", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 80, "avg_line_length": 38.07142857142857, "alnum_prop": 0.6553202894666309, "repo_name": "nwjs/chromium.src", "id": "6d61f9634b8ddacbfdec677767a9102b5b3f5a8a", "size": "4296", "binary": false, "copies": "6", "ref": "refs/heads/nw70", "path": "content/browser/indexed_db/fake_indexed_db_metadata_coding.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112-release) on Tue Nov 22 11:00:27 CET 2016 --> <title>NetworkModule (lib API)</title> <meta name="date" content="2016-11-22"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="NetworkModule (lib API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?io/door2door/analytics/network/dagger/NetworkModule.html" target="_top">Frames</a></li> <li><a href="NetworkModule.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods.inherited.from.class.java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">io.door2door.analytics.network.dagger</div> <h2 title="Class NetworkModule" class="title">Class NetworkModule</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>io.door2door.analytics.network.dagger.NetworkModule</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">NetworkModule</span> extends java.lang.Object</pre> <div class="block">Dagger module for providing the network dependencies.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../io/door2door/analytics/network/dagger/NetworkModule.html#NetworkModule--">NetworkModule</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="NetworkModule--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>NetworkModule</h4> <pre>public&nbsp;NetworkModule()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?io/door2door/analytics/network/dagger/NetworkModule.html" target="_top">Frames</a></li> <li><a href="NetworkModule.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods.inherited.from.class.java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "5dd001751e08b2af6e76fe6f95b3b9f6", "timestamp": "", "source": "github", "line_count": 236, "max_line_length": 196, "avg_line_length": 30.258474576271187, "alnum_prop": 0.6209214395742894, "repo_name": "door2door-io/door2door-sdk-android", "id": "a4fc4b1d2a8ff558772c68206a1669bc0664a211", "size": "7141", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "docs/javadoc/io/door2door/analytics/network/dagger/NetworkModule.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "113594" } ], "symlink_target": "" }
#ifndef cmSourceFileLocation_h #define cmSourceFileLocation_h #include "cmStandardIncludes.h" class cmMakefile; /** \class cmSourceFileLocation * \brief cmSourceFileLocation tracks knowledge about a source file location * * Source files can be referenced by a variety of names. The * directory and/or extension may be omitted leading to a certain * level of ambiguity about the source file location. This class is * used by cmSourceFile to keep track of what is known about the * source file location. Each reference may add some information * about the directory or extension of the file. */ class cmSourceFileLocation { public: /** * Construct for a source file created in a given cmMakefile * instance with an initial name. */ cmSourceFileLocation(cmMakefile* mf, const char* name); /** * Return whether the givne source file location could refers to the * same source file as this location given the level of ambiguity in * each location. */ bool Matches(cmSourceFileLocation const& loc); /** * Explicity state that the source file is located in the source tree. */ void DirectoryUseSource(); /** * Explicity state that the source file is located in the build tree. */ void DirectoryUseBinary(); /** * Return whether the directory containing the source is ambiguous. */ bool DirectoryIsAmbiguous() const { return this->AmbiguousDirectory; } /** * Return whether the extension of the source name is ambiguous. */ bool ExtensionIsAmbiguous() const { return this->AmbiguousExtension; } /** * Get the directory containing the file as best is currently known. * If DirectoryIsAmbiguous() returns false this will be a full path. * Otherwise it will be a relative path (possibly empty) that is * either with respect to the source or build tree. */ const char* GetDirectory() const { return this->Directory.c_str(); } /** * Get the file name as best is currently known. If * ExtensionIsAmbiguous() returns true this name may not be the * final name (but could be). Otherwise the returned name is the * final name. */ const char* GetName() const { return this->Name.c_str(); } /** * Get the cmMakefile instance for which the source file was created. */ cmMakefile* GetMakefile() const { return this->Makefile; } private: cmMakefile* Makefile; bool AmbiguousDirectory; bool AmbiguousExtension; std::string Directory; std::string Name; // Update the location with additional knowledge. void Update(cmSourceFileLocation const& loc); void Update(const char* name); void UpdateExtension(const char* name); void UpdateDirectory(const char* name); }; #endif
{ "content_hash": "d38cbecb350da68422e8816a4d770f27", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 76, "avg_line_length": 30.46067415730337, "alnum_prop": 0.7203983769826632, "repo_name": "Multi2Sim/m2s-bench-parsec-3.0-src", "id": "9d17e58f09cda8c97f72dfcc4fd4dc5193992085", "size": "3430", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tools/cmake/src/Source/cmSourceFileLocation.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ada", "bytes": "89144" }, { "name": "Assembly", "bytes": "1659124" }, { "name": "Awk", "bytes": "142" }, { "name": "Batchfile", "bytes": "87065" }, { "name": "C", "bytes": "68546505" }, { "name": "C#", "bytes": "55726" }, { "name": "C++", "bytes": "8136682" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CSS", "bytes": "25825" }, { "name": "Clean", "bytes": "6801" }, { "name": "DIGITAL Command Language", "bytes": "292209" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "Groff", "bytes": "1279566" }, { "name": "HTML", "bytes": "22851143" }, { "name": "JavaScript", "bytes": "38451" }, { "name": "Lex", "bytes": "5802" }, { "name": "Logos", "bytes": "108920" }, { "name": "Makefile", "bytes": "3250395" }, { "name": "Max", "bytes": "296" }, { "name": "Module Management System", "bytes": "63061" }, { "name": "Objective-C", "bytes": "25859" }, { "name": "PHP", "bytes": "20451" }, { "name": "Pascal", "bytes": "61164" }, { "name": "Perl", "bytes": "779784" }, { "name": "Perl6", "bytes": "27602" }, { "name": "PostScript", "bytes": "74572" }, { "name": "Prolog", "bytes": "121408" }, { "name": "Python", "bytes": "457003" }, { "name": "Rebol", "bytes": "106436" }, { "name": "SAS", "bytes": "15821" }, { "name": "Scheme", "bytes": "4249" }, { "name": "Shell", "bytes": "1294787" }, { "name": "Smalltalk", "bytes": "1252" }, { "name": "SourcePawn", "bytes": "4209" }, { "name": "TeX", "bytes": "1014354" }, { "name": "XS", "bytes": "4319" }, { "name": "XSLT", "bytes": "167485" }, { "name": "Yacc", "bytes": "8202" }, { "name": "eC", "bytes": "4568" } ], "symlink_target": "" }
<!-- This file is part of the X12Parser library that provides tools to manipulate X12 messages using Ruby native syntax. http://x12parser.rubyforge.org Copyright (C) 2009 APP Design, Inc. 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 $Id: T1163.xml 78 2009-05-12 22:27:26Z ikk $ --> <Table name="T1163"> <Entry name="AD" value="Adult"/> <Entry name="CH" value="Child"/> <Entry name="EX" value="Discount Coupon Exchange"/> <Entry name="GR" value="Group Rate"/> <Entry name="NR" value="Not Reported"/> <Entry name="RR" value="Reduced Rate"/> <Entry name="SP" value="Any Pass"/> <Entry name="ST" value="Student"/> </Table>
{ "content_hash": "eb1ea8b0353f1d8073cc7ead396085ed", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 81, "avg_line_length": 39.6, "alnum_prop": 0.6948051948051948, "repo_name": "Wylan/x12", "id": "38d72e96331bcabdeca8d1bdf7df38976094c9c5", "size": "1386", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "misc/T1163.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "137790" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using SearchAcceleratorFramework.Collectors; namespace SearchAcceleratorFramework { public class SearchProcessor : ISearchProcessor { private readonly Dictionary<Type, List<IResultCollector>> _collectorMap = new Dictionary<Type, List<IResultCollector>>(); private readonly Dictionary<Type, Func<long, object>> _lookupMap = new Dictionary<Type, Func<long, object>>(); public void RegisterCollector<TResult>(IResultCollector collector) { List<IResultCollector> collectors; var resultType = typeof(TResult); if (!_collectorMap.TryGetValue(resultType, out collectors)) { collectors = new List<IResultCollector>(); } collectors.Add(collector); _collectorMap[resultType] = collectors; } public void RegisterLookup<TResult>(Func<long, object> itemLookupFunc) { Func<long, object> func; var resultType = typeof(TResult); if (!_lookupMap.TryGetValue(resultType, out func)) { _lookupMap.Add(resultType, itemLookupFunc); return; } _lookupMap[resultType] = itemLookupFunc; } public IEnumerable<WeightedSearchResult<TResult>> SearchFor<TResult>(SearchQuery<TResult> query, int? offset = null, int? limit = null) { var resultType = typeof(TResult); List<IResultCollector> collectors; if (!_collectorMap.TryGetValue(resultType, out collectors) || !collectors.Any()) { throw new InvalidOperationException("You must supply at least one collector before issuing search"); } var collectorResults = new List<WeightedItemResult>(); foreach (var collector in collectors) { collectorResults.AddRange(collector.GetWeightedItemsMatching(query.SearchTerm)); } var itemResults = collectorResults .Select(s => s.Id) .Distinct() .Select(s => new { Id = s, Weight = collectorResults.Where(w => w.Id == s).Sum(sm => sm.Weight) }) .OrderByDescending(o => o.Weight) .ToList(); var skip = offset.GetValueOrDefault(0); var hasLimit = limit.HasValue; Func<long, object> lookupFunc; if (!_lookupMap.TryGetValue(resultType, out lookupFunc)) { if (hasLimit) return itemResults .Skip(skip) .Take(limit.Value) .Select(s => new WeightedSearchResult<TResult> { Id = s.Id, Weight = s.Weight }); return itemResults .Skip(skip) .Select(s => new WeightedSearchResult<TResult> { Id = s.Id, Weight = s.Weight }); } if (hasLimit) { return itemResults .Skip(skip) .Take(limit.Value) .Select(s => new WeightedSearchResult<TResult> { Id = s.Id, Weight = s.Weight, Item = (TResult) lookupFunc.Invoke(s.Id) }); } return itemResults .Skip(skip) .Select(s => new WeightedSearchResult<TResult> { Id = s.Id, Weight = s.Weight, Item = (TResult) lookupFunc.Invoke(s.Id) }); } } }
{ "content_hash": "8e4186800ba70510e21a91fc4c5b42cd", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 139, "avg_line_length": 28.68695652173913, "alnum_prop": 0.5959381630797211, "repo_name": "halfbakedbits/SearchAcceleratorFramework", "id": "f997b48eaf915c646164be8bcbd145835236b332", "size": "3301", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SearchAcceleratorFramework/SearchProcessor.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "14804" }, { "name": "JavaScript", "bytes": "3126" } ], "symlink_target": "" }
import * as ts from 'typescript'; import {AbsoluteFsPath} from '../../../ngtsc/path'; import {Decorator} from '../../../ngtsc/reflection'; import {DecoratorHandler, DetectResult} from '../../../ngtsc/transform'; import {DecorationAnalyses, DecorationAnalyzer} from '../../src/analysis/decoration_analyzer'; import {NgccReferencesRegistry} from '../../src/analysis/ngcc_references_registry'; import {Esm2015ReflectionHost} from '../../src/host/esm2015_host'; import {makeTestBundleProgram} from '../helpers/utils'; const TEST_PROGRAM = { name: 'test.js', contents: ` import {Component, Injectable} from '@angular/core'; export class MyComponent {} MyComponent.decorators = [{type: Component}]; export class MyService {} MyService.decorators = [{type: Injectable}]; ` }; const INTERNAL_COMPONENT_PROGRAM = [ { name: 'entrypoint.js', contents: ` import {Component, NgModule} from '@angular/core'; import {ImportedComponent} from './component'; export class LocalComponent {} LocalComponent.decorators = [{type: Component}]; export class MyModule {} MyModule.decorators = [{type: NgModule, args: [{ declarations: [ImportedComponent, LocalComponent], exports: [ImportedComponent, LocalComponent], },] }]; ` }, { name: 'component.js', contents: ` import {Component} from '@angular/core'; export class ImportedComponent {} ImportedComponent.decorators = [{type: Component}]; `, isRoot: false, } ]; function createTestHandler() { const handler = jasmine.createSpyObj<DecoratorHandler<any, any>>('TestDecoratorHandler', [ 'detect', 'analyze', 'compile', ]); // Only detect the Component decorator handler.detect.and.callFake( (node: ts.Declaration, decorators: Decorator[]): DetectResult<any>| undefined => { if (!decorators) { return undefined; } const metadata = decorators.find(d => d.name === 'Component'); if (metadata === undefined) { return undefined; } else { return { metadata, trigger: metadata.node, }; } }); // The "test" analysis is just the name of the decorator being analyzed handler.analyze.and.callFake( ((decl: ts.Declaration, dec: Decorator) => ({analysis: dec.name, diagnostics: undefined}))); // The "test" compilation result is just the name of the decorator being compiled handler.compile.and.callFake(((decl: ts.Declaration, analysis: any) => ({analysis}))); return handler; } describe('DecorationAnalyzer', () => { describe('analyzeProgram()', () => { let program: ts.Program; let testHandler: jasmine.SpyObj<DecoratorHandler<any, any>>; let result: DecorationAnalyses; beforeEach(() => { const {options, host, ...bundle} = makeTestBundleProgram([TEST_PROGRAM]); program = bundle.program; const reflectionHost = new Esm2015ReflectionHost(false, program.getTypeChecker()); const referencesRegistry = new NgccReferencesRegistry(reflectionHost); const analyzer = new DecorationAnalyzer( program, options, host, program.getTypeChecker(), reflectionHost, referencesRegistry, [AbsoluteFsPath.fromUnchecked('/')], false); testHandler = createTestHandler(); analyzer.handlers = [testHandler]; result = analyzer.analyzeProgram(); }); it('should return an object containing a reference to the original source file', () => { const file = program.getSourceFile(TEST_PROGRAM.name) !; expect(result.get(file) !.sourceFile).toBe(file); }); it('should call detect on the decorator handlers with each class from the parsed file', () => { expect(testHandler.detect).toHaveBeenCalledTimes(2); expect(testHandler.detect.calls.allArgs()[0][1]).toEqual([jasmine.objectContaining( {name: 'Component'})]); expect(testHandler.detect.calls.allArgs()[1][1]).toEqual([jasmine.objectContaining( {name: 'Injectable'})]); }); it('should return an object containing the classes that were analyzed', () => { const file = program.getSourceFile(TEST_PROGRAM.name) !; const compiledFile = result.get(file) !; expect(compiledFile.compiledClasses.length).toEqual(1); expect(compiledFile.compiledClasses[0].name).toEqual('MyComponent'); }); it('should analyze and compile the classes that are detected', () => { expect(testHandler.analyze).toHaveBeenCalledTimes(1); expect(testHandler.analyze.calls.allArgs()[0][1].name).toEqual('Component'); expect(testHandler.compile).toHaveBeenCalledTimes(1); expect(testHandler.compile.calls.allArgs()[0][1]).toEqual('Component'); }); describe('internal components', () => { // The problem of exposing the type of these internal components in the .d.ts typing files // is not yet solved. it('should analyze an internally imported component, which is not publicly exported from the entry-point', () => { const {program, options, host} = makeTestBundleProgram(INTERNAL_COMPONENT_PROGRAM); const reflectionHost = new Esm2015ReflectionHost(false, program.getTypeChecker()); const referencesRegistry = new NgccReferencesRegistry(reflectionHost); const analyzer = new DecorationAnalyzer( program, options, host, program.getTypeChecker(), reflectionHost, referencesRegistry, [AbsoluteFsPath.fromUnchecked('/')], false); const testHandler = createTestHandler(); analyzer.handlers = [testHandler]; const result = analyzer.analyzeProgram(); const file = program.getSourceFile('component.js') !; const analysis = result.get(file) !; expect(analysis).toBeDefined(); const ImportedComponent = analysis.compiledClasses.find(f => f.name === 'ImportedComponent') !; expect(ImportedComponent).toBeDefined(); }); it('should analyze an internally defined component, which is not exported at all', () => { const {program, options, host} = makeTestBundleProgram(INTERNAL_COMPONENT_PROGRAM); const reflectionHost = new Esm2015ReflectionHost(false, program.getTypeChecker()); const referencesRegistry = new NgccReferencesRegistry(reflectionHost); const analyzer = new DecorationAnalyzer( program, options, host, program.getTypeChecker(), reflectionHost, referencesRegistry, [AbsoluteFsPath.fromUnchecked('/')], false); const testHandler = createTestHandler(); analyzer.handlers = [testHandler]; const result = analyzer.analyzeProgram(); const file = program.getSourceFile('entrypoint.js') !; const analysis = result.get(file) !; expect(analysis).toBeDefined(); const LocalComponent = analysis.compiledClasses.find(f => f.name === 'LocalComponent') !; expect(LocalComponent).toBeDefined(); }); }); }); });
{ "content_hash": "0a09cfa4144b9fdac23a4419f407e3aa", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 112, "avg_line_length": 41.40350877192982, "alnum_prop": 0.6588983050847458, "repo_name": "hansl/angular", "id": "5798fae8b955f2edb94baeef8431273f141c8a0b", "size": "7282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/compiler-cli/src/ngcc/test/analysis/decoration_analyzer_spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "247" }, { "name": "CSS", "bytes": "337345" }, { "name": "Dockerfile", "bytes": "14627" }, { "name": "HTML", "bytes": "327986" }, { "name": "JSONiq", "bytes": "410" }, { "name": "JavaScript", "bytes": "794437" }, { "name": "PHP", "bytes": "7222" }, { "name": "PowerShell", "bytes": "4229" }, { "name": "Python", "bytes": "329250" }, { "name": "Shell", "bytes": "67724" }, { "name": "TypeScript", "bytes": "17127977" } ], "symlink_target": "" }
<Type Name="ApplicationOptions+OrientationType" FullName="Urho.ApplicationOptions+OrientationType"> <TypeSignature Language="C#" Value="public enum ApplicationOptions.OrientationType" /> <TypeSignature Language="ILAsm" Value=".class nested public auto ansi sealed ApplicationOptions/OrientationType extends System.Enum" /> <AssemblyInfo> <AssemblyName>Urho</AssemblyName> <AssemblyVersion>1.0.0.0</AssemblyVersion> </AssemblyInfo> <Base> <BaseTypeName>System.Enum</BaseTypeName> </Base> <Docs> <summary>Orientation type for the application</summary> <remarks> <para> </para> </remarks> </Docs> <Members> <Member MemberName="Landscape"> <MemberSignature Language="C#" Value="Landscape" /> <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ApplicationOptions/OrientationType Landscape = int32(0)" /> <MemberType>Field</MemberType> <AssemblyInfo> <AssemblyVersion>1.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>Urho.ApplicationOptions+OrientationType</ReturnType> </ReturnValue> <Docs> <summary> <para>Landscape orientation desired.</para> <para> </para> </summary> </Docs> </Member> <Member MemberName="LandscapeAndPortrait"> <MemberSignature Language="C#" Value="LandscapeAndPortrait" /> <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ApplicationOptions/OrientationType LandscapeAndPortrait = int32(2)" /> <MemberType>Field</MemberType> <AssemblyInfo> <AssemblyVersion>1.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>Urho.ApplicationOptions+OrientationType</ReturnType> </ReturnValue> <Docs> <summary>Landscape or portrait orientation accepted.</summary> </Docs> </Member> <Member MemberName="Portrait"> <MemberSignature Language="C#" Value="Portrait" /> <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ApplicationOptions/OrientationType Portrait = int32(1)" /> <MemberType>Field</MemberType> <AssemblyInfo> <AssemblyVersion>1.0.0.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>Urho.ApplicationOptions+OrientationType</ReturnType> </ReturnValue> <Docs> <summary> <para>Portrati orientation desired.</para> <para> </para> </summary> </Docs> </Member> </Members> </Type>
{ "content_hash": "8f9c252bfe3ebf6ec01e2a5546748a06", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 161, "avg_line_length": 37.48571428571429, "alnum_prop": 0.6692073170731707, "repo_name": "florin-chelaru/urho", "id": "c2cb26f357d6b1218eae44c7f9da33d678c1c6b1", "size": "2624", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Docs/Urho/ApplicationOptions+OrientationType.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1504000" }, { "name": "C#", "bytes": "3618775" }, { "name": "C++", "bytes": "982541" }, { "name": "CSS", "bytes": "3736" }, { "name": "F#", "bytes": "14158" }, { "name": "GLSL", "bytes": "156108" }, { "name": "HLSL", "bytes": "181070" }, { "name": "HTML", "bytes": "7034" }, { "name": "Java", "bytes": "131204" }, { "name": "Makefile", "bytes": "4311" }, { "name": "Objective-C", "bytes": "8426" }, { "name": "Perl", "bytes": "9691" } ], "symlink_target": "" }
package com.ilearnrw.api.selectnextword; import ilearnrw.annotation.AnnotatedWord; import ilearnrw.resource.ResourceLoader; import ilearnrw.resource.ResourceLoader.Type; import ilearnrw.textclassification.english.EnglishWord; import ilearnrw.textclassification.greek.GreekWord; import ilearnrw.user.problems.ProblemDefinitionIndex; import ilearnrw.utils.LanguageCode; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.ilearnrw.api.selectnextword.tools.ProblemWordListLoader; public class WordSelectionUtils { /*static public Word[] getListWords(LanguageCode language, int languageArea, int difficulty,int amount, int wordLevel){ ArrayList<String> words = new ProblemWordListLoader(language, languageArea, difficulty).getItems(); int tmp = words.indexOf("###"); if(tmp>-1) words.remove(tmp); if (words.size()==0) return new Word[0]; int validEnd = wordLevel+amount; if (validEnd>=words.size()) validEnd = words.size(); int validStart = validEnd-amount; if(validStart<0) validStart = 0; Word[] targetWords = new Word[amount]; for(int i=validStart;i<validEnd;i++){ if(language == LanguageCode.EN) targetWords[i-validStart] = new EnglishWord(words.get(i)); else targetWords[i-validStart] = new GreekWord(words.get(i)); } //for(int i=validEnd-validStart;i<amount;i++){//if there are not enough words, repeat the first ones // targetWords[i] = targetWords[i-(validEnd-validStart)]; //} return targetWords; }*/ /* Provides words with more than the number of syllables specified */ /*static public List<GameElement> getTargetWordsWithSyllables( LanguageCode language, int languageArea, int difficulty, int amount, int wordLevel, TypeFiller typeDistractors, int numberSyllables){ return getTargetWords( language, languageArea, difficulty, amount, wordLevel,true,typeDistractors, false,numberSyllables,new ArrayList<String>()); }*/ /* Provides distractors that do not contain the given phonemes */ /*static public List<GameElement> getTargetWordsWithoutPhonemes( LanguageCode language, int languageArea, int difficulty, int amount, int wordLevel, boolean isFiller, TypeFiller typeDistractors, List<String> phoneme){ return getTargetWords( language, languageArea, difficulty, amount, wordLevel,false,typeDistractors, isFiller,-1,phoneme); }/* /* Provides words of the specified language area and difficulty */ /*static public List<GameElement> getTargetWords( LanguageCode language, int languageArea, int difficulty, int amount, int wordLevel, TypeFiller typeDistractors){ return getTargetWords( language, languageArea, difficulty, amount, wordLevel,true,typeDistractors,false,-1,new ArrayList<String>()); }*/ /* Provides words of the specified language area and difficulty */ /*static public List<GameElement> getTargetWordsBegins( LanguageCode language, int languageArea, int difficulty, int amount, int wordLevel, TypeFiller typeDistractors, boolean begins, boolean single){ return getTargetWords( language, languageArea, difficulty, amount, wordLevel,true,typeDistractors,false,-1,new ArrayList<String>(),begins,single); }*/ /* Provides words of the specified language area and difficulty, and mark them as distractors or not */ /*static public List<GameElement> getTargetWords( LanguageCode language, int languageArea, int difficulty, int amount, int wordLevel, TypeFiller typeDistractors, boolean isFiller){ return getTargetWords( language, languageArea, difficulty, amount, wordLevel,true,typeDistractors, isFiller,-1,new ArrayList<String>()); }*/ /*static private List<GameElement> getTargetWords( LanguageCode language, int languageArea, int difficulty, int amount, int wordLevel, boolean findDistractors, TypeFiller typeDistractors, boolean isFiller, int numberSyllables, List<String> phoneme){ return getTargetWords(language, languageArea, difficulty, amount, wordLevel, findDistractors, typeDistractors,isFiller, numberSyllables, phoneme,false,false); }*/ static public List<GameElement> getTargetWordsWithDistractorsAndNoPhonemes( LanguageCode language, int languageArea, int difficulty, LevelParameters parameters, int numberSyllables, boolean begins, boolean single){ if(language == LanguageCode.GR) System.err.println("Might not work"); ProblemDefinitionIndex definitions = new ProblemDefinitionIndex(language); List<Integer> selectedDifficulties = WordSelectionUtils.findCompatiblePhoneticDifficulties(language, languageArea, difficulty,parameters.amountDistractors.ordinal()); String[] phonemes = new String[selectedDifficulties.size()]; for(int i =0;i< selectedDifficulties.size();i++){ phonemes[i] = (definitions.getProblemDescription(languageArea, selectedDifficulties.get(i)).getDescriptions()[0].split("-")[1]); } List<GameElement> result = new ArrayList<GameElement>(); int wordsPerDistractor = (int)java.lang.Math.floor(0.25*parameters.batchSize); if(parameters.amountDistractors.ordinal()==0){ wordsPerDistractor = 0; } for(int i=phonemes.length-1;i>=0;i--){ List<String> copy = new ArrayList<String>(); for(int j = 0;j< phonemes.length;j++){ if (j!=i) copy.add(phonemes[j]); } int numberWords = wordsPerDistractor; if(i==0)//Target difficulty numberWords = parameters.batchSize-result.size(); List<GameElement> aux = WordSelectionUtils.getTargetWords( language, languageArea, selectedDifficulties.get(i), numberWords, parameters.wordLevel, false,//complete with distractors TypeFiller.NONE, i!=0, //isFiller numberSyllables, copy, begins, single, parameters.amountTricky); if(i==0) if(aux.size()==0) return aux; for(GameElement ge : aux) result.add(ge); } return result; } static public List<GameElement> getTargetWordsWithDistractors( LanguageCode language, int languageArea, int difficulty, LevelParameters parameters, int numberSyllables, //List<String> phoneme, boolean begins, boolean single){ List<GameElement> result = new ArrayList<GameElement>(); int wordsPerDistractor = (int)java.lang.Math.floor(0.25*parameters.batchSize); if(parameters.amountDistractors.ordinal()==0) wordsPerDistractor = 0; if(parameters.fillerType == TypeFiller.NONE) wordsPerDistractor = 0; if(wordsPerDistractor>0){ List<List<GameElement>> distractors = WordSelectionUtils.getDistractors( language, languageArea, difficulty, wordsPerDistractor, parameters.wordLevel , parameters.amountDistractors.ordinal(),//number of different distractors = amountDistractors.ordinal() (25% of words per distractor) parameters.fillerType, numberSyllables, new ArrayList<String>(), begins, single, parameters.amountTricky); for(List<GameElement> lge : distractors){ for(GameElement ge : lge) result.add(ge); } } int numberTargets = parameters.batchSize-result.size();//After selecting distractors, fill the list with the target words //wordsPerDistractor List<GameElement> targetWords = WordSelectionUtils.getTargetWords( language, languageArea, difficulty, numberTargets, parameters.wordLevel, true, parameters.fillerType, false, numberSyllables, new ArrayList<String>(), begins, single, parameters.amountTricky); if(targetWords.size()==0) return targetWords; for(int i= targetWords.size()-1;i>=0;i--)//Target words placed first result.add(0,targetWords.get(i)); return result; } /* Provides words satisfying all given constraints */ static private List<GameElement> getTargetWords( LanguageCode language, int languageArea, int difficulty, int amount, int wordLevel, boolean completeWithDistractors, TypeFiller typeDistractors, boolean isFiller, int numberSyllables, List<String> phoneme, boolean begins, boolean single, TypeAmount trickyWords){ //TODO tricky words List<String> words; if(language==LanguageCode.EN){ words = new ProblemWordListLoader(language, languageArea, difficulty).getItems(); }else{ words = getListGreekWords(languageArea, difficulty,begins,single); } int tmp = words.indexOf("###"); if(tmp>-1) words.remove(tmp); if (words.size()==0) return new ArrayList<GameElement>(); int validEnd = wordLevel+amount; if (validEnd>=words.size()) validEnd = words.size(); ArrayList<GameElement> targetWords = new ArrayList<GameElement>();// new GameElement[amount]; for(int i=validEnd-1;i>=0;i--){ AnnotatedWord w; if(language == LanguageCode.EN){ w = new AnnotatedWord(new EnglishWord(words.get(i)),languageArea,difficulty); }else{ w = new AnnotatedWord(new GreekWord(words.get(i)),languageArea,difficulty); } if(w.getNumberOfSyllables()<=numberSyllables){ continue; } boolean clean = true; for(String ph : phoneme){ if(w.getPhonetics().contains(ph)){ clean = false; break; } } if(!clean) continue; GameElement ge = new GameElement(isFiller,w); if( ((AnnotatedWord)ge.getAnnotatedWord()).getWordProblems().size()==0)//If no difficulties found, get out! continue; targetWords.add(ge); if (targetWords.size()==amount) break; } if (completeWithDistractors &&(targetWords.size()<amount)){ List<GameElement> distractors = getDistractors( language, languageArea, difficulty, amount-targetWords.size() , wordLevel, 1, typeDistractors, numberSyllables, phoneme, begins, single, trickyWords).get(0); for(GameElement ge : distractors) targetWords.add(ge); } return targetWords; } /* Returns several sets of distractors, each with several different difficulties depending on availability of words */ static private List<List<GameElement>> getDistractors( LanguageCode language, int languageArea, int originalDifficulty, int wordsPerDifficulty, int wordLevel , int numberDifficulties, TypeFiller distractorType, int numberSyllables, List<String> phoneme, boolean begins, boolean single, TypeAmount trickyWords){ ProblemDefinitionIndex definitions = new ProblemDefinitionIndex(language); List<List<GameElement>> distractors = new ArrayList<List<GameElement>>(); for(int i=0;i<numberDifficulties;i++) distractors.add(new ArrayList<GameElement>()); if(distractorType==TypeFiller.CHARACTER){ HashMap<String,List<Integer>> characterSameCluster = new HashMap<String,List<Integer>>(); HashMap<String,List<Integer>> characterDifCluster = new HashMap<String,List<Integer>>(); String targetCharacter = definitions.getProblemDescription(languageArea, originalDifficulty).getCharacter(); int targetCluster = definitions.getProblemDescription(languageArea, originalDifficulty).getCluster(); for(int i = 0; i< definitions.getRowLength(languageArea);i++){ String nextCharacter = definitions.getProblemDescription(languageArea, i).getCharacter(); if(!targetCharacter.equals(nextCharacter))//different character if(targetCluster==definitions.getProblemDescription(languageArea, i).getCluster()){ if(!characterSameCluster.containsKey(nextCharacter)) characterSameCluster.put(nextCharacter, new ArrayList<Integer>()); characterSameCluster.get(nextCharacter).add(i); }else{ if(!characterDifCluster.containsKey(nextCharacter)) characterDifCluster.put(nextCharacter, new ArrayList<Integer>()); characterDifCluster.get(nextCharacter).add(i); } } int currentDifficulty = 0; for(String index : characterSameCluster.keySet()){ List<Integer> newDifficulties = characterSameCluster.get(index); Collections.shuffle(newDifficulties); for(int newDifficulty : newDifficulties){ List<GameElement> aux = getTargetWords( language, languageArea, newDifficulty, wordsPerDifficulty-distractors.get(currentDifficulty).size(), wordLevel, false, distractorType, true, numberSyllables, phoneme, begins, single, trickyWords); for(GameElement ge : aux) distractors.get(currentDifficulty).add(ge); if (distractors.get(currentDifficulty).size()==wordsPerDifficulty){//Move on to fill the next distractor only if we got all necessary words currentDifficulty++; break; } } if(currentDifficulty==numberDifficulties) return distractors; } for(String index : characterDifCluster.keySet()){ List<Integer> newDifficulties = characterDifCluster.get(index); //Randomize order within each cluster Collections.shuffle(newDifficulties); for(int newDifficulty : newDifficulties){ List<GameElement> aux = getTargetWords( language, languageArea, newDifficulty, wordsPerDifficulty-distractors.get(currentDifficulty).size(), wordLevel, false, distractorType, true, numberSyllables, phoneme, begins, single, trickyWords); for(GameElement ge : aux) distractors.get(currentDifficulty).add(ge); if (distractors.get(currentDifficulty).size()==wordsPerDifficulty){//Move on to fill the next distractor only if we got all necessary words currentDifficulty++; break; } } if(currentDifficulty==numberDifficulties) return distractors; } }else{ HashMap<Integer,ArrayList<Integer>> differentClusters = new HashMap<Integer,ArrayList<Integer>>(); int maxCluster = 0; for(int i = 0; i< definitions.getRowLength(languageArea);i++){ if (i==originalDifficulty) continue; int nextCluster = definitions.getProblemDescription(languageArea, i).getCluster();; if (nextCluster> maxCluster) maxCluster = nextCluster; if(!differentClusters.containsKey(nextCluster)){ ArrayList<Integer> singleItem = new ArrayList<Integer>(); singleItem.add(i); differentClusters.put(nextCluster, singleItem); }else{ differentClusters.get(nextCluster).add(i); } } int originalCluster = definitions.getProblemDescription(languageArea, originalDifficulty).getCluster(); int currentDifficulty = 0; for(int cluster=originalCluster;cluster>=0;cluster--){//Distractors from current or previous clusters if (differentClusters.containsKey(cluster)){ Collections.shuffle(differentClusters.get(cluster)); for(int newDifficulty : differentClusters.get(cluster)){ List<GameElement> aux = getTargetWords( language, languageArea, newDifficulty, wordsPerDifficulty-distractors.get(currentDifficulty).size(), wordLevel, false, distractorType, true, numberSyllables, phoneme, begins, single, trickyWords); for(GameElement ge : aux) distractors.get(currentDifficulty).add(ge); if (distractors.get(currentDifficulty).size()==wordsPerDifficulty)//Move on to fill the next distractor only if we got all necessary words currentDifficulty++; if(currentDifficulty==numberDifficulties) return distractors; } } } for(int cluster=originalCluster+1;cluster<=maxCluster;cluster++){//if not enough distractors on current and previous clusters, try next if (differentClusters.containsKey(cluster)){ Collections.shuffle(differentClusters.get(cluster)); for(int newDifficulty : differentClusters.get(cluster)){ List<GameElement> aux = getTargetWords( language, languageArea, newDifficulty, wordsPerDifficulty-distractors.get(currentDifficulty).size(), wordLevel, false, distractorType, true, numberSyllables, phoneme, begins, single, trickyWords); for(GameElement ge : aux) distractors.get(currentDifficulty).add(ge); if (distractors.get(currentDifficulty).size()==wordsPerDifficulty) currentDifficulty++; if(currentDifficulty==numberDifficulties) return distractors; } } } } return distractors; } static public List<Integer> findDifferentCharacter(LanguageCode language, int languageArea, int originalDifficulty,int numberDifficulties){ List<Integer> compatibleDifficulties = new ArrayList<Integer>(); ProblemDefinitionIndex definitions = new ProblemDefinitionIndex(language); List<String> characters = new ArrayList<String>(); compatibleDifficulties.add(originalDifficulty); characters.add(definitions.getProblemDescription(languageArea, originalDifficulty).getCharacter()); for(int i = 0; i< definitions.getRowLength(languageArea);i++){ if (!characters.contains(definitions.getProblemDescription(languageArea, i).getCharacter())){ characters.add(definitions.getProblemDescription(languageArea, i).getCharacter()); compatibleDifficulties.add(i); } } return compatibleDifficulties; } /* Creates a list that alternates words with different patters */ static private List<String> getListGreekWords(int languageArea, int difficulty,boolean begins,boolean single){ ArrayList<String> words = new ArrayList<String>();; try { String filename = "game_words_GR/cat"+languageArea+"/words_"+languageArea+"_"+difficulty+"_GR.json"; String jsonFile = ResourceLoader.getInstance().readAllLinesAsStringUTF8(Type.DATA, filename); HashMap<String, ArrayList<String>> hm = new Gson().fromJson(jsonFile, new TypeToken<HashMap<String, ArrayList<String>>>() {}.getType()); HashMap<String, ArrayList<String>> validWords = new HashMap<String, ArrayList<String>>(); //List<String> validKeys = new ArrayList<String>(); if(begins&single){ for(String key : hm.keySet()){ if (hm.get(key).size()==0) continue; if(key.contains("BEGINS")&!key.contains(" ")){ validWords.put(key, hm.get(key)); } } //No sorting of the keys required }else if(begins){ for(String key : hm.keySet()){ if (hm.get(key).size()==0) continue; if(key.contains("BEGINS")){ String shortKey = key.split(" ")[0]; if(!validWords.containsKey(shortKey)){ validWords.put(shortKey, hm.get(key)); }else{ ArrayList<String> reference = validWords.get(shortKey); for(String word : hm.get(key)){ reference.add(word); } } } } }else{ for(String key : hm.keySet()){ if (hm.get(key).size()==0) continue; List<String> patterns = new ArrayList<String>(); if (key.contains("BEGIN")){ patterns.add(key.split(" ")[0].replace("BEGINS:", "")); } if (key.contains("ENDS")){ String nextPattern = key.split("ENDS:")[1]; if(!patterns.contains(nextPattern)) patterns.add(nextPattern); } if(key.contains("(")){ String[] nextPatterns = key.replace("*","").split("\\(")[1].split("\\)")[0].split(" "); for(String nextPattern : nextPatterns) if(!patterns.contains(nextPattern)) patterns.add(nextPattern); } if(single){ if(patterns.size()==1){ String shortKey = patterns.get(0); if(!validWords.containsKey(shortKey)){ validWords.put(shortKey, hm.get(key)); }else{ ArrayList<String> reference = validWords.get(shortKey); for(String word : hm.get(key)){ reference.add(word); } } } }else{ for(String shortKey : patterns){ if(!validWords.containsKey(shortKey)){ validWords.put(shortKey, new ArrayList<String>()); } } int nextIndex = 0; for(String word : hm.get(key)){//distribute the words along the different patterns validWords.get(patterns.get(nextIndex)).add(word); nextIndex = (nextIndex+1)%patterns.size(); } } } } int maxSize = 0; HashMap<String,Integer> indexes = new HashMap<String,Integer>(); for(String key:validWords.keySet()){ if(validWords.get(key).size()==0){ continue; } indexes.put(key, 0); if(validWords.get(key).size()>maxSize) maxSize = validWords.get(key).size(); } for(int i=0;i<maxSize;i++){ for(String key : validWords.keySet()){ if(validWords.get(key).size()==0){ continue; } int nextIndex = indexes.get(key); if(nextIndex>=validWords.get(key).size()){ nextIndex = validWords.get(key).size()-(maxSize-indexes.get(key)); if(nextIndex<0) nextIndex = 0; } words.add(validWords.get(key).get(nextIndex)); indexes.put(key, nextIndex+1); } } } catch (Exception e) { e.printStackTrace(); return null; } return words; } static public List<Integer> findCompatiblePhoneticDifficulties(LanguageCode language, int languageArea, int originalDifficulty,int numberDifficulties){ List<Integer> compatibleDifficulties = new ArrayList<Integer>(); ProblemDefinitionIndex definitions = new ProblemDefinitionIndex(language); String[] descriptions = definitions.getProblemDescription(languageArea, originalDifficulty).getDescriptions(); if(!descriptions[0].contains("-")) return compatibleDifficulties;//If this difficulty does not contain a phoneme, wth List<String> phonemes = new ArrayList<String>(); compatibleDifficulties.add(originalDifficulty); phonemes.add(descriptions[0].split("-")[1]); HashMap<Integer,ArrayList<Integer>> differentClusters = new HashMap<Integer,ArrayList<Integer>>(); int maxCluster = 0; for(int i = 0; i< definitions.getRowLength(languageArea);i++){ if (i==originalDifficulty) continue; int nextCluster = definitions.getProblemDescription(languageArea, i).getCluster(); if (nextCluster> maxCluster) maxCluster = nextCluster; if(!differentClusters.containsKey(nextCluster)){ ArrayList<Integer> singleItem = new ArrayList<Integer>(); singleItem.add(i); differentClusters.put(nextCluster, singleItem); }else{ differentClusters.get(nextCluster).add(i); } } int originalCluster = definitions.getProblemDescription(languageArea, originalDifficulty).getCluster(); for(int cluster=originalCluster;cluster>=0;cluster--){ if (differentClusters.containsKey(cluster)){ for(int newDifficulty : differentClusters.get(cluster)){ String[] newDescriptions = definitions.getProblemDescription(languageArea, newDifficulty).getDescriptions(); if(!newDescriptions[0].contains("-")) continue; String newPhoneme = newDescriptions[0].split("-")[1]; boolean clean = true; for(String phoneme : phonemes){ if (phoneme.contains(newPhoneme) || newPhoneme.contains(phoneme)){ clean = false; break; } } if(clean){ compatibleDifficulties.add(newDifficulty); phonemes.add(newPhoneme); if(compatibleDifficulties.size()==numberDifficulties+1) return compatibleDifficulties; } } } } for(int cluster=originalCluster+1;cluster<=maxCluster;cluster++){ if (differentClusters.containsKey(cluster)){ for(int newDifficulty : differentClusters.get(cluster)){ String[] newDescriptions = definitions.getProblemDescription(languageArea, newDifficulty).getDescriptions(); if(!newDescriptions[0].contains("-")) continue; String newPhoneme = newDescriptions[0].split("-")[1]; boolean clean = true; for(String phoneme : phonemes){ if (phoneme.contains(newPhoneme) || newPhoneme.contains(phoneme)){ clean = false; break; } } if(clean){ compatibleDifficulties.add(newDifficulty); phonemes.add(newPhoneme); if(compatibleDifficulties.size()==numberDifficulties+1) return compatibleDifficulties; } } } } return compatibleDifficulties; } /*static public List<GameElement> getClusterDistractors( LanguageCode language, int languageArea, int difficulty, int wordsPerDifficulty, int wordLevel, int numberDifficulties, TypeFiller distractorType){ ProblemDefinitionIndex definitions = new ProblemDefinitionIndex(language); int targetCluster = definitions.getProblemDescription(languageArea, difficulty).getCluster(); ArrayList<Integer> candidates = new ArrayList<Integer>(); for(int ii = 0; ii< definitions.getRowLength(languageArea);ii++){ if(ii!=difficulty) if(definitions.getProblemDescription(languageArea, ii).getCluster()==targetCluster){ if(getTargetWords( language, languageArea, ii, 1, wordLevel,distractorType,true).size()>0) candidates.add(ii); } } if (candidates.size()<numberDifficulties){//When there are no more difficulties within the cluster, use the previous difficulties for(int ii = 0; ii< difficulty;ii++){ if(getTargetWords( language, languageArea, ii, 1, wordLevel,distractorType,true).size()>0) candidates.add(ii); } } if (candidates.size()<numberDifficulties){//As last resort, use the next difficulties for(int ii = difficulty+1; ii< definitions.getRowLength(languageArea);ii++){ if(getTargetWords( language, languageArea, ii, 1, wordLevel,distractorType,true).size()>0) candidates.add(ii); } } Random rand = new Random(); List<GameElement> result = new ArrayList<GameElement>(); int numberFillers = numberDifficulties; int adjustedWordsPerDifficulty = wordsPerDifficulty; // if (candidates.size()<numberDifficulties){ // adjustedWordsPerDifficulty = (int) Math.ceil(wordsPerDifficulty*numberDifficulties/candidates.size()); // } while((numberFillers>0)&&(candidates.size()>0)){ int index = rand.nextInt(candidates.size()); int newDifficulty = candidates.get(index); List<GameElement> aux = getTargetWords( language, languageArea, newDifficulty, adjustedWordsPerDifficulty, wordLevel,distractorType,true); if (aux.size()>0) numberFillers--; for(GameElement ge : aux) result.add(ge); candidates.remove(index); } return result; }*/ }
{ "content_hash": "1abacfa3f7cd887a28d3067e9b030f42", "timestamp": "", "source": "github", "line_count": 1010, "max_line_length": 168, "avg_line_length": 26.397029702970297, "alnum_prop": 0.6939349611792506, "repo_name": "mpakarlsson/ilearnrw-service", "id": "29ae0e6566e0d026daf396722f48b3ec981ceefe", "size": "26766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/ilearnrw/api/selectnextword/WordSelectionUtils.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "105269" }, { "name": "HTML", "bytes": "32443" }, { "name": "Java", "bytes": "746142" }, { "name": "JavaScript", "bytes": "818188" } ], "symlink_target": "" }
class AddNewsVolunteerToPartners < ActiveRecord::Migration[5.0] def change add_column :partners, :news, :text add_column :partners, :volunteer, :text end end
{ "content_hash": "06707a2a9ce877c3c6626f54e5256841", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 63, "avg_line_length": 28.333333333333332, "alnum_prop": 0.7294117647058823, "repo_name": "russellschmidt/climate-cents", "id": "4c4c7360c902ea1133ad10459046e5d07e98ba90", "size": "170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20170225234932_add_news_volunteer_to_partners.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16552705" }, { "name": "CoffeeScript", "bytes": "2790" }, { "name": "HTML", "bytes": "297878" }, { "name": "JavaScript", "bytes": "6807437" }, { "name": "Ruby", "bytes": "290423" } ], "symlink_target": "" }
#ifndef __DEBUG_PORT_H__ #define __DEBUG_PORT_H__ /// /// DebugPortIo protocol {EBA4E8D2-3858-41EC-A281-2647BA9660D0} /// #define EFI_DEBUGPORT_PROTOCOL_GUID \ { \ 0xEBA4E8D2, 0x3858, 0x41EC, {0xA2, 0x81, 0x26, 0x47, 0xBA, 0x96, 0x60, 0xD0 } \ } extern EFI_GUID gEfiDebugPortProtocolGuid; typedef struct _EFI_DEBUGPORT_PROTOCOL EFI_DEBUGPORT_PROTOCOL; // // DebugPort member functions // /** Resets the debugport. @param This A pointer to the EFI_DEBUGPORT_PROTOCOL instance. @retval EFI_SUCCESS The debugport device was reset and is in usable state. @retval EFI_DEVICE_ERROR The debugport device could not be reset and is unusable. **/ typedef EFI_STATUS (EFIAPI *EFI_DEBUGPORT_RESET)( IN EFI_DEBUGPORT_PROTOCOL *This ); /** Writes data to the debugport. @param This A pointer to the EFI_DEBUGPORT_PROTOCOL instance. @param Timeout The number of microseconds to wait before timing out a write operation. @param BufferSize On input, the requested number of bytes of data to write. On output, the number of bytes of data actually written. @param Buffer A pointer to a buffer containing the data to write. @retval EFI_SUCCESS The data was written. @retval EFI_DEVICE_ERROR The device reported an error. @retval EFI_TIMEOUT The data write was stopped due to a timeout. **/ typedef EFI_STATUS (EFIAPI *EFI_DEBUGPORT_WRITE)( IN EFI_DEBUGPORT_PROTOCOL *This, IN UINT32 Timeout, IN OUT UINTN *BufferSize, IN VOID *Buffer ); /** Reads data from the debugport. @param This A pointer to the EFI_DEBUGPORT_PROTOCOL instance. @param Timeout The number of microseconds to wait before timing out a read operation. @param BufferSize On input, the requested number of bytes of data to read. On output, the number of bytes of data actually number of bytes of data read and returned in Buffer. @param Buffer A pointer to a buffer into which the data read will be saved. @retval EFI_SUCCESS The data was read. @retval EFI_DEVICE_ERROR The device reported an error. @retval EFI_TIMEOUT The operation was stopped due to a timeout or overrun. **/ typedef EFI_STATUS (EFIAPI *EFI_DEBUGPORT_READ)( IN EFI_DEBUGPORT_PROTOCOL *This, IN UINT32 Timeout, IN OUT UINTN *BufferSize, OUT VOID *Buffer ); /** Checks to see if any data is available to be read from the debugport device. @param This A pointer to the EFI_DEBUGPORT_PROTOCOL instance. @retval EFI_SUCCESS At least one byte of data is available to be read. @retval EFI_DEVICE_ERROR The debugport device is not functioning correctly. @retval EFI_NOT_READY No data is available to be read. **/ typedef EFI_STATUS (EFIAPI *EFI_DEBUGPORT_POLL)( IN EFI_DEBUGPORT_PROTOCOL *This ); /// /// This protocol provides the communication link between the debug agent and the remote host. /// struct _EFI_DEBUGPORT_PROTOCOL { EFI_DEBUGPORT_RESET Reset; EFI_DEBUGPORT_WRITE Write; EFI_DEBUGPORT_READ Read; EFI_DEBUGPORT_POLL Poll; }; // // DEBUGPORT variable definitions... // #define EFI_DEBUGPORT_VARIABLE_NAME L"DEBUGPORT" #define EFI_DEBUGPORT_VARIABLE_GUID EFI_DEBUGPORT_PROTOCOL_GUID extern EFI_GUID gEfiDebugPortVariableGuid; // // DebugPort device path definitions... // #define DEVICE_PATH_MESSAGING_DEBUGPORT EFI_DEBUGPORT_PROTOCOL_GUID extern EFI_GUID gEfiDebugPortDevicePathGuid; typedef struct { EFI_DEVICE_PATH_PROTOCOL Header; EFI_GUID Guid; } DEBUGPORT_DEVICE_PATH; #endif
{ "content_hash": "7e2be7698466385fe06d34b3eb6bc277", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 115, "avg_line_length": 36.19083969465649, "alnum_prop": 0.5391267665049567, "repo_name": "jjingram/schminke", "id": "2e09033b10859150e82a77f1beffad4b399d48aa", "size": "5518", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "inc/edk2/MdePkg/Include/Protocol/DebugPort.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3445510" }, { "name": "C++", "bytes": "485675" }, { "name": "Makefile", "bytes": "1393" }, { "name": "Objective-C", "bytes": "745414" } ], "symlink_target": "" }
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2016, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "GafferScene/Private/IECoreScenePreview/Renderer.h" #include "GafferScene/Private/IECoreScenePreview/Procedural.h" #include "IECoreArnold/CameraAlgo.h" #include "IECoreArnold/NodeAlgo.h" #include "IECoreArnold/ParameterAlgo.h" #include "IECoreArnold/ShaderNetworkAlgo.h" #include "IECoreArnold/UniverseBlock.h" #include "IECoreScene/Camera.h" #include "IECoreScene/CurvesPrimitive.h" #include "IECoreScene/ExternalProcedural.h" #include "IECoreScene/MeshPrimitive.h" #include "IECoreScene/Shader.h" #include "IECoreScene/SpherePrimitive.h" #include "IECoreScene/Transform.h" #include "IECoreVDB/VDBObject.h" #include "IECoreVDB/TypeIds.h" #include "IECore/MessageHandler.h" #include "IECore/SimpleTypedData.h" #include "IECore/StringAlgo.h" #include "IECore/VectorTypedData.h" #include "IECore/Version.h" #include "boost/algorithm/string.hpp" #include "boost/algorithm/string/join.hpp" #include "boost/algorithm/string/predicate.hpp" #include "boost/bind.hpp" #include "boost/container/flat_map.hpp" #include "boost/date_time/posix_time/posix_time.hpp" #include "boost/filesystem/operations.hpp" #include "boost/format.hpp" #include "boost/lexical_cast.hpp" #include "boost/optional.hpp" #include "ai_array.h" #include "ai_msg.h" #include "ai_procedural.h" #include "ai_ray.h" #include "ai_render.h" #include "ai_scene.h" #include "ai_stats.h" #include "tbb/concurrent_unordered_map.h" #include "tbb/concurrent_vector.h" #include "tbb/partitioner.h" #include "tbb/spin_mutex.h" #include <condition_variable> #include <functional> #include <memory> #include <sstream> #include <thread> #include <unordered_set> using namespace std; using namespace boost::filesystem; using namespace IECoreArnold; ////////////////////////////////////////////////////////////////////////// // Utilities ////////////////////////////////////////////////////////////////////////// namespace { typedef std::shared_ptr<AtNode> SharedAtNodePtr; typedef bool (*NodeDeleter)( AtNode *); bool nullNodeDeleter( AtNode *node ) { return false; } NodeDeleter nodeDeleter( IECoreScenePreview::Renderer::RenderType renderType ) { if( renderType == IECoreScenePreview::Renderer::Interactive ) { // As interactive edits add/remove objects and shaders, we want to // destroy any AtNodes that are no longer needed. return AiNodeDestroy; } else { // Edits are not possible, so we have no need to delete nodes except // when shutting the renderer down. `AiEnd()` (as called by ~UniverseBlock) // automatically destroys all nodes and is _much_ faster than destroying // them one by one with AiNodeDestroy. So we use a null deleter so that we // don't try to destroy the nodes ourselves, and rely entirely on `AiEnd()`. return nullNodeDeleter; } } template<typename T> T *reportedCast( const IECore::RunTimeTyped *v, const char *type, const IECore::InternedString &name ) { T *t = IECore::runTimeCast<T>( v ); if( t ) { return t; } IECore::msg( IECore::Msg::Warning, "IECoreArnold::Renderer", boost::format( "Expected %s but got %s for %s \"%s\"." ) % T::staticTypeName() % v->typeName() % type % name.c_str() ); return nullptr; } template<typename T> T parameter( const IECore::CompoundDataMap &parameters, const IECore::InternedString &name, const T &defaultValue ) { IECore::CompoundDataMap::const_iterator it = parameters.find( name ); if( it == parameters.end() ) { return defaultValue; } typedef IECore::TypedData<T> DataType; if( const DataType *d = reportedCast<const DataType>( it->second.get(), "parameter", name ) ) { return d->readable(); } else { return defaultValue; } } std::string formatHeaderParameter( const std::string name, const IECore::Data *data ) { if( const IECore::BoolData *boolData = IECore::runTimeCast<const IECore::BoolData>( data ) ) { return boost::str( boost::format( "int '%s' %i" ) % name % int(boolData->readable()) ); } else if( const IECore::FloatData *floatData = IECore::runTimeCast<const IECore::FloatData>( data ) ) { return boost::str( boost::format( "float '%s' %f" ) % name % floatData->readable() ); } else if( const IECore::IntData *intData = IECore::runTimeCast<const IECore::IntData>( data ) ) { return boost::str( boost::format( "int '%s' %i" ) % name % intData->readable() ); } else if( const IECore::StringData *stringData = IECore::runTimeCast<const IECore::StringData>( data ) ) { return boost::str( boost::format( "string '%s' %s" ) % name % stringData->readable() ); } else if( const IECore::V2iData *v2iData = IECore::runTimeCast<const IECore::V2iData>( data ) ) { return boost::str( boost::format( "string '%s' %s" ) % name % v2iData->readable() ); } else if( const IECore::V3iData *v3iData = IECore::runTimeCast<const IECore::V3iData>( data ) ) { return boost::str( boost::format( "string '%s' %s" ) % name % v3iData->readable() ); } else if( const IECore::V2fData *v2fData = IECore::runTimeCast<const IECore::V2fData>( data ) ) { return boost::str( boost::format( "string '%s' %s" ) % name % v2fData->readable() ); } else if( const IECore::V3fData *v3fData = IECore::runTimeCast<const IECore::V3fData>( data ) ) { return boost::str( boost::format( "string '%s' %s" ) % name % v3fData->readable() ); } else if( const IECore::Color3fData *c3fData = IECore::runTimeCast<const IECore::Color3fData>( data ) ) { return boost::str( boost::format( "string '%s' %s" ) % name % c3fData->readable() ); } else if( const IECore::Color4fData *c4fData = IECore::runTimeCast<const IECore::Color4fData>( data ) ) { return boost::str( boost::format( "string '%s' %s" ) % name % c4fData->readable() ); } else { IECore::msg( IECore::Msg::Warning, "IECoreArnold::Renderer", boost::format( "Cannot convert data \"%s\" of type \"%s\"." ) % name % data->typeName() ); return ""; } } void substituteShaderIfNecessary( IECoreScene::ConstShaderNetworkPtr &shaderNetwork, const IECore::CompoundObject *attributes ) { if( !shaderNetwork ) { return; } IECore::MurmurHash h; shaderNetwork->hashSubstitutions( attributes, h ); if( h != IECore::MurmurHash() ) { IECoreScene::ShaderNetworkPtr substituted = shaderNetwork->copy(); substituted->applySubstitutions( attributes ); shaderNetwork = substituted; } } void hashShaderOutputParameter( const IECoreScene::ShaderNetwork *network, const IECoreScene::ShaderNetwork::Parameter &parameter, IECore::MurmurHash &h ) { h.append( parameter.name ); network->getShader( parameter.shader )->hash( h ); for( const auto &i : network->inputConnections( parameter.shader ) ) { h.append( i.destination.name ); hashShaderOutputParameter( network, i.source, h ); } } // Arnold does not support non-uniform sampling. It just takes a start and end // time, and assumes the samples are distributed evenly between them. Throw an // exception if given data we can't render. void ensureUniformTimeSamples( const std::vector<float> &times ) { if( times.size() == 0 ) { throw IECore::Exception( "Motion block times must not be empty" ); } float motionStart = times[0]; float motionEnd = times[ times.size() - 1 ]; for( unsigned int i = 0; i < times.size(); i++ ) { // Use a really coarse epsilon to check if the values are uniform - if someone is sloppy with // floating point precision when computing their sample times, we don't want to stop them from rendering. // But we should warn someone if they are actually trying to use a feature Arnold doesn't support. const float uniformity_epsilon = 0.01; float expectedTime = motionStart + ( motionEnd - motionStart ) / ( times.size() - 1 ) * i; if( times[i] < expectedTime - uniformity_epsilon || times[i] > expectedTime + uniformity_epsilon ) { std::stringstream text; text << "Arnold does not support non-uniform motion blocks.\n"; text << "Invalid motion block: [ " << times[0]; for( unsigned int j = 1; j < times.size(); j++ ) { text << ", " << times[j]; } text << " ]\n"; text << "( sample " << i << ", with value " << times[i] << " does not match " << expectedTime << ")\n"; throw IECore::Exception( text.str() ); } } } const AtString g_aaSamplesArnoldString( "AA_samples" ); const AtString g_aaSeedArnoldString( "AA_seed" ); const AtString g_aovShadersArnoldString( "aov_shaders" ); const AtString g_autoArnoldString( "auto" ); const AtString g_atmosphereArnoldString( "atmosphere" ); const AtString g_backgroundArnoldString( "background" ); const AtString g_boxArnoldString("box"); const AtString g_cameraArnoldString( "camera" ); const AtString g_catclarkArnoldString("catclark"); const AtString g_colorManagerArnoldString( "color_manager" ); const AtString g_customAttributesArnoldString( "custom_attributes" ); const AtString g_curvesArnoldString("curves"); const AtString g_dispMapArnoldString( "disp_map" ); const AtString g_dispHeightArnoldString( "disp_height" ); const AtString g_dispPaddingArnoldString( "disp_padding" ); const AtString g_dispZeroValueArnoldString( "disp_zero_value" ); const AtString g_dispAutoBumpArnoldString( "disp_autobump" ); const AtString g_enableProgressiveRenderString( "enable_progressive_render" ); const AtString g_fileNameArnoldString( "filename" ); const AtString g_filtersArnoldString( "filters" ); const AtString g_funcPtrArnoldString( "funcptr" ); const AtString g_ginstanceArnoldString( "ginstance" ); const AtString g_ignoreMotionBlurArnoldString( "ignore_motion_blur" ); const AtString g_lightGroupArnoldString( "light_group" ); const AtString g_shadowGroupArnoldString( "shadow_group" ); const AtString g_linearArnoldString( "linear" ); const AtString g_matrixArnoldString( "matrix" ); const AtString g_geometryMatrixArnoldString( "geometry_matrix" ); const AtString g_matteArnoldString( "matte" ); const AtString g_meshArnoldString( "mesh" ); const AtString g_modeArnoldString( "mode" ); const AtString g_minPixelWidthArnoldString( "min_pixel_width" ); const AtString g_meshLightArnoldString("mesh_light"); const AtString g_motionStartArnoldString( "motion_start" ); const AtString g_motionEndArnoldString( "motion_end" ); const AtString g_nameArnoldString( "name" ); const AtString g_nodeArnoldString("node"); const AtString g_objectArnoldString( "object" ); const AtString g_opaqueArnoldString( "opaque" ); const AtString g_proceduralArnoldString( "procedural" ); const AtString g_pinCornersArnoldString( "pin_corners" ); const AtString g_pixelAspectRatioArnoldString( "pixel_aspect_ratio" ); const AtString g_pluginSearchPathArnoldString( "plugin_searchpath" ); const AtString g_polymeshArnoldString("polymesh"); const AtString g_rasterArnoldString( "raster" ); const AtString g_receiveShadowsArnoldString( "receive_shadows" ); const AtString g_regionMinXArnoldString( "region_min_x" ); const AtString g_regionMaxXArnoldString( "region_max_x" ); const AtString g_regionMinYArnoldString( "region_min_y" ); const AtString g_regionMaxYArnoldString( "region_max_y" ); const AtString g_renderSessionArnoldString( "render_session" ); const AtString g_selfShadowsArnoldString( "self_shadows" ); const AtString g_shaderArnoldString( "shader" ); const AtString g_shutterStartArnoldString( "shutter_start" ); const AtString g_shutterEndArnoldString( "shutter_end" ); const AtString g_sidednessArnoldString( "sidedness" ); const AtString g_sphereArnoldString("sphere"); const AtString g_sssSetNameArnoldString( "sss_setname" ); const AtString g_stepSizeArnoldString( "step_size" ); const AtString g_stepScaleArnoldString( "step_scale" ); const AtString g_subdivDicingCameraString( "subdiv_dicing_camera" ); const AtString g_subdivIterationsArnoldString( "subdiv_iterations" ); const AtString g_subdivAdaptiveErrorArnoldString( "subdiv_adaptive_error" ); const AtString g_subdivAdaptiveMetricArnoldString( "subdiv_adaptive_metric" ); const AtString g_subdivAdaptiveSpaceArnoldString( "subdiv_adaptive_space" ); const AtString g_subdivFrustumIgnoreArnoldString( "subdiv_frustum_ignore" ); const AtString g_subdivSmoothDerivsArnoldString( "subdiv_smooth_derivs" ); const AtString g_subdivTypeArnoldString( "subdiv_type" ); const AtString g_subdivUVSmoothingArnoldString( "subdiv_uv_smoothing" ); const AtString g_toonIdArnoldString( "toon_id" ); const AtString g_traceSetsArnoldString( "trace_sets" ); const AtString g_transformTypeArnoldString( "transform_type" ); const AtString g_thickArnoldString( "thick" ); const AtString g_useLightGroupArnoldString( "use_light_group" ); const AtString g_useShadowGroupArnoldString( "use_shadow_group" ); const AtString g_userPtrArnoldString( "userptr" ); const AtString g_visibilityArnoldString( "visibility" ); const AtString g_autobumpVisibilityArnoldString( "autobump_visibility" ); const AtString g_volumeArnoldString("volume"); const AtString g_volumePaddingArnoldString( "volume_padding" ); const AtString g_volumeGridsArnoldString( "grids" ); const AtString g_velocityGridsArnoldString( "velocity_grids" ); const AtString g_velocityScaleArnoldString( "velocity_scale" ); const AtString g_velocityFPSArnoldString( "velocity_fps" ); const AtString g_velocityOutlierThresholdArnoldString( "velocity_outlier_threshold" ); const AtString g_widthArnoldString( "width" ); const AtString g_xresArnoldString( "xres" ); const AtString g_yresArnoldString( "yres" ); const AtString g_filterMapArnoldString( "filtermap" ); const AtString g_uvRemapArnoldString( "uv_remap" ); } // namespace ////////////////////////////////////////////////////////////////////////// // ArnoldRendererBase forward declaration ////////////////////////////////////////////////////////////////////////// namespace { class ArnoldGlobals; class Instance; IE_CORE_FORWARDDECLARE( ShaderCache ); IE_CORE_FORWARDDECLARE( InstanceCache ); IE_CORE_FORWARDDECLARE( ArnoldObject ); /// This class implements the basics of outputting attributes /// and objects to Arnold, but is not a complete implementation /// of the renderer interface. It is subclassed to provide concrete /// implementations suitable for use as the master renderer or /// for use in procedurals. class ArnoldRendererBase : public IECoreScenePreview::Renderer { public : ~ArnoldRendererBase() override; IECore::InternedString name() const override; Renderer::AttributesInterfacePtr attributes( const IECore::CompoundObject *attributes ) override; ObjectInterfacePtr camera( const std::string &name, const IECoreScene::Camera *camera, const AttributesInterface *attributes ) override; ObjectInterfacePtr camera( const std::string &name, const std::vector<const IECoreScene::Camera *> &samples, const std::vector<float> &times, const AttributesInterface *attributes ) override; ObjectInterfacePtr light( const std::string &name, const IECore::Object *object, const AttributesInterface *attributes ) override; ObjectInterfacePtr lightFilter( const std::string &name, const IECore::Object *object, const AttributesInterface *attributes ) override; Renderer::ObjectInterfacePtr object( const std::string &name, const IECore::Object *object, const AttributesInterface *attributes ) override; ObjectInterfacePtr object( const std::string &name, const std::vector<const IECore::Object *> &samples, const std::vector<float> &times, const AttributesInterface *attributes ) override; protected : ArnoldRendererBase( NodeDeleter nodeDeleter, AtUniverse *universe, AtNode *parentNode = nullptr, const IECore::MessageHandlerPtr &messageHandler = IECore::MessageHandlerPtr() ); NodeDeleter m_nodeDeleter; AtUniverse *m_universe; ShaderCachePtr m_shaderCache; InstanceCachePtr m_instanceCache; IECore::MessageHandlerPtr m_messageHandler; private : AtNode *m_parentNode; }; } // namespace ////////////////////////////////////////////////////////////////////////// // ArnoldOutput ////////////////////////////////////////////////////////////////////////// namespace { class ArnoldOutput : public IECore::RefCounted { public : ArnoldOutput( AtUniverse *universe, const IECore::InternedString &name, const IECoreScene::Output *output, NodeDeleter nodeDeleter ) { // Create a driver node and set its parameters. AtString driverNodeType( output->getType().c_str() ); if( AiNodeEntryGetType( AiNodeEntryLookUp( driverNodeType ) ) != AI_NODE_DRIVER ) { // Automatically map tiff to driver_tiff and so on, to provide a degree of // compatibility with existing renderman driver names. AtString prefixedType( ( std::string("driver_") + driverNodeType.c_str() ).c_str() ); if( AiNodeEntryLookUp( prefixedType ) ) { driverNodeType = prefixedType; } } const std::string driverNodeName = boost::str( boost::format( "ieCoreArnold:display:%s" ) % name.string() ); m_driver.reset( AiNode( universe, driverNodeType, AtString( driverNodeName.c_str() ) ), nodeDeleter ); if( !m_driver ) { throw IECore::Exception( boost::str( boost::format( "Unable to create output driver of type \"%s\"" ) % driverNodeType.c_str() ) ); } if( const AtParamEntry *fileNameParameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( m_driver.get() ), g_fileNameArnoldString ) ) { AiNodeSetStr( m_driver.get(), AiParamGetName( fileNameParameter ), AtString( output->getName().c_str() ) ); } IECore::StringVectorDataPtr customAttributesData; if( const IECore::StringVectorData *d = output->parametersData()->member<IECore::StringVectorData>( "custom_attributes") ) { customAttributesData = d->copy(); } else { customAttributesData = new IECore::StringVectorData(); } std::vector<std::string> &customAttributes = customAttributesData->writable(); for( IECore::CompoundDataMap::const_iterator it = output->parameters().begin(), eIt = output->parameters().end(); it != eIt; ++it ) { if( boost::starts_with( it->first.string(), "filter" ) ) { continue; } if( boost::starts_with( it->first.string(), "header:" ) ) { std::string formattedString = formatHeaderParameter( it->first.string().substr( 7 ), it->second.get() ); if( !formattedString.empty()) { customAttributes.push_back( formattedString ); } } if( it->first.string() == "camera" ) { if( const IECore::StringData *d = IECore::runTimeCast<const IECore::StringData>( it->second.get() ) ) { m_cameraOverride = d->readable(); continue; } } ParameterAlgo::setParameter( m_driver.get(), it->first.c_str(), it->second.get() ); } if( AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( m_driver.get() ), g_customAttributesArnoldString ) ) { ParameterAlgo::setParameter( m_driver.get(), "custom_attributes", customAttributesData.get() ); } // Create a filter. std::string filterNodeType = parameter<std::string>( output->parameters(), "filter", "gaussian" ); if( AiNodeEntryGetType( AiNodeEntryLookUp( AtString( filterNodeType.c_str() ) ) ) != AI_NODE_FILTER ) { filterNodeType = filterNodeType + "_filter"; } const std::string filterNodeName = boost::str( boost::format( "ieCoreArnold:filter:%s" ) % name.string() ); m_filter.reset( AiNode( universe, AtString( filterNodeType.c_str() ), AtString( filterNodeName.c_str() ) ), nodeDeleter ); if( AiNodeEntryGetType( AiNodeGetNodeEntry( m_filter.get() ) ) != AI_NODE_FILTER ) { throw IECore::Exception( boost::str( boost::format( "Unable to create filter of type \"%s\"" ) % filterNodeType ) ); } for( IECore::CompoundDataMap::const_iterator it = output->parameters().begin(), eIt = output->parameters().end(); it != eIt; ++it ) { if( !boost::starts_with( it->first.string(), "filter" ) || it->first == "filter" ) { continue; } if( it->first == "filterwidth" ) { // Special case to convert RenderMan style `float filterwidth[2]` into // Arnold style `float width`. if( const IECore::V2fData *v = IECore::runTimeCast<const IECore::V2fData>( it->second.get() ) ) { if( v->readable().x != v->readable().y ) { IECore::msg( IECore::Msg::Warning, "IECoreArnold::Renderer", "Non-square filterwidth not supported" ); } AiNodeSetFlt( m_filter.get(), g_widthArnoldString, v->readable().x ); continue; } } ParameterAlgo::setParameter( m_filter.get(), it->first.c_str() + 6, it->second.get() ); } // Convert the data specification to the form // supported by Arnold. m_data = output->getData(); m_lpeName = "ieCoreArnold:lpe:" + name.string(); m_lpeValue = ""; if( m_data=="rgb" ) { m_data = "RGB RGB"; } else if( m_data=="rgba" ) { m_data = "RGBA RGBA"; } else { std::string arnoldType = "RGB"; if( parameter<bool>( output->parameters(), "includeAlpha", false ) ) { arnoldType = "RGBA"; } vector<std::string> tokens; IECore::StringAlgo::tokenize( m_data, ' ', tokens ); if( tokens.size() == 2 ) { if( tokens[0] == "color" ) { m_data = tokens[1] + " " + arnoldType; } else if( tokens[0] == "lpe" ) { m_lpeValue = tokens[1]; m_data = m_lpeName + " " + arnoldType; } } } } void append( std::vector<std::string> &outputs, std::vector<std::string> &lightPathExpressions ) const { outputs.push_back( boost::str( boost::format( "%s %s %s" ) % m_data % AiNodeGetName( m_filter.get() ) % AiNodeGetName( m_driver.get() ) ) ); if( m_lpeValue.size() ) { lightPathExpressions.push_back( m_lpeName + " " + m_lpeValue ); } } const std::string &cameraOverride() { return m_cameraOverride; } private : SharedAtNodePtr m_driver; SharedAtNodePtr m_filter; std::string m_data; std::string m_lpeName; std::string m_lpeValue; std::string m_cameraOverride; }; IE_CORE_DECLAREPTR( ArnoldOutput ) } // namespace ////////////////////////////////////////////////////////////////////////// // ArnoldShader ////////////////////////////////////////////////////////////////////////// namespace { class ArnoldShader : public IECore::RefCounted { public : ArnoldShader( const IECoreScene::ShaderNetwork *shaderNetwork, NodeDeleter nodeDeleter, AtUniverse *universe, const std::string &name, const AtNode *parentNode ) : m_nodeDeleter( nodeDeleter ), m_hash( shaderNetwork->Object::hash() ) { m_nodes = ShaderNetworkAlgo::convert( shaderNetwork, universe, name, parentNode ); } ~ArnoldShader() override { for( std::vector<AtNode *>::const_iterator it = m_nodes.begin(), eIt = m_nodes.end(); it != eIt; ++it ) { m_nodeDeleter( *it ); } } bool update( const IECoreScene::ShaderNetwork *shaderNetwork ) { // `ShaderNetworkAlgo::update()` will destroy unwanted nodes, so we can // only call it if we're responsible for deleting them in the first place. assert( m_nodeDeleter == AiNodeDestroy ); return ShaderNetworkAlgo::update( m_nodes, shaderNetwork ); } AtNode *root() const { return !m_nodes.empty() ? m_nodes.back() : nullptr; } void nodesCreated( vector<AtNode *> &nodes ) const { nodes.insert( nodes.end(), m_nodes.begin(), m_nodes.end() ); } void hash( IECore::MurmurHash &h ) const { h.append( m_hash ); } private : NodeDeleter m_nodeDeleter; std::vector<AtNode *> m_nodes; const IECore::MurmurHash m_hash; }; IE_CORE_DECLAREPTR( ArnoldShader ) class ShaderCache : public IECore::RefCounted { public : ShaderCache( NodeDeleter nodeDeleter, AtUniverse *universe, AtNode *parentNode ) : m_nodeDeleter( nodeDeleter ), m_universe( universe ), m_parentNode( parentNode ) { } // Can be called concurrently with other get() calls. ArnoldShaderPtr get( const IECoreScene::ShaderNetwork *shader, const IECore::CompoundObject *attributes ) { IECore::MurmurHash h = shader->Object::hash(); IECore::MurmurHash hSubst; if( attributes ) { shader->hashSubstitutions( attributes, hSubst ); h.append( hSubst ); } Cache::const_accessor readAccessor; if( m_cache.find( readAccessor, h ) ) { return readAccessor->second; } Cache::accessor writeAccessor; if( m_cache.insert( writeAccessor, h ) ) { const std::string namePrefix = "shader:" + writeAccessor->first.toString(); if( hSubst != IECore::MurmurHash() ) { IECoreScene::ShaderNetworkPtr substitutedShader = shader->copy(); substitutedShader->applySubstitutions( attributes ); writeAccessor->second = new ArnoldShader( substitutedShader.get(), m_nodeDeleter, m_universe, namePrefix, m_parentNode ); } else { writeAccessor->second = new ArnoldShader( shader, m_nodeDeleter, m_universe, namePrefix, m_parentNode ); } } return writeAccessor->second; } // Must not be called concurrently with anything. void clearUnused() { vector<IECore::MurmurHash> toErase; for( Cache::iterator it = m_cache.begin(), eIt = m_cache.end(); it != eIt; ++it ) { if( it->second->refCount() == 1 ) { // Only one reference - this is ours, so // nothing outside of the cache is using the // shader. toErase.push_back( it->first ); } } for( vector<IECore::MurmurHash>::const_iterator it = toErase.begin(), eIt = toErase.end(); it != eIt; ++it ) { m_cache.erase( *it ); } } void nodesCreated( vector<AtNode *> &nodes ) const { for( Cache::const_iterator it = m_cache.begin(), eIt = m_cache.end(); it != eIt; ++it ) { it->second->nodesCreated( nodes ); } } private : NodeDeleter m_nodeDeleter; AtUniverse *m_universe; AtNode *m_parentNode; typedef tbb::concurrent_hash_map<IECore::MurmurHash, ArnoldShaderPtr> Cache; Cache m_cache; }; IE_CORE_DECLAREPTR( ShaderCache ) } // namespace ////////////////////////////////////////////////////////////////////////// // ArnoldAttributes ////////////////////////////////////////////////////////////////////////// namespace { // Forward declaration bool isConvertedProcedural( const AtNode *node ); IECore::InternedString g_surfaceShaderAttributeName( "surface" ); IECore::InternedString g_lightShaderAttributeName( "light" ); IECore::InternedString g_doubleSidedAttributeName( "doubleSided" ); IECore::InternedString g_setsAttributeName( "sets" ); IECore::InternedString g_oslSurfaceShaderAttributeName( "osl:surface" ); IECore::InternedString g_oslShaderAttributeName( "osl:shader" ); IECore::InternedString g_cameraVisibilityAttributeName( "ai:visibility:camera" ); IECore::InternedString g_shadowVisibilityAttributeName( "ai:visibility:shadow" ); IECore::InternedString g_shadowGroup( "ai:visibility:shadow_group" ); IECore::InternedString g_diffuseReflectVisibilityAttributeName( "ai:visibility:diffuse_reflect" ); IECore::InternedString g_specularReflectVisibilityAttributeName( "ai:visibility:specular_reflect" ); IECore::InternedString g_diffuseTransmitVisibilityAttributeName( "ai:visibility:diffuse_transmit" ); IECore::InternedString g_specularTransmitVisibilityAttributeName( "ai:visibility:specular_transmit" ); IECore::InternedString g_volumeVisibilityAttributeName( "ai:visibility:volume" ); IECore::InternedString g_subsurfaceVisibilityAttributeName( "ai:visibility:subsurface" ); IECore::InternedString g_cameraVisibilityAutoBumpAttributeName( "ai:autobump_visibility:camera" ); IECore::InternedString g_diffuseReflectVisibilityAutoBumpAttributeName( "ai:autobump_visibility:diffuse_reflect" ); IECore::InternedString g_specularReflectVisibilityAutoBumpAttributeName( "ai:autobump_visibility:specular_reflect" ); IECore::InternedString g_diffuseTransmitVisibilityAutoBumpAttributeName( "ai:autobump_visibility:diffuse_transmit" ); IECore::InternedString g_specularTransmitVisibilityAutoBumpAttributeName( "ai:autobump_visibility:specular_transmit" ); IECore::InternedString g_volumeVisibilityAutoBumpAttributeName( "ai:autobump_visibility:volume" ); IECore::InternedString g_subsurfaceVisibilityAutoBumpAttributeName( "ai:autobump_visibility:subsurface" ); IECore::InternedString g_arnoldSurfaceShaderAttributeName( "ai:surface" ); IECore::InternedString g_arnoldLightShaderAttributeName( "ai:light" ); IECore::InternedString g_arnoldFilterMapAttributeName( "ai:filtermap" ); IECore::InternedString g_arnoldUVRemapAttributeName( "ai:uv_remap" ); IECore::InternedString g_arnoldLightFilterShaderAttributeName( "ai:lightFilter:filter" ); IECore::InternedString g_arnoldReceiveShadowsAttributeName( "ai:receive_shadows" ); IECore::InternedString g_arnoldSelfShadowsAttributeName( "ai:self_shadows" ); IECore::InternedString g_arnoldOpaqueAttributeName( "ai:opaque" ); IECore::InternedString g_arnoldMatteAttributeName( "ai:matte" ); IECore::InternedString g_volumeStepSizeAttributeName( "ai:volume:step_size" ); IECore::InternedString g_volumeStepScaleAttributeName( "ai:volume:step_scale" ); IECore::InternedString g_shapeVolumeStepScaleAttributeName( "ai:shape:step_scale" ); IECore::InternedString g_shapeVolumeStepSizeAttributeName( "ai:shape:step_size" ); IECore::InternedString g_shapeVolumePaddingAttributeName( "ai:shape:volume_padding" ); IECore::InternedString g_volumeGridsAttributeName( "ai:volume:grids" ); IECore::InternedString g_velocityGridsAttributeName( "ai:volume:velocity_grids" ); IECore::InternedString g_velocityScaleAttributeName( "ai:volume:velocity_scale" ); IECore::InternedString g_velocityFPSAttributeName( "ai:volume:velocity_fps" ); IECore::InternedString g_velocityOutlierThresholdAttributeName( "ai:volume:velocity_outlier_threshold" ); IECore::InternedString g_transformTypeAttributeName( "ai:transform_type" ); IECore::InternedString g_polyMeshSubdivIterationsAttributeName( "ai:polymesh:subdiv_iterations" ); IECore::InternedString g_polyMeshSubdivAdaptiveErrorAttributeName( "ai:polymesh:subdiv_adaptive_error" ); IECore::InternedString g_polyMeshSubdivAdaptiveMetricAttributeName( "ai:polymesh:subdiv_adaptive_metric" ); IECore::InternedString g_polyMeshSubdivAdaptiveSpaceAttributeName( "ai:polymesh:subdiv_adaptive_space" ); IECore::InternedString g_polyMeshSubdivSmoothDerivsAttributeName( "ai:polymesh:subdiv_smooth_derivs" ); IECore::InternedString g_polyMeshSubdivFrustumIgnoreAttributeName( "ai:polymesh:subdiv_frustum_ignore" ); IECore::InternedString g_polyMeshSubdividePolygonsAttributeName( "ai:polymesh:subdivide_polygons" ); IECore::InternedString g_polyMeshSubdivUVSmoothingAttributeName( "ai:polymesh:subdiv_uv_smoothing" ); IECore::InternedString g_dispMapAttributeName( "ai:disp_map" ); IECore::InternedString g_dispHeightAttributeName( "ai:disp_height" ); IECore::InternedString g_dispPaddingAttributeName( "ai:disp_padding" ); IECore::InternedString g_dispZeroValueAttributeName( "ai:disp_zero_value" ); IECore::InternedString g_dispAutoBumpAttributeName( "ai:disp_autobump" ); IECore::InternedString g_curvesMinPixelWidthAttributeName( "ai:curves:min_pixel_width" ); IECore::InternedString g_curvesModeAttributeName( "ai:curves:mode" ); IECore::InternedString g_sssSetNameName( "ai:sss_setname" ); IECore::InternedString g_toonIdName( "ai:toon_id" ); IECore::InternedString g_lightFilterPrefix( "ai:lightFilter:" ); IECore::InternedString g_filteredLights( "filteredLights" ); const char *customAttributeName( const std::string &attributeName, bool *hasPrecedence = nullptr ) { if( boost::starts_with( attributeName, "user:" ) ) { if( hasPrecedence ) { *hasPrecedence = false; } return attributeName.c_str(); } else if( boost::starts_with( attributeName, "render:" ) ) { if( hasPrecedence ) { *hasPrecedence = true; } return attributeName.c_str() + 7; } // Not a custom attribute return nullptr; } class ArnoldAttributes : public IECoreScenePreview::Renderer::AttributesInterface { public : ArnoldAttributes( const IECore::CompoundObject *attributes, ShaderCache *shaderCache ) : m_visibility( AI_RAY_ALL ), m_sidedness( AI_RAY_ALL ), m_shadingFlags( Default ), m_stepSize( 0.0f ), m_stepScale( 1.0f ), m_volumePadding( 0.0f ), m_polyMesh( attributes ), m_displacement( attributes, shaderCache ), m_curves( attributes ), m_volume( attributes ), m_allAttributes( attributes ) { updateVisibility( m_visibility, g_cameraVisibilityAttributeName, AI_RAY_CAMERA, attributes ); updateVisibility( m_visibility, g_shadowVisibilityAttributeName, AI_RAY_SHADOW, attributes ); updateVisibility( m_visibility, g_diffuseReflectVisibilityAttributeName, AI_RAY_DIFFUSE_REFLECT, attributes ); updateVisibility( m_visibility, g_specularReflectVisibilityAttributeName, AI_RAY_SPECULAR_REFLECT, attributes ); updateVisibility( m_visibility, g_diffuseTransmitVisibilityAttributeName, AI_RAY_DIFFUSE_TRANSMIT, attributes ); updateVisibility( m_visibility, g_specularTransmitVisibilityAttributeName, AI_RAY_SPECULAR_TRANSMIT, attributes ); updateVisibility( m_visibility, g_volumeVisibilityAttributeName, AI_RAY_VOLUME, attributes ); updateVisibility( m_visibility, g_subsurfaceVisibilityAttributeName, AI_RAY_SUBSURFACE, attributes ); if( const IECore::BoolData *d = attribute<IECore::BoolData>( g_doubleSidedAttributeName, attributes ) ) { m_sidedness = d->readable() ? AI_RAY_ALL : AI_RAY_UNDEFINED; } updateShadingFlag( g_arnoldReceiveShadowsAttributeName, ReceiveShadows, attributes ); updateShadingFlag( g_arnoldSelfShadowsAttributeName, SelfShadows, attributes ); updateShadingFlag( g_arnoldOpaqueAttributeName, Opaque, attributes ); updateShadingFlag( g_arnoldMatteAttributeName, Matte, attributes ); const IECoreScene::ShaderNetwork *surfaceShaderAttribute = attribute<IECoreScene::ShaderNetwork>( g_arnoldSurfaceShaderAttributeName, attributes ); surfaceShaderAttribute = surfaceShaderAttribute ? surfaceShaderAttribute : attribute<IECoreScene::ShaderNetwork>( g_oslSurfaceShaderAttributeName, attributes ); /// \todo Remove support for interpreting "osl:shader" as a surface shader assignment. surfaceShaderAttribute = surfaceShaderAttribute ? surfaceShaderAttribute : attribute<IECoreScene::ShaderNetwork>( g_oslShaderAttributeName, attributes ); surfaceShaderAttribute = surfaceShaderAttribute ? surfaceShaderAttribute : attribute<IECoreScene::ShaderNetwork>( g_surfaceShaderAttributeName, attributes ); if( surfaceShaderAttribute ) { m_surfaceShader = shaderCache->get( surfaceShaderAttribute, attributes ); } if( auto filterMapAttribute = attribute<IECoreScene::ShaderNetwork>( g_arnoldFilterMapAttributeName, attributes ) ) { m_filterMap = shaderCache->get( filterMapAttribute, attributes ); } if( auto uvRemapAttribute = attribute<IECoreScene::ShaderNetwork>( g_arnoldUVRemapAttributeName, attributes ) ) { m_uvRemap = shaderCache->get( uvRemapAttribute, attributes ); } m_lightShader = attribute<IECoreScene::ShaderNetwork>( g_arnoldLightShaderAttributeName, attributes ); m_lightShader = m_lightShader ? m_lightShader : attribute<IECoreScene::ShaderNetwork>( g_lightShaderAttributeName, attributes ); substituteShaderIfNecessary( m_lightShader, attributes ); m_lightFilterShader = attribute<IECoreScene::ShaderNetwork>( g_arnoldLightFilterShaderAttributeName, attributes ); substituteShaderIfNecessary( m_lightFilterShader, attributes ); m_traceSets = attribute<IECore::InternedStringVectorData>( g_setsAttributeName, attributes ); m_transformType = attribute<IECore::StringData>( g_transformTypeAttributeName, attributes ); m_stepSize = attributeValue<float>( g_shapeVolumeStepSizeAttributeName, attributes, 0.0f ); m_stepScale = attributeValue<float>( g_shapeVolumeStepScaleAttributeName, attributes, 1.0f ); m_volumePadding = attributeValue<float>( g_shapeVolumePaddingAttributeName, attributes, 0.0f ); m_sssSetName = attribute<IECore::StringData>( g_sssSetNameName, attributes ); m_toonId = attribute<IECore::StringData>( g_toonIdName, attributes ); for( IECore::CompoundObject::ObjectMap::const_iterator it = attributes->members().begin(), eIt = attributes->members().end(); it != eIt; ++it ) { bool hasPrecedence; if( const char *name = customAttributeName( it->first.string(), &hasPrecedence ) ) { if( const IECore::Data *data = IECore::runTimeCast<const IECore::Data>( it->second.get() ) ) { auto inserted = m_custom.insert( CustomAttributes::value_type( name, nullptr ) ); if( hasPrecedence || inserted.second ) { inserted.first->second = data; } } } if( it->first.string() == g_arnoldLightFilterShaderAttributeName ) { continue; } else if( boost::starts_with( it->first.string(), g_lightFilterPrefix.string() ) ) { ArnoldShaderPtr filter = shaderCache->get( IECore::runTimeCast<const IECoreScene::ShaderNetwork>( it->second.get() ), attributes ); m_lightFilterShaders.push_back( filter ); } } } // Some attributes affect the geometric properties of a node, which means they // go on the shape rather than the ginstance. These are problematic because they // must be taken into account when determining the hash for instancing, and // because they cannot be edited interactively. This method applies those // attributes, and is called from InstanceCache during geometry conversion. void applyGeometry( const IECore::Object *object, AtNode *node ) const { if( const IECoreScene::MeshPrimitive *mesh = IECore::runTimeCast<const IECoreScene::MeshPrimitive>( object ) ) { m_polyMesh.apply( mesh, node ); m_displacement.apply( node ); } else if( IECore::runTimeCast<const IECoreScene::CurvesPrimitive>( object ) ) { m_curves.apply( node ); } else if( IECore::runTimeCast<const IECoreVDB::VDBObject>( object ) ) { m_volume.apply( node ); } else if( const IECoreScene::ExternalProcedural *procedural = IECore::runTimeCast<const IECoreScene::ExternalProcedural>( object ) ) { if( procedural->getFileName() == "volume" ) { m_volume.apply( node ); } } float actualStepSize = m_stepSize * m_stepScale; if( actualStepSize != 0.0f && AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), g_stepSizeArnoldString ) ) { // Only apply step_size if it hasn't already been set to a non-zero // value by the geometry converter. This allows procedurals to carry // their step size as a parameter and have it trump the attribute value. // This is important for Gaffer nodes like ArnoldVDB, which carefully // calculate the correct step size and provide it via a parameter. if( AiNodeGetFlt( node, g_stepSizeArnoldString ) == 0.0f ) { AiNodeSetFlt( node, g_stepSizeArnoldString, actualStepSize ); } } if( m_volumePadding != 0.0f && AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), g_volumePaddingArnoldString ) ) { AiNodeSetFlt( node, g_volumePaddingArnoldString, m_volumePadding ); } } // Generates a signature for the work done by applyGeometry. void hashGeometry( const IECore::Object *object, IECore::MurmurHash &h ) const { const IECore::TypeId objectType = object->typeId(); bool meshInterpolationIsLinear = false; bool proceduralIsVolumetric = false; if( objectType == IECoreScene::MeshPrimitive::staticTypeId() ) { meshInterpolationIsLinear = static_cast<const IECoreScene::MeshPrimitive *>( object )->interpolation() == "linear"; } else if( objectType == IECoreScene::ExternalProcedural::staticTypeId() ) { const IECoreScene::ExternalProcedural *procedural = static_cast<const IECoreScene::ExternalProcedural *>( object ); if( procedural->getFileName() == "volume" ) { proceduralIsVolumetric = true; } } hashGeometryInternal( objectType, meshInterpolationIsLinear, proceduralIsVolumetric, h ); } // Returns true if the given geometry can be instanced, given the attributes that // will be applied in `applyGeometry()`. bool canInstanceGeometry( const IECore::Object *object ) const { if( !IECore::runTimeCast<const IECoreScene::VisibleRenderable>( object ) ) { return false; } if( const IECoreScene::MeshPrimitive *mesh = IECore::runTimeCast<const IECoreScene::MeshPrimitive>( object ) ) { if( mesh->interpolation() == "linear" ) { return true; } else { // We shouldn't instance poly meshes with view dependent subdivision, because the subdivision // for the master mesh might be totally inappropriate for the position of the ginstances in frame. return m_polyMesh.subdivAdaptiveError == 0.0f || m_polyMesh.subdivAdaptiveSpace == g_objectArnoldString; } } else if( IECore::runTimeCast<const IECoreScene::CurvesPrimitive>( object ) ) { // Min pixel width is a screen-space metric, and hence not compatible with instancing. return m_curves.minPixelWidth == 0.0f; } else if( const IECoreScene::ExternalProcedural *procedural = IECore::runTimeCast<const IECoreScene::ExternalProcedural>( object ) ) { // We don't instance "ass archive" procedurals, because Arnold // does automatic instancing of those itself, using its procedural // cache. return ( !boost::ends_with( procedural->getFileName(), ".ass" ) && !boost::ends_with( procedural->getFileName(), ".ass.gz" ) ); } return true; } // Most attributes (visibility, surface shader etc) are orthogonal to the // type of object to which they are applied. These are the good kind, because // they can be applied to ginstance nodes, making attribute edits easy. This // method applies those attributes, and is called from `Renderer::object()` // and `Renderer::attributes()`. // // The previousAttributes are passed so that we can check that the new // geometry attributes are compatible with those which were applied previously // (and which cannot be changed now). Returns true if all is well and false // if there is a clash (and the edit has therefore failed). bool apply( AtNode *node, const ArnoldAttributes *previousAttributes ) const { // Check that we're not looking at an impossible request // to edit geometric attributes. const AtNode *geometry = node; if( AiNodeIs( node, g_ginstanceArnoldString ) ) { geometry = static_cast<const AtNode *>( AiNodeGetPtr( node, g_nodeArnoldString ) ); } if( previousAttributes ) { IECore::TypeId objectType = IECore::InvalidTypeId; bool meshInterpolationIsLinear = false; bool proceduralIsVolumetric = false; if( AiNodeIs( geometry, g_polymeshArnoldString ) ) { objectType = IECoreScene::MeshPrimitive::staticTypeId(); meshInterpolationIsLinear = AiNodeGetStr( geometry, g_subdivTypeArnoldString ) != g_catclarkArnoldString; } else if( AiNodeIs( geometry, g_curvesArnoldString ) ) { objectType = IECoreScene::CurvesPrimitive::staticTypeId(); } else if( AiNodeIs( geometry, g_boxArnoldString ) ) { objectType = IECoreScene::MeshPrimitive::staticTypeId(); } else if( AiNodeIs( geometry, g_volumeArnoldString ) ) { objectType = IECoreScene::ExternalProcedural::staticTypeId(); proceduralIsVolumetric = true; } else if( AiNodeIs( geometry, g_sphereArnoldString ) ) { objectType = IECoreScene::SpherePrimitive::staticTypeId(); } else if( isConvertedProcedural( geometry ) ) { objectType = IECoreScenePreview::Procedural::staticTypeId(); } IECore::MurmurHash previousGeometryHash; previousAttributes->hashGeometryInternal( objectType, meshInterpolationIsLinear, proceduralIsVolumetric, previousGeometryHash ); IECore::MurmurHash currentGeometryHash; hashGeometryInternal( objectType, meshInterpolationIsLinear, proceduralIsVolumetric, currentGeometryHash ); if( previousGeometryHash != currentGeometryHash ) { return false; } } // Remove old custom parameters. const AtNodeEntry *nodeEntry = AiNodeGetNodeEntry( node ); if( previousAttributes ) { for( const auto &attr : previousAttributes->m_custom ) { if( AiNodeEntryLookUpParameter( nodeEntry, attr.first ) ) { // Be careful not to reset a parameter we wouldn't // have set in the first place. continue; } AiNodeResetParameter( node, attr.first ); } } // Add new custom parameters. for( const auto &attr : m_custom ) { if( AiNodeEntryLookUpParameter( nodeEntry, attr.first ) ) { IECore::msg( IECore::Msg::Warning, "Renderer::attributes", boost::format( "Custom attribute \"%s\" will be ignored because it clashes with Arnold's built-in parameters" ) % attr.first.c_str() ); continue; } ParameterAlgo::setParameter( node, attr.first, attr.second.get() ); } // Early out for IECoreScene::Procedurals. Arnold's inheritance rules for procedurals are back // to front, with any explicitly set parameters on the procedural node overriding parameters of child // nodes completely. We emulate the inheritance we want in ArnoldProceduralRenderer. if( isConvertedProcedural( geometry ) ) { // Arnold neither inherits nor overrides visibility parameters. Instead // it does a bitwise `&` between the procedural and its children. The // `procedural` node itself will have `visibility == 0` applied by the // `Instance` constructor, so it can be instanced without the original // being seen. Override that by applying full visibility to the `ginstance` // so that the children of the procedural have full control of their final // visibility. AiNodeSetByte( node, g_visibilityArnoldString, AI_RAY_ALL ); return true; } // Add shape specific parameters. if( AiNodeEntryGetType( AiNodeGetNodeEntry( node ) ) == AI_NODE_SHAPE ) { AiNodeSetByte( node, g_visibilityArnoldString, m_visibility ); AiNodeSetByte( node, g_sidednessArnoldString, m_sidedness ); if( m_transformType ) { // \todo : Arnold quite explicitly discourages constructing AtStrings repeatedly, // but given the need to pass m_transformType around as a string for consistency // reasons, it seems like there's not much else we can do here. // If we start reusing ArnoldAttributes for multiple locations with identical attributes, // it could be worth caching this, or possibly in the future we could come up with // some way of cleanly exposing enum values as something other than strings. AiNodeSetStr( node, g_transformTypeArnoldString, AtString( m_transformType->readable().c_str() ) ); } AiNodeSetBool( node, g_receiveShadowsArnoldString, m_shadingFlags & ArnoldAttributes::ReceiveShadows ); AiNodeSetBool( node, g_selfShadowsArnoldString, m_shadingFlags & ArnoldAttributes::SelfShadows ); AiNodeSetBool( node, g_opaqueArnoldString, m_shadingFlags & ArnoldAttributes::Opaque ); AiNodeSetBool( node, g_matteArnoldString, m_shadingFlags & ArnoldAttributes::Matte ); if( m_surfaceShader && m_surfaceShader->root() ) { AiNodeSetPtr( node, g_shaderArnoldString, m_surfaceShader->root() ); } else { AiNodeResetParameter( node, g_shaderArnoldString ); } if( m_traceSets && m_traceSets->readable().size() ) { const vector<IECore::InternedString> &v = m_traceSets->readable(); AtArray *array = AiArrayAllocate( v.size(), 1, AI_TYPE_STRING ); for( size_t i = 0, e = v.size(); i < e; ++i ) { AiArraySetStr( array, i, v[i].c_str() ); } AiNodeSetArray( node, g_traceSetsArnoldString, array ); } else { // Arnold very unhelpfully treats `trace_sets == []` as meaning the object // is in every trace set. So we instead make `trace_sets == [ "__none__" ]` // to get the behaviour people expect. AiNodeSetArray( node, g_traceSetsArnoldString, AiArray( 1, 1, AI_TYPE_STRING, "__none__" ) ); } if( m_sssSetName ) { ParameterAlgo::setParameter( node, g_sssSetNameArnoldString, m_sssSetName.get() ); } else { AiNodeResetParameter( node, g_sssSetNameArnoldString ); } if( m_toonId ) { ParameterAlgo::setParameter( node, g_toonIdArnoldString, m_toonId.get() ); } else { AiNodeResetParameter( node, g_toonIdArnoldString ); } } // Add camera specific parameters. if( AiNodeEntryGetType( AiNodeGetNodeEntry( node ) ) == AI_NODE_CAMERA ) { if( AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), g_filterMapArnoldString ) ) { if( m_filterMap && m_filterMap->root() ) { AiNodeSetPtr( node, g_filterMapArnoldString, m_filterMap->root() ); } else { AiNodeResetParameter( node, g_filterMapArnoldString ); } } if( AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), g_uvRemapArnoldString ) ) { if( m_uvRemap && m_uvRemap->root() ) { AiNodeLinkOutput( m_uvRemap->root(), "", node, g_uvRemapArnoldString ); } else { AiNodeResetParameter( node, g_uvRemapArnoldString ); } } } return true; } const IECoreScene::ShaderNetwork *lightShader() const { return m_lightShader.get(); } /// Return the shader assigned to a world space light filter const IECoreScene::ShaderNetwork *lightFilterShader() const { return m_lightFilterShader.get(); } /// Return the shaders for filters directly assigned to a light const std::vector<ArnoldShaderPtr>& lightFilterShaders() const { return m_lightFilterShaders; } const IECore::CompoundObject *allAttributes() const { return m_allAttributes.get(); } private : struct PolyMesh { PolyMesh( const IECore::CompoundObject *attributes ) { subdivIterations = attributeValue<int>( g_polyMeshSubdivIterationsAttributeName, attributes, 1 ); subdivAdaptiveError = attributeValue<float>( g_polyMeshSubdivAdaptiveErrorAttributeName, attributes, 0.0f ); const IECore::StringData *subdivAdaptiveMetricData = attribute<IECore::StringData>( g_polyMeshSubdivAdaptiveMetricAttributeName, attributes ); if( subdivAdaptiveMetricData ) { subdivAdaptiveMetric = AtString( subdivAdaptiveMetricData->readable().c_str() ); } else { subdivAdaptiveMetric = g_autoArnoldString; } const IECore::StringData *subdivAdaptiveSpaceData = attribute<IECore::StringData>( g_polyMeshSubdivAdaptiveSpaceAttributeName, attributes ); if( subdivAdaptiveSpaceData ) { subdivAdaptiveSpace = AtString( subdivAdaptiveSpaceData->readable().c_str() ); } else { subdivAdaptiveSpace = g_rasterArnoldString; } if( auto a = attribute<IECore::StringData>( g_polyMeshSubdivUVSmoothingAttributeName, attributes ) ) { subdivUVSmoothing = AtString( a->readable().c_str() ); } else { subdivUVSmoothing = g_pinCornersArnoldString; } subdividePolygons = attributeValue<bool>( g_polyMeshSubdividePolygonsAttributeName, attributes, false ); subdivSmoothDerivs = attributeValue<bool>( g_polyMeshSubdivSmoothDerivsAttributeName, attributes, false ); subdivFrustumIgnore = attributeValue<bool>( g_polyMeshSubdivFrustumIgnoreAttributeName, attributes, false ); } int subdivIterations; float subdivAdaptiveError; AtString subdivAdaptiveMetric; AtString subdivAdaptiveSpace; AtString subdivUVSmoothing; bool subdividePolygons; bool subdivSmoothDerivs; bool subdivFrustumIgnore; void hash( bool meshInterpolationIsLinear, IECore::MurmurHash &h ) const { if( !meshInterpolationIsLinear || subdividePolygons ) { h.append( subdivIterations ); h.append( subdivAdaptiveError ); h.append( subdivAdaptiveMetric.c_str() ); h.append( subdivAdaptiveSpace.c_str() ); h.append( subdivUVSmoothing.c_str() ); h.append( subdivSmoothDerivs ); h.append( subdivFrustumIgnore ); } } void apply( const IECoreScene::MeshPrimitive *mesh, AtNode *node ) const { if( mesh->interpolation() != "linear" || subdividePolygons ) { AiNodeSetByte( node, g_subdivIterationsArnoldString, subdivIterations ); AiNodeSetFlt( node, g_subdivAdaptiveErrorArnoldString, subdivAdaptiveError ); AiNodeSetStr( node, g_subdivAdaptiveMetricArnoldString, subdivAdaptiveMetric ); AiNodeSetStr( node, g_subdivAdaptiveSpaceArnoldString, subdivAdaptiveSpace ); AiNodeSetStr( node, g_subdivUVSmoothingArnoldString, subdivUVSmoothing ); AiNodeSetBool( node, g_subdivSmoothDerivsArnoldString, subdivSmoothDerivs ); AiNodeSetBool( node, g_subdivFrustumIgnoreArnoldString, subdivFrustumIgnore ); if( mesh->interpolation() == "linear" ) { AiNodeSetStr( node, g_subdivTypeArnoldString, g_linearArnoldString ); } } } }; struct Displacement { Displacement( const IECore::CompoundObject *attributes, ShaderCache *shaderCache ) { if( const IECoreScene::ShaderNetwork *mapAttribute = attribute<IECoreScene::ShaderNetwork>( g_dispMapAttributeName, attributes ) ) { map = shaderCache->get( mapAttribute, attributes ); } height = attributeValue<float>( g_dispHeightAttributeName, attributes, 1.0f ); padding = attributeValue<float>( g_dispPaddingAttributeName, attributes, 0.0f ); zeroValue = attributeValue<float>( g_dispZeroValueAttributeName, attributes, 0.0f ); autoBump = attributeValue<bool>( g_dispAutoBumpAttributeName, attributes, false ); autoBumpVisibility = AI_RAY_CAMERA; updateVisibility( autoBumpVisibility, g_cameraVisibilityAutoBumpAttributeName, AI_RAY_CAMERA, attributes ); updateVisibility( autoBumpVisibility, g_diffuseReflectVisibilityAutoBumpAttributeName, AI_RAY_DIFFUSE_REFLECT, attributes ); updateVisibility( autoBumpVisibility, g_specularReflectVisibilityAutoBumpAttributeName, AI_RAY_SPECULAR_REFLECT, attributes ); updateVisibility( autoBumpVisibility, g_diffuseTransmitVisibilityAutoBumpAttributeName, AI_RAY_DIFFUSE_TRANSMIT, attributes ); updateVisibility( autoBumpVisibility, g_specularTransmitVisibilityAutoBumpAttributeName, AI_RAY_SPECULAR_TRANSMIT, attributes ); updateVisibility( autoBumpVisibility, g_volumeVisibilityAutoBumpAttributeName, AI_RAY_VOLUME, attributes ); updateVisibility( autoBumpVisibility, g_subsurfaceVisibilityAutoBumpAttributeName, AI_RAY_SUBSURFACE, attributes ); } ArnoldShaderPtr map; float height; float padding; float zeroValue; bool autoBump; unsigned char autoBumpVisibility; void hash( IECore::MurmurHash &h ) const { if( map && map->root() ) { h.append( AiNodeGetName( map->root() ) ); } h.append( height ); h.append( padding ); h.append( zeroValue ); h.append( autoBump ); h.append( autoBumpVisibility ); } void apply( AtNode *node ) const { if( map && map->root() ) { AiNodeSetPtr( node, g_dispMapArnoldString, map->root() ); } else { AiNodeResetParameter( node, g_dispMapArnoldString ); } AiNodeSetFlt( node, g_dispHeightArnoldString, height ); AiNodeSetFlt( node, g_dispPaddingArnoldString, padding ); AiNodeSetFlt( node, g_dispZeroValueArnoldString, zeroValue ); AiNodeSetBool( node, g_dispAutoBumpArnoldString, autoBump ); AiNodeSetByte( node, g_autobumpVisibilityArnoldString, autoBumpVisibility ); } }; struct Curves { Curves( const IECore::CompoundObject *attributes ) { minPixelWidth = attributeValue<float>( g_curvesMinPixelWidthAttributeName, attributes, 0.0f ); // Arnold actually has three modes - "ribbon", "oriented" and "thick". // The Cortex convention (inherited from RenderMan) is that curves without // normals ("N" primitive variable) are rendered as camera facing ribbons, // and those with normals are rendered as ribbons oriented by "N". // IECoreArnold::CurvesAlgo takes care of this part for us automatically, so all that // remains for us to do is to override the mode to "thick" if necessary to // expose Arnold's remaining functionality. // // The semantics for our "ai:curves:mode" attribute are therefore as follows : // // "ribbon" : Automatically choose `mode = "ribbon"` or `mode = "oriented"` // according to the existence of "N". // "thick" : Render with `mode = "thick"`. thick = attributeValue<string>( g_curvesModeAttributeName, attributes, "ribbon" ) == "thick"; } float minPixelWidth; bool thick; void hash( IECore::MurmurHash &h ) const { h.append( minPixelWidth ); h.append( thick ); } void apply( AtNode *node ) const { AiNodeSetFlt( node, g_minPixelWidthArnoldString, minPixelWidth ); if( thick ) { AiNodeSetStr( node, g_modeArnoldString, g_thickArnoldString ); } } }; struct Volume { Volume( const IECore::CompoundObject *attributes ) { volumeGrids = attribute<IECore::StringVectorData>( g_volumeGridsAttributeName, attributes ); velocityGrids = attribute<IECore::StringVectorData>( g_velocityGridsAttributeName, attributes ); velocityScale = optionalAttribute<float>( g_velocityScaleAttributeName, attributes ); velocityFPS = optionalAttribute<float>( g_velocityFPSAttributeName, attributes ); velocityOutlierThreshold = optionalAttribute<float>( g_velocityOutlierThresholdAttributeName, attributes ); stepSize = optionalAttribute<float> ( g_volumeStepSizeAttributeName, attributes ); stepScale = optionalAttribute<float>( g_volumeStepScaleAttributeName, attributes ); } IECore::ConstStringVectorDataPtr volumeGrids; IECore::ConstStringVectorDataPtr velocityGrids; boost::optional<float> velocityScale; boost::optional<float> velocityFPS; boost::optional<float> velocityOutlierThreshold; boost::optional<float> stepSize; boost::optional<float> stepScale; void hash( IECore::MurmurHash &h ) const { if( volumeGrids ) { volumeGrids->hash( h ); } if( velocityGrids ) { velocityGrids->hash( h ); } h.append( velocityScale.get_value_or( 1.0f ) ); h.append( velocityFPS.get_value_or( 24.0f ) ); h.append( velocityOutlierThreshold.get_value_or( 0.001f ) ); h.append( stepSize.get_value_or( 0.0f ) ); h.append( stepScale.get_value_or( 1.0f ) ); } void apply( AtNode *node ) const { if( volumeGrids && volumeGrids->readable().size() ) { AtArray *array = ParameterAlgo::dataToArray( volumeGrids.get(), AI_TYPE_STRING ); AiNodeSetArray( node, g_volumeGridsArnoldString, array ); } if( velocityGrids && velocityGrids->readable().size() ) { AtArray *array = ParameterAlgo::dataToArray( velocityGrids.get(), AI_TYPE_STRING ); AiNodeSetArray( node, g_velocityGridsArnoldString, array ); } if( !velocityScale || velocityScale.get() > 0 ) { AtNode *options = AiUniverseGetOptions( AiNodeGetUniverse( node ) ); const AtNode *arnoldCamera = static_cast<const AtNode *>( AiNodeGetPtr( options, g_cameraArnoldString ) ); if( arnoldCamera ) { float shutterStart = AiNodeGetFlt( arnoldCamera, g_shutterStartArnoldString ); float shutterEnd = AiNodeGetFlt( arnoldCamera, g_shutterEndArnoldString ); // We're getting very lucky here: // - Arnold has automatically set options.camera the first time we made a camera // - All cameras output by Gaffer at present will have the same shutter, // so it doesn't matter if we get it from the final render camera or not. AiNodeSetFlt( node, g_motionStartArnoldString, shutterStart ); AiNodeSetFlt( node, g_motionEndArnoldString, shutterEnd ); } } if( velocityScale ) { AiNodeSetFlt( node, g_velocityScaleArnoldString, velocityScale.get() ); } if( velocityFPS ) { AiNodeSetFlt( node, g_velocityFPSArnoldString, velocityFPS.get() ); } if( velocityOutlierThreshold ) { AiNodeSetFlt( node, g_velocityOutlierThresholdArnoldString, velocityOutlierThreshold.get() ); } if ( stepSize ) { AiNodeSetFlt( node, g_stepSizeArnoldString, stepSize.get() * stepScale.get_value_or( 1.0f ) ); } else if ( stepScale ) { AiNodeSetFlt( node, g_stepScaleArnoldString, stepScale.get() ); } } }; enum ShadingFlags { ReceiveShadows = 1, SelfShadows = 2, Opaque = 4, Matte = 8, Default = ReceiveShadows | SelfShadows | Opaque, All = ReceiveShadows | SelfShadows | Opaque | Matte }; template<typename T> static const T *attribute( const IECore::InternedString &name, const IECore::CompoundObject *attributes ) { IECore::CompoundObject::ObjectMap::const_iterator it = attributes->members().find( name ); if( it == attributes->members().end() ) { return nullptr; } return reportedCast<const T>( it->second.get(), "attribute", name ); } template<typename T> static T attributeValue( const IECore::InternedString &name, const IECore::CompoundObject *attributes, const T &defaultValue ) { typedef IECore::TypedData<T> DataType; const DataType *data = attribute<DataType>( name, attributes ); return data ? data->readable() : defaultValue; } template<typename T> static boost::optional<T> optionalAttribute( const IECore::InternedString &name, const IECore::CompoundObject *attributes ) { typedef IECore::TypedData<T> DataType; const DataType *data = attribute<DataType>( name, attributes ); return data ? data->readable() : boost::optional<T>(); } static void updateVisibility( unsigned char &visibility, const IECore::InternedString &name, unsigned char rayType, const IECore::CompoundObject *attributes ) { if( const IECore::BoolData *d = attribute<IECore::BoolData>( name, attributes ) ) { if( d->readable() ) { visibility |= rayType; } else { visibility = visibility & ~rayType; } } } void updateShadingFlag( const IECore::InternedString &name, unsigned char flag, const IECore::CompoundObject *attributes ) { if( const IECore::BoolData *d = attribute<IECore::BoolData>( name, attributes ) ) { if( d->readable() ) { m_shadingFlags |= flag; } else { m_shadingFlags = m_shadingFlags & ~flag; } } } void hashGeometryInternal( IECore::TypeId objectType, bool meshInterpolationIsLinear, bool proceduralIsVolumetric, IECore::MurmurHash &h ) const { switch( (int)objectType ) { case IECoreScene::MeshPrimitiveTypeId : m_polyMesh.hash( meshInterpolationIsLinear, h ); m_displacement.hash( h ); h.append( m_stepSize ); h.append( m_stepScale ); h.append( m_volumePadding ); break; case IECoreScene::CurvesPrimitiveTypeId : m_curves.hash( h ); break; case IECoreScene::SpherePrimitiveTypeId : h.append( m_stepSize ); h.append( m_stepScale ); h.append( m_volumePadding ); break; case IECoreScene::ExternalProceduralTypeId : if( proceduralIsVolumetric ) { h.append( m_stepSize ); h.append( m_stepScale ); h.append( m_volumePadding ); m_volume.hash( h ); } break; case IECoreVDB::VDBObjectTypeId : h.append( m_volumePadding ); m_volume.hash( h ); break; default : if( objectType == (IECore::TypeId)GafferScene::PreviewProceduralTypeId || IECore::RunTimeTyped::inheritsFrom( objectType, (IECore::TypeId)GafferScene::PreviewProceduralTypeId ) ) { hashProceduralGeometry( h ); } // No geometry attributes for this type. break; } } template<typename T> void hashOptional( const T *t, IECore::MurmurHash &h ) const { if( t ) { t->hash( h ); } else { h.append( 0 ); } } void hashProceduralGeometry( IECore::MurmurHash &h ) const { // Everything except custom attributes affects procedurals, // because we have to manually inherit attributes by // applying them to the child nodes of the procedural. h.append( m_visibility ); h.append( m_sidedness ); h.append( m_shadingFlags ); hashOptional( m_surfaceShader.get(), h ); hashOptional( m_filterMap.get(), h ); hashOptional( m_uvRemap.get(), h ); hashOptional( m_lightShader.get(), h ); hashOptional( m_lightFilterShader.get(), h ); for( const auto &s : m_lightFilterShaders ) { s->hash( h ); } hashOptional( m_traceSets.get(), h ); hashOptional( m_transformType.get(), h ); h.append( m_stepSize ); h.append( m_stepScale ); h.append( m_volumePadding ); m_polyMesh.hash( true, h ); m_polyMesh.hash( false, h ); m_displacement.hash( h ); m_curves.hash( h ); m_volume.hash( h ); hashOptional( m_toonId.get(), h ); hashOptional( m_sssSetName.get(), h ); } unsigned char m_visibility; unsigned char m_sidedness; unsigned char m_shadingFlags; ArnoldShaderPtr m_surfaceShader; ArnoldShaderPtr m_filterMap; ArnoldShaderPtr m_uvRemap; IECoreScene::ConstShaderNetworkPtr m_lightShader; IECoreScene::ConstShaderNetworkPtr m_lightFilterShader; std::vector<ArnoldShaderPtr> m_lightFilterShaders; IECore::ConstInternedStringVectorDataPtr m_traceSets; IECore::ConstStringDataPtr m_transformType; float m_stepSize; float m_stepScale; float m_volumePadding; PolyMesh m_polyMesh; Displacement m_displacement; Curves m_curves; Volume m_volume; IECore::ConstStringDataPtr m_toonId; IECore::ConstStringDataPtr m_sssSetName; // When adding fields, please update `hashProceduralGeometry()`! // AtString defines implicit cast to a (uniquefied) `const char *`, // and that is sufficient for the default `std::less<AtString>` // comparison. using CustomAttributes = boost::container::flat_map<AtString, IECore::ConstDataPtr>; CustomAttributes m_custom; // The original attributes we were contructed from. We stash // these so that they can be inherited manually when expanding // procedurals. /// \todo Instead of storing this, can be instead copy/update /// the fields above directly when emulating inheritance? We are /// avoiding that for now because it would mean child nodes of the /// procedural referencing shaders etc generated outside of the /// procedural. We saw crashes in Arnold when attempting that in the /// past, but have been told by the developers since that it should /// be supported. IECore::ConstCompoundObjectPtr m_allAttributes; }; IE_CORE_DECLAREPTR( ArnoldAttributes ) } // namespace ////////////////////////////////////////////////////////////////////////// // InstanceCache ////////////////////////////////////////////////////////////////////////// namespace { class Instance { public : AtNode *node() { return m_ginstance.get() ? m_ginstance.get() : m_node.get(); } void nodesCreated( vector<AtNode *> &nodes ) const { if( m_ginstance ) { nodes.push_back( m_ginstance.get() ); } else { // Technically the node was created in `InstanceCache.get()` // rather than by us directly, but we are the sole owner and // this is the most natural place to report the creation. nodes.push_back( m_node.get() ); } } private : // Constructors are private as they are only intended for use in // `InstanceCache::get()`. See comment in `nodesCreated()`. friend class InstanceCache; // Non-instanced Instance( const SharedAtNodePtr &node ) : m_node( node ) { } // Instanced Instance( const SharedAtNodePtr &node, NodeDeleter nodeDeleter, AtUniverse *universe, const std::string &instanceName, const AtNode *parent ) : m_node( node ) { if( node ) { AiNodeSetByte( node.get(), g_visibilityArnoldString, 0 ); m_ginstance = SharedAtNodePtr( AiNode( universe, g_ginstanceArnoldString, AtString( instanceName.c_str() ), parent ), nodeDeleter ); AiNodeSetPtr( m_ginstance.get(), g_nodeArnoldString, m_node.get() ); } } SharedAtNodePtr m_node; SharedAtNodePtr m_ginstance; }; // Forward declaration AtNode *convertProcedural( IECoreScenePreview::ConstProceduralPtr procedural, const ArnoldAttributes *attributes, AtUniverse *universe, const std::string &nodeName, AtNode *parentNode ); class InstanceCache : public IECore::RefCounted { public : InstanceCache( NodeDeleter nodeDeleter, AtUniverse *universe, AtNode *parentNode ) : m_nodeDeleter( nodeDeleter ), m_universe( universe ), m_parentNode( parentNode ) { } // Can be called concurrently with other get() calls. Instance get( const IECore::Object *object, const IECoreScenePreview::Renderer::AttributesInterface *attributes, const std::string &nodeName ) { const ArnoldAttributes *arnoldAttributes = static_cast<const ArnoldAttributes *>( attributes ); if( !arnoldAttributes->canInstanceGeometry( object ) ) { return Instance( convert( object, arnoldAttributes, nodeName ) ); } IECore::MurmurHash h = object->hash(); arnoldAttributes->hashGeometry( object, h ); SharedAtNodePtr node; Cache::const_accessor readAccessor; if( m_cache.find( readAccessor, h ) ) { node = readAccessor->second; readAccessor.release(); } else { Cache::accessor writeAccessor; if( m_cache.insert( writeAccessor, h ) ) { writeAccessor->second = convert( object, arnoldAttributes, "instance:" + h.toString() ); } node = writeAccessor->second; writeAccessor.release(); } return Instance( node, m_nodeDeleter, m_universe, nodeName, m_parentNode ); } Instance get( const std::vector<const IECore::Object *> &samples, const std::vector<float> &times, const IECoreScenePreview::Renderer::AttributesInterface *attributes, const std::string &nodeName ) { const ArnoldAttributes *arnoldAttributes = static_cast<const ArnoldAttributes *>( attributes ); if( !arnoldAttributes->canInstanceGeometry( samples.front() ) ) { return Instance( convert( samples, times, arnoldAttributes, nodeName ) ); } IECore::MurmurHash h; for( std::vector<const IECore::Object *>::const_iterator it = samples.begin(), eIt = samples.end(); it != eIt; ++it ) { (*it)->hash( h ); } for( std::vector<float>::const_iterator it = times.begin(), eIt = times.end(); it != eIt; ++it ) { h.append( *it ); } arnoldAttributes->hashGeometry( samples.front(), h ); SharedAtNodePtr node; Cache::const_accessor readAccessor; if( m_cache.find( readAccessor, h ) ) { node = readAccessor->second; readAccessor.release(); } else { Cache::accessor writeAccessor; if( m_cache.insert( writeAccessor, h ) ) { writeAccessor->second = convert( samples, times, arnoldAttributes, "instance:" + h.toString() ); } node = writeAccessor->second; writeAccessor.release(); } return Instance( node, m_nodeDeleter, m_universe, nodeName, m_parentNode ); } // Must not be called concurrently with anything. void clearUnused() { vector<IECore::MurmurHash> toErase; for( Cache::iterator it = m_cache.begin(), eIt = m_cache.end(); it != eIt; ++it ) { if( it->second.unique() ) { // Only one reference - this is ours, so // nothing outside of the cache is using the // node. toErase.push_back( it->first ); } } for( vector<IECore::MurmurHash>::const_iterator it = toErase.begin(), eIt = toErase.end(); it != eIt; ++it ) { m_cache.erase( *it ); } } void nodesCreated( vector<AtNode *> &nodes ) const { for( Cache::const_iterator it = m_cache.begin(), eIt = m_cache.end(); it != eIt; ++it ) { if( it->second ) { nodes.push_back( it->second.get() ); } } } private : SharedAtNodePtr convert( const IECore::Object *object, const ArnoldAttributes *attributes, const std::string &nodeName ) { if( !object ) { return SharedAtNodePtr(); } AtNode *node = nullptr; if( const IECoreScenePreview::Procedural *procedural = IECore::runTimeCast<const IECoreScenePreview::Procedural>( object ) ) { node = convertProcedural( procedural, attributes, m_universe, nodeName, m_parentNode ); } else { node = NodeAlgo::convert( object, m_universe, nodeName, m_parentNode ); } if( !node ) { return SharedAtNodePtr(); } attributes->applyGeometry( object, node ); return SharedAtNodePtr( node, m_nodeDeleter ); } SharedAtNodePtr convert( const std::vector<const IECore::Object *> &samples, const std::vector<float> &times, const ArnoldAttributes *attributes, const std::string &nodeName ) { ensureUniformTimeSamples( times ); AtNode *node = nullptr; if( const IECoreScenePreview::Procedural *procedural = IECore::runTimeCast<const IECoreScenePreview::Procedural>( samples.front() ) ) { node = convertProcedural( procedural, attributes, m_universe, nodeName, m_parentNode ); } else { node = NodeAlgo::convert( samples, times[0], times[times.size() - 1], m_universe, nodeName, m_parentNode ); } if( !node ) { return SharedAtNodePtr(); } attributes->applyGeometry( samples.front(), node ); return SharedAtNodePtr( node, m_nodeDeleter ); } NodeDeleter m_nodeDeleter; AtUniverse *m_universe; AtNode *m_parentNode; typedef tbb::concurrent_hash_map<IECore::MurmurHash, SharedAtNodePtr> Cache; Cache m_cache; }; IE_CORE_DECLAREPTR( InstanceCache ) } // namespace ////////////////////////////////////////////////////////////////////////// // ArnoldObject ////////////////////////////////////////////////////////////////////////// namespace { static IECore::InternedString g_surfaceAttributeName( "surface" ); static IECore::InternedString g_aiSurfaceAttributeName( "ai:surface" ); IE_CORE_FORWARDDECLARE( ArnoldLight ) class ArnoldObjectBase : public IECoreScenePreview::Renderer::ObjectInterface { public : ArnoldObjectBase( const Instance &instance ) : m_instance( instance ), m_attributes( nullptr ) { } void transform( const Imath::M44f &transform ) override { AtNode *node = m_instance.node(); if( !node ) { return; } applyTransform( node, transform ); } void transform( const std::vector<Imath::M44f> &samples, const std::vector<float> &times ) override { AtNode *node = m_instance.node(); if( !node ) { return; } applyTransform( node, samples, times ); } bool attributes( const IECoreScenePreview::Renderer::AttributesInterface *attributes ) override { const ArnoldAttributes *arnoldAttributes = static_cast<const ArnoldAttributes *>( attributes ); AtNode *node = m_instance.node(); if( !node || arnoldAttributes->apply( node, m_attributes.get() ) ) { m_attributes = arnoldAttributes; return true; } return false; } void link( const IECore::InternedString &type, const IECoreScenePreview::Renderer::ConstObjectSetPtr &objects ) override { } const Instance &instance() const { return m_instance; } protected : void applyTransform( AtNode *node, const Imath::M44f &transform, const AtString matrixParameterName = g_matrixArnoldString ) { AiNodeSetMatrix( node, matrixParameterName, reinterpret_cast<const AtMatrix&>( transform.x ) ); } void applyTransform( AtNode *node, const std::vector<Imath::M44f> &samples, const std::vector<float> &times, const AtString matrixParameterName = g_matrixArnoldString ) { const AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), matrixParameterName ); if( AiParamGetType( parameter ) != AI_TYPE_ARRAY ) { // Parameter doesn't support motion blur applyTransform( node, samples[0], matrixParameterName ); return; } const size_t numSamples = samples.size(); AtArray *matricesArray = AiArrayAllocate( 1, numSamples, AI_TYPE_MATRIX ); for( size_t i = 0; i < numSamples; ++i ) { AiArraySetMtx( matricesArray, i, reinterpret_cast<const AtMatrix&>( samples[i].x ) ); } AiNodeSetArray( node, matrixParameterName, matricesArray ); ensureUniformTimeSamples( times ); AiNodeSetFlt( node, g_motionStartArnoldString, times[0] ); AiNodeSetFlt( node, g_motionEndArnoldString, times[times.size() - 1] ); } Instance m_instance; // We keep a reference to the currently applied attributes // for a couple of reasons : // // - We need to keep the displacement and surface shaders // alive for as long as they are referenced by m_instance. // - We can use the previously applied attributes to determine // if an incoming attribute edit is impossible because it // would affect the instance itself, and return failure from // `attributes()`. ConstArnoldAttributesPtr m_attributes; }; IE_CORE_FORWARDDECLARE( ArnoldObject ) } // namespace ////////////////////////////////////////////////////////////////////////// // ArnoldLightFilter ////////////////////////////////////////////////////////////////////////// namespace { class ArnoldLightFilter : public ArnoldObjectBase { public : ArnoldLightFilter( const std::string &name, const Instance &instance, NodeDeleter nodeDeleter, AtUniverse *universe, const AtNode *parentNode ) : ArnoldObjectBase( instance ), m_name( name ), m_nodeDeleter( nodeDeleter ), m_universe( universe ), m_parentNode( parentNode ) { } ~ArnoldLightFilter() override { } void transform( const Imath::M44f &transform ) override { ArnoldObjectBase::transform( transform ); m_transformMatrices.clear(); m_transformTimes.clear(); m_transformMatrices.push_back( transform ); applyLightFilterTransform(); } void transform( const std::vector<Imath::M44f> &samples, const std::vector<float> &times ) override { ArnoldObjectBase::transform( samples, times ); m_transformMatrices = samples; m_transformTimes = times; applyLightFilterTransform(); } bool attributes( const IECoreScenePreview::Renderer::AttributesInterface *attributes ) override { if( !ArnoldObjectBase::attributes( attributes ) ) { return false; } // Update light filter shader. if( m_attributes->lightFilterShader() ) { if( !m_lightFilterShader ) { m_lightFilterShader = new ArnoldShader( m_attributes->lightFilterShader(), m_nodeDeleter, m_universe, "lightFilter:" + m_name, m_parentNode ); applyLightFilterTransform(); } else { bool keptRootShader = m_lightFilterShader->update( m_attributes->lightFilterShader() ); if( !keptRootShader ) { // Couldn't update existing shader in place because the shader type // was changed. This will leave dangling pointers in any `filters` lists // held by lights. Return false to force the client to rebuild from // scratch. return false; } } } else { if( m_lightFilterShader ) { // Removing `m_lightFilterShader` would create dangling pointers, // so we can not make the edit. return false; } } return true; } void nodesCreated( vector<AtNode *> &nodes ) const { if( m_lightFilterShader ) { m_lightFilterShader->nodesCreated( nodes ); } } ArnoldShader *lightFilterShader() const { return m_lightFilterShader.get(); } private : void applyLightFilterTransform() { if( !m_lightFilterShader || m_transformMatrices.empty() ) { return; } AtNode *root = m_lightFilterShader->root(); if( m_transformTimes.empty() ) { assert( m_transformMatrices.size() == 1 ); applyTransform( root, m_transformMatrices[0], g_geometryMatrixArnoldString ); } else { applyTransform( root, m_transformMatrices, m_transformTimes, g_geometryMatrixArnoldString ); } } std::string m_name; vector<Imath::M44f> m_transformMatrices; vector<float> m_transformTimes; NodeDeleter m_nodeDeleter; AtUniverse *m_universe; const AtNode *m_parentNode; ArnoldShaderPtr m_lightFilterShader; }; IE_CORE_DECLAREPTR( ArnoldLightFilter ) } // namespace ////////////////////////////////////////////////////////////////////////// // ArnoldLight ////////////////////////////////////////////////////////////////////////// namespace { IECore::InternedString g_lightFilters( "lightFilters" ); class ArnoldLight : public ArnoldObjectBase { public : ArnoldLight( const std::string &name, const Instance &instance, NodeDeleter nodeDeleter, AtUniverse *universe, const AtNode *parentNode ) : ArnoldObjectBase( instance ), m_name( name ), m_nodeDeleter( nodeDeleter ), m_universe( universe ), m_parentNode( parentNode ) { } ~ArnoldLight() override { } void transform( const Imath::M44f &transform ) override { ArnoldObjectBase::transform( transform ); m_transformMatrices.clear(); m_transformTimes.clear(); m_transformMatrices.push_back( transform ); applyLightTransform(); } void transform( const std::vector<Imath::M44f> &samples, const std::vector<float> &times ) override { ArnoldObjectBase::transform( samples, times ); m_transformMatrices = samples; m_transformTimes = times; applyLightTransform(); } bool attributes( const IECoreScenePreview::Renderer::AttributesInterface *attributes ) override { ConstArnoldAttributesPtr oldAttributes = m_attributes; if( !ArnoldObjectBase::attributes( attributes ) ) { return false; } // Update light shader. if( m_attributes->lightShader() ) { if( !m_lightShader ) { m_lightShader = new ArnoldShader( m_attributes->lightShader(), m_nodeDeleter, m_universe, "light:" + m_name, m_parentNode ); applyLightTransform(); // Link mesh lights to the geometry held by ArnoldObjectBase. if( AiNodeIs( m_lightShader->root(), g_meshLightArnoldString ) ) { if( m_instance.node() ) { AiNodeSetPtr( m_lightShader->root(), g_meshArnoldString, m_instance.node() ); } else { // Don't output mesh lights from locations with no object IECore::msg( IECore::Msg::Warning, "Arnold Render", "Mesh light without object at location: " + m_name ); m_lightShader = nullptr; } } } else { const IECoreScene::Shader* lightOutput = m_attributes->lightShader()->outputShader(); if( lightOutput && lightOutput->getName() == "quad_light" ) { IECoreScene::ShaderNetwork::Parameter newColorParameter = m_attributes->lightShader()->getOutput(); newColorParameter.name = "color"; IECoreScene::ShaderNetwork::Parameter newColorInput = m_attributes->lightShader()->input( newColorParameter ); IECoreScene::ShaderNetwork::Parameter oldColorParameter = oldAttributes->lightShader()->getOutput(); oldColorParameter.name = "color"; IECoreScene::ShaderNetwork::Parameter oldColorInput = oldAttributes->lightShader()->input( oldColorParameter ); if( newColorInput && oldColorInput ) { IECore::MurmurHash newColorHash, oldColorHash; hashShaderOutputParameter( m_attributes->lightShader(), newColorInput, newColorHash ); hashShaderOutputParameter( oldAttributes->lightShader(), oldColorInput, oldColorHash ); if( newColorHash != oldColorHash ) { // Arnold currently fails to update quad light shaders during interactive renders // correctly. ( At least when there is an edit to the color parameter, and it's // driven by a network which contains a texture. ) // Until they fix this, we can just throw out and rebuild quad lights whenever // there's a change to a network driving color return false; } } } bool keptRootShader = m_lightShader->update( m_attributes->lightShader() ); if( !keptRootShader ) { // Couldn't update existing shader in place because the shader type // was changed. This will leave dangling pointers in any `light_group` // lists held by objects. Return false to force the client to rebuild from // scratch. return false; } } } else { if( m_lightShader ) { // Removing `m_lightShader` would create dangling light linking pointers, // so we can not make the edit - the client must rebuild instead. return false; } else { // We're outputting a light that is invalid, output a warning about that IECore::msg( IECore::Msg::Warning, "Arnold Render", "Light without shader at location: " + m_name ); } } // Update filter links if needed. if( ( oldAttributes && oldAttributes->lightFilterShaders() != m_attributes->lightFilterShaders() ) || ( !oldAttributes && m_attributes->lightFilterShaders().size() ) ) { updateLightFilterLinks(); } return true; } void link( const IECore::InternedString &type, const IECoreScenePreview::Renderer::ConstObjectSetPtr &lightFilters ) override { if( type != g_lightFilters || lightFilters == m_linkedLightFilters ) { return; } m_linkedLightFilters = lightFilters; updateLightFilterLinks(); } const ArnoldShader *lightShader() const { return m_lightShader.get(); } void nodesCreated( vector<AtNode *> &nodes ) const { if( m_lightShader ) { m_lightShader->nodesCreated( nodes ); } } private : void applyLightTransform() { if( !m_lightShader || m_transformMatrices.empty() ) { return; } AtNode *root = m_lightShader->root(); if( m_transformTimes.empty() ) { assert( m_transformMatrices.size() == 1 ); applyTransform( root, m_transformMatrices[0] ); } else { applyTransform( root, m_transformMatrices, m_transformTimes ); } } void updateLightFilterLinks() { if( !m_lightShader ) { return; } auto &attributesLightFilters = m_attributes->lightFilterShaders(); vector<AtNode *> lightFilterNodes; lightFilterNodes.reserve( ( m_linkedLightFilters ? m_linkedLightFilters->size() : 0 ) + attributesLightFilters.size() ); if( m_linkedLightFilters ) { for( const auto &filter : *m_linkedLightFilters ) { const ArnoldLightFilter *arnoldFilter = static_cast<const ArnoldLightFilter *>( filter.get() ); if( arnoldFilter->lightFilterShader() ) { lightFilterNodes.push_back( arnoldFilter->lightFilterShader()->root() ); } } } for( const auto &filterShader : attributesLightFilters ) { lightFilterNodes.push_back( filterShader->root() ); } AiNodeSetArray( m_lightShader->root(), g_filtersArnoldString, AiArrayConvert( lightFilterNodes.size(), 1, AI_TYPE_NODE, lightFilterNodes.data() ) ); } // Because the AtNode for the light arrives via attributes(), // we need to store the transform and name ourselves so we have // them later when we need them. std::string m_name; vector<Imath::M44f> m_transformMatrices; vector<float> m_transformTimes; NodeDeleter m_nodeDeleter; AtUniverse *m_universe; const AtNode *m_parentNode; ArnoldShaderPtr m_lightShader; IECoreScenePreview::Renderer::ConstObjectSetPtr m_linkedLightFilters; }; IE_CORE_DECLAREPTR( ArnoldLight ) } // namespace ////////////////////////////////////////////////////////////////////////// // ArnoldObject ////////////////////////////////////////////////////////////////////////// namespace { IECore::InternedString g_lights( "lights" ); class ArnoldObject : public ArnoldObjectBase { public : ArnoldObject( const Instance &instance ) : ArnoldObjectBase( instance ) { } ~ArnoldObject() override { } void link( const IECore::InternedString &type, const IECoreScenePreview::Renderer::ConstObjectSetPtr &objects ) override { AtNode *node = m_instance.node(); if( !node ) { return; } AtString groupParameterName; AtString useParameterName; if( type == g_lights ) { groupParameterName = g_lightGroupArnoldString; useParameterName = g_useLightGroupArnoldString; } else if( type == g_shadowGroup ) { groupParameterName = g_shadowGroupArnoldString; useParameterName = g_useShadowGroupArnoldString; } else { return; } if( objects ) { vector<AtNode *> lightNodes; lightNodes.reserve( objects->size() ); for( const auto &o : *objects ) { auto arnoldLight = dynamic_cast<const ArnoldLight *>( o.get() ); if( arnoldLight && arnoldLight->lightShader() ) { lightNodes.push_back( arnoldLight->lightShader()->root() ); } else { if( !arnoldLight ) { // Not aware of any way this could happen IECore::msg( IECore::Msg::Warning, "ArnoldObject::link()", "Attempt to link nonexistent light" ); } else { // We have an ArnoldLight, but with an invalid lightShader. // It is the responsibility of ArnoldLight to output a warning when constructing in // an invalid state, so we don't need to warn here } } } AiNodeSetArray( node, groupParameterName, AiArrayConvert( lightNodes.size(), 1, AI_TYPE_NODE, lightNodes.data() ) ); AiNodeSetBool( node, useParameterName, true ); } else { AiNodeResetParameter( node, groupParameterName ); AiNodeResetParameter( node, useParameterName ); } } }; IE_CORE_DECLAREPTR( ArnoldLight ) } // namespace ////////////////////////////////////////////////////////////////////////// // Procedurals ////////////////////////////////////////////////////////////////////////// namespace { class ProceduralRenderer final : public ArnoldRendererBase { public : // We use a null node deleter because Arnold will automatically // destroy all nodes belonging to the procedural when the procedural // itself is destroyed. /// \todo The base class currently makes a new shader cache /// and a new instance cache. Can we share with the parent /// renderer instead? /// \todo Pass through the parent message hander so we can redirect /// IECore::msg message handlers here. ProceduralRenderer( AtNode *procedural, IECore::ConstCompoundObjectPtr attributesToInherit ) : ArnoldRendererBase( nullNodeDeleter, AiNodeGetUniverse( procedural ), procedural ), m_attributesToInherit( attributesToInherit ) { } void option( const IECore::InternedString &name, const IECore::Object *value ) override { IECore::msg( IECore::Msg::Warning, "ArnoldRenderer", "Procedurals can not call option()" ); } void output( const IECore::InternedString &name, const IECoreScene::Output *output ) override { IECore::msg( IECore::Msg::Warning, "ArnoldRenderer", "Procedurals can not call output()" ); } ArnoldRendererBase::AttributesInterfacePtr attributes( const IECore::CompoundObject *attributes ) override { // Emulate attribute inheritance. IECore::CompoundObjectPtr fullAttributes = new IECore::CompoundObject; for( const auto &a : m_attributesToInherit->members() ) { if( !customAttributeName( a.first.string() ) ) { // We ignore custom attributes because they follow normal inheritance // in Arnold anyway. They will be written onto the `ginstance` node // referring to the procedural instead. fullAttributes->members()[a.first] = a.second; } } for( const auto &a : attributes->members() ) { fullAttributes->members()[a.first] = a.second; } return ArnoldRendererBase::attributes( fullAttributes.get() ); } ObjectInterfacePtr camera( const std::string &name, const IECoreScene::Camera *camera, const AttributesInterface *attributes ) override { IECore::msg( IECore::Msg::Warning, "ArnoldRenderer", "Procedurals can not call camera()" ); return nullptr; } ObjectInterfacePtr camera( const std::string &name, const std::vector<const IECoreScene::Camera *> &samples, const std::vector<float> &times, const AttributesInterface *attributes ) override { IECore::msg( IECore::Msg::Warning, "ArnoldRenderer", "Procedurals can not call camera()" ); return nullptr; } ObjectInterfacePtr light( const std::string &name, const IECore::Object *object, const AttributesInterface *attributes ) override { ArnoldLightPtr result = static_pointer_cast<ArnoldLight>( ArnoldRendererBase::light( name, object, attributes ) ); NodesCreatedMutex::scoped_lock lock( m_nodesCreatedMutex ); result->instance().nodesCreated( m_nodesCreated ); result->nodesCreated( m_nodesCreated ); return result; } ObjectInterfacePtr lightFilter( const std::string &name, const IECore::Object *object, const AttributesInterface *attributes ) override { ArnoldLightFilterPtr result = static_pointer_cast<ArnoldLightFilter>( ArnoldRendererBase::lightFilter( name, object, attributes ) ); NodesCreatedMutex::scoped_lock lock( m_nodesCreatedMutex ); result->instance().nodesCreated( m_nodesCreated ); result->nodesCreated( m_nodesCreated ); return result; } Renderer::ObjectInterfacePtr object( const std::string &name, const IECore::Object *object, const AttributesInterface *attributes ) override { ArnoldObjectPtr result = static_pointer_cast<ArnoldObject>( ArnoldRendererBase::object( name, object, attributes ) ); NodesCreatedMutex::scoped_lock lock( m_nodesCreatedMutex ); result->instance().nodesCreated( m_nodesCreated ); return result; } ObjectInterfacePtr object( const std::string &name, const std::vector<const IECore::Object *> &samples, const std::vector<float> &times, const AttributesInterface *attributes ) override { ArnoldObjectPtr result = static_pointer_cast<ArnoldObject>( ArnoldRendererBase::object( name, samples, times, attributes ) ); NodesCreatedMutex::scoped_lock lock( m_nodesCreatedMutex ); result->instance().nodesCreated( m_nodesCreated ); return result; } void render() override { IECore::msg( IECore::Msg::Warning, "ArnoldRenderer", "Procedurals can not call render()" ); } void pause() override { IECore::msg( IECore::Msg::Warning, "ArnoldRenderer", "Procedurals can not call pause()" ); } void nodesCreated( vector<AtNode *> &nodes ) { nodes.insert( nodes.begin(), m_nodesCreated.begin(), m_nodesCreated.end() ); m_instanceCache->nodesCreated( nodes ); m_shaderCache->nodesCreated( nodes ); } private : IECore::ConstCompoundObjectPtr m_attributesToInherit; typedef tbb::spin_mutex NodesCreatedMutex; NodesCreatedMutex m_nodesCreatedMutex; vector<AtNode *> m_nodesCreated; }; IE_CORE_DECLAREPTR( ProceduralRenderer ) struct ProceduralData : boost::noncopyable { vector<AtNode *> nodesCreated; }; int procInit( AtNode *node, void **userPtr ) { ProceduralData *data = (ProceduralData *)( AiNodeGetPtr( node, g_userPtrArnoldString ) ); *userPtr = data; return 1; } int procCleanup( const AtNode *node, void *userPtr ) { const ProceduralData *data = (ProceduralData *)( userPtr ); delete data; return 1; } int procNumNodes( const AtNode *node, void *userPtr ) { const ProceduralData *data = (ProceduralData *)( userPtr ); return data->nodesCreated.size(); } AtNode *procGetNode( const AtNode *node, void *userPtr, int i ) { const ProceduralData *data = (ProceduralData *)( userPtr ); return data->nodesCreated[i]; } int procFunc( AtProceduralNodeMethods *methods ) { methods->Init = procInit; methods->Cleanup = procCleanup; methods->NumNodes = procNumNodes; methods->GetNode = procGetNode; return 1; } AtNode *convertProcedural( IECoreScenePreview::ConstProceduralPtr procedural, const ArnoldAttributes *attributes, AtUniverse *universe, const std::string &nodeName, AtNode *parentNode ) { AtNode *node = AiNode( universe, g_proceduralArnoldString, AtString( nodeName.c_str() ), parentNode ); AiNodeSetPtr( node, g_funcPtrArnoldString, (void *)procFunc ); ProceduralRendererPtr renderer = new ProceduralRenderer( node, attributes->allAttributes() ); tbb::this_task_arena::isolate( // Isolate in case procedural spawns TBB tasks, because // `convertProcedural()` is called behind a lock in // `InstanceCache.get()`. [&]() { procedural->render( renderer.get() ); } ); ProceduralData *data = new ProceduralData; renderer->nodesCreated( data->nodesCreated ); AiNodeSetPtr( node, g_userPtrArnoldString, data ); return node; } bool isConvertedProcedural( const AtNode *node ) { return AiNodeIs( node, g_proceduralArnoldString ) && AiNodeGetPtr( node, g_funcPtrArnoldString ) == procFunc; } } // namespace ////////////////////////////////////////////////////////////////////////// // Globals ////////////////////////////////////////////////////////////////////////// namespace { /// \todo Should these be defined in the Renderer base class? /// Or maybe be in a utility header somewhere? IECore::InternedString g_frameOptionName( "frame" ); IECore::InternedString g_cameraOptionName( "camera" ); IECore::InternedString g_logFileNameOptionName( "ai:log:filename" ); IECore::InternedString g_logMaxWarningsOptionName( "ai:log:max_warnings" ); IECore::InternedString g_statisticsFileNameOptionName( "ai:statisticsFileName" ); IECore::InternedString g_profileFileNameOptionName( "ai:profileFileName" ); IECore::InternedString g_pluginSearchPathOptionName( "ai:plugin_searchpath" ); IECore::InternedString g_aaSeedOptionName( "ai:AA_seed" ); IECore::InternedString g_enableProgressiveRenderOptionName( "ai:enable_progressive_render" ); IECore::InternedString g_progressiveMinAASamplesOptionName( "ai:progressive_min_AA_samples" ); IECore::InternedString g_sampleMotionOptionName( "sampleMotion" ); IECore::InternedString g_atmosphereOptionName( "ai:atmosphere" ); IECore::InternedString g_backgroundOptionName( "ai:background" ); IECore::InternedString g_colorManagerOptionName( "ai:color_manager" ); IECore::InternedString g_subdivDicingCameraOptionName( "ai:subdiv_dicing_camera" ); std::string g_logFlagsOptionPrefix( "ai:log:" ); std::string g_consoleFlagsOptionPrefix( "ai:console:" ); const int g_logFlagsDefault = AI_LOG_ALL; const int g_consoleFlagsDefault = AI_LOG_WARNINGS | AI_LOG_ERRORS | AI_LOG_TIMESTAMP | AI_LOG_BACKTRACE | AI_LOG_MEMORY | AI_LOG_COLOR; void throwError( int errorCode ) { switch( errorCode ) { case AI_ABORT : throw IECore::Exception( "Render aborted" ); case AI_ERROR_NO_CAMERA : throw IECore::Exception( "Camera not defined" ); case AI_ERROR_BAD_CAMERA : throw IECore::Exception( "Bad camera" ); case AI_ERROR_VALIDATION : throw IECore::Exception( "Usage not validated" ); case AI_ERROR_RENDER_REGION : throw IECore::Exception( "Invalid render region" ); case AI_INTERRUPT : throw IECore::Exception( "Render interrupted by user" ); case AI_ERROR_NO_OUTPUTS : throw IECore::Exception( "No outputs" ); case AI_ERROR : throw IECore::Exception( "Generic Arnold error" ); } } #if ARNOLD_VERSION_NUM < 70000 // Arnold 6 doesn't have AtRenderSession, so we define forwards-compatibility wrappers // that let us write code to the new API only, rather than sprinkle `#ifdefs` throughout. class AtRenderSession; AtRenderSession *AiRenderSession( AtUniverse *universe, AtSessionMode mode ) { return nullptr; } AtRenderErrorCode AiRenderBegin( AtRenderSession *renderSession, AtRenderMode mode = AI_RENDER_MODE_CAMERA, AtRenderUpdateCallback callback = nullptr, void *callbackData = nullptr ) { return ::AiRenderBegin( mode, callback, callbackData ); } void AiRenderInterrupt( AtRenderSession *renderSession, AtBlockingCall blocking ) { return ::AiRenderInterrupt( blocking ); } void AiRenderRestart( AtRenderSession *renderSession ) { return ::AiRenderRestart(); } AtRenderErrorCode AiRenderEnd( AtRenderSession *renderSession ) { return ::AiRenderEnd(); } bool AiRenderSetHintInt( AtRenderSession *renderSession, AtString hint, int32_t value ) { return AiRenderSetHintInt( hint, value ); } bool AiRenderSetHintBool( AtRenderSession *renderSession, AtString hint, bool value ) { return AiRenderSetHintBool( hint, value ); } void AiRenderAddInteractiveOutput( AtRenderSession *renderSession, uint32_t outputIndex ) { ::AiRenderAddInteractiveOutput( outputIndex ); } bool AiRenderRemoveInteractiveOutput( AtRenderSession *renderSession, uint32_t outputIndex ) { return ::AiRenderRemoveInteractiveOutput( outputIndex ); } void AiRenderSessionDestroy( AtRenderSession *renderSession ) { } void AiMsgSetConsoleFlags( const AtRenderSession *renderSession, int flags ) { ::AiMsgSetConsoleFlags( flags ); } void AiMsgSetLogFileFlags( const AtRenderSession *renderSession, int flags ) { ::AiMsgSetLogFileFlags( flags ); } #endif // Arnold's `AiRender()` function does exactly what you want for a batch render : // starts a render and returns when it is complete. But it is deprecated. Here we // jump through hoops to re-implement the behaviour using non-deprecated API. void renderAndWait( AtRenderSession *renderSession ) { // Updated by `callback` to notify this thread when the render has // completed. struct Status { std::mutex mutex; std::condition_variable conditionVariable; AtRenderStatus value = AI_RENDER_STATUS_NOT_STARTED; } status; // Called from one of the Arnold render threads to notify us of progress. auto callback = []( void *voidStatus, AtRenderUpdateType updateType, const AtRenderUpdateInfo *updateInfo ) { // We are required to return a new status for the render, // following a table of values in `ai_render.h`. AtRenderStatus newStatus = AI_RENDER_STATUS_FAILED; switch( updateType ) { case AI_RENDER_UPDATE_INTERRUPT : newStatus = AI_RENDER_STATUS_PAUSED; break; case AI_RENDER_UPDATE_BEFORE_PASS : newStatus = AI_RENDER_STATUS_RENDERING; break; case AI_RENDER_UPDATE_DURING_PASS : newStatus = AI_RENDER_STATUS_RENDERING; break; case AI_RENDER_UPDATE_AFTER_PASS : newStatus = AI_RENDER_STATUS_RENDERING; break; case AI_RENDER_UPDATE_IMAGERS : // Documentation doesn't state the appropriate // return value, so this is a guess. newStatus = AI_RENDER_STATUS_RENDERING; break; case AI_RENDER_UPDATE_FINISHED : newStatus = AI_RENDER_STATUS_FINISHED; break; case AI_RENDER_UPDATE_ERROR : newStatus = AI_RENDER_STATUS_FAILED; break; // No `default` clause so that the compiler will warn us // when new AtRenderUpdateType values are added. } if( newStatus == AI_RENDER_STATUS_FINISHED || newStatus == AI_RENDER_STATUS_FAILED ) { // Notify the waiting thread that we're done. Status *status = static_cast<Status *>( voidStatus ); { std::lock_guard<std::mutex> lock( status->mutex ); status->value = newStatus; } status->conditionVariable.notify_one(); } return newStatus; }; // Start the render. `AiRenderBegin()` returns immediately. AtRenderErrorCode result = AiRenderBegin( renderSession, AI_RENDER_MODE_CAMERA, callback, &status ); if( result != AI_SUCCESS ) { throwError( result ); } // Wait to be notified that the render has finished. We're using the // condition variable approach to avoid busy-waiting on `AiRenderGetStatus()`. std::unique_lock<std::mutex> lock( status.mutex ); status.conditionVariable.wait( lock, [&status]{ return status.value != AI_RENDER_STATUS_NOT_STARTED; } ); result = AiRenderEnd( renderSession ); if( result != AI_SUCCESS ) { throwError( result ); } } class ArnoldGlobals { public : ArnoldGlobals( IECoreScenePreview::Renderer::RenderType renderType, const std::string &fileName, const IECore::MessageHandlerPtr &messageHandler ) : m_renderType( renderType ), m_universeBlock( new IECoreArnold::UniverseBlock( /* writable = */ true ) ), m_renderSession( AiRenderSession( m_universeBlock->universe(), renderType == IECoreScenePreview::Renderer::RenderType::Interactive ? AI_SESSION_INTERACTIVE : AI_SESSION_BATCH ), &AiRenderSessionDestroy ), m_messageHandler( messageHandler ), m_interactiveOutput( -1 ), m_logFileFlags( g_logFlagsDefault ), m_consoleFlags( g_consoleFlagsDefault ), m_enableProgressiveRender( true ), m_shaderCache( new ShaderCache( nodeDeleter( renderType ), m_universeBlock->universe(), /* parentNode = */ nullptr ) ), m_renderBegun( false ), m_fileName( fileName ) { // If we've been given a MessageHandler then we output to that and // turn off Arnold's console logging. if( m_messageHandler ) { m_messageCallbackId = AiMsgRegisterCallback( &messageCallback, m_consoleFlags, this ); AiMsgSetConsoleFlags( m_renderSession.get(), AI_LOG_NONE ); } else { AiMsgSetConsoleFlags( m_renderSession.get(), m_consoleFlags ); } AiMsgSetLogFileFlags( m_renderSession.get(), m_logFileFlags ); // Get OSL shaders onto the shader searchpath. option( g_pluginSearchPathOptionName, new IECore::StringData( "" ) ); } ~ArnoldGlobals() { if( m_renderBegun ) { AiRenderInterrupt( m_renderSession.get(), AI_BLOCKING ); AiRenderEnd( m_renderSession.get() ); } // Delete nodes we own before universe is destroyed. m_shaderCache.reset(); m_outputs.clear(); m_colorManager.reset(); m_atmosphere.reset(); m_background.reset(); m_defaultCamera.reset(); // Destroy the universe while our message callback is // still active, so we catch any Arnold shutdown messages. m_renderSession.reset( nullptr ); m_universeBlock.reset( nullptr ); if( m_messageCallbackId ) { AiMsgDeregisterCallback( *m_messageCallbackId ); } } AtUniverse *universe() { return m_universeBlock->universe(); } void option( const IECore::InternedString &name, const IECore::Object *value ) { AtNode *options = AiUniverseGetOptions( m_universeBlock->universe() ); if( name == g_frameOptionName ) { if( value == nullptr ) { m_frame = boost::none; } else if( const IECore::IntData *d = reportedCast<const IECore::IntData>( value, "option", name ) ) { m_frame = d->readable(); } return; } else if( name == g_cameraOptionName ) { if( value == nullptr ) { m_cameraName = ""; } else if( const IECore::StringData *d = reportedCast<const IECore::StringData>( value, "option", name ) ) { m_cameraName = d->readable(); } return; } else if( name == g_subdivDicingCameraOptionName ) { if( value == nullptr ) { m_subdivDicingCameraName = ""; } else if( const IECore::StringData *d = reportedCast<const IECore::StringData>( value, "option", name ) ) { m_subdivDicingCameraName = d->readable(); } return; } else if( name == g_logFileNameOptionName ) { if( value == nullptr ) { AiMsgSetLogFileName( "" ); } else if( const IECore::StringData *d = reportedCast<const IECore::StringData>( value, "option", name ) ) { if( !d->readable().empty() ) { try { boost::filesystem::path path( d->readable() ); path.remove_filename(); boost::filesystem::create_directories( path ); } catch( const std::exception &e ) { IECore::msg( IECore::Msg::Error, "ArnoldRenderer::option()", e.what() ); } } /// \todo Arnold only has one global log file, but we want /// one per renderer. AiMsgSetLogFileName( d->readable().c_str() ); } return; } else if( name == g_statisticsFileNameOptionName ) { AiStatsSetMode( AI_STATS_MODE_OVERWRITE ); if( value == nullptr ) { AiStatsSetFileName( "" ); } else if( const IECore::StringData *d = reportedCast<const IECore::StringData>( value, "option", name ) ) { if( !d->readable().empty() ) { try { boost::filesystem::path path( d->readable() ); path.remove_filename(); boost::filesystem::create_directories( path ); } catch( const std::exception &e ) { IECore::msg( IECore::Msg::Error, "ArnoldRenderer::option()", e.what() ); } } AiStatsSetFileName( d->readable().c_str() ); } return; } else if( name == g_profileFileNameOptionName ) { if( value == nullptr ) { AiProfileSetFileName( "" ); } else if( const IECore::StringData *d = reportedCast<const IECore::StringData>( value, "option", name ) ) { if( !d->readable().empty() ) { try { boost::filesystem::path path( d->readable() ); path.remove_filename(); boost::filesystem::create_directories( path ); } catch( const std::exception &e ) { IECore::msg( IECore::Msg::Error, "ArnoldRenderer::option()", e.what() ); } } AiProfileSetFileName( d->readable().c_str() ); } return; } else if( name == g_logMaxWarningsOptionName ) { if( value == nullptr ) { AiMsgSetMaxWarnings( 100 ); } else if( const IECore::IntData *d = reportedCast<const IECore::IntData>( value, "option", name ) ) { AiMsgSetMaxWarnings( d->readable() ); } return; } else if( boost::starts_with( name.c_str(), g_logFlagsOptionPrefix ) ) { if( updateLogFlags( name.string().substr( g_logFlagsOptionPrefix.size() ), IECore::runTimeCast<const IECore::Data>( value ), /* console = */ false ) ) { return; } } else if( boost::starts_with( name.c_str(), g_consoleFlagsOptionPrefix ) ) { if( updateLogFlags( name.string().substr( g_consoleFlagsOptionPrefix.size() ), IECore::runTimeCast<const IECore::Data>( value ), /* console = */ true ) ) { return; } } else if( name == g_enableProgressiveRenderOptionName ) { if( value == nullptr ) { m_enableProgressiveRender = true; } else if( auto d = reportedCast<const IECore::BoolData>( value, "option", name ) ) { m_enableProgressiveRender = d->readable(); } return; } else if( name == g_progressiveMinAASamplesOptionName ) { if( value == nullptr ) { m_progressiveMinAASamples = boost::none; } else if( const IECore::IntData *d = reportedCast<const IECore::IntData>( value, "option", name ) ) { m_progressiveMinAASamples = d->readable(); } return; } else if( name == g_aaSeedOptionName ) { if( value == nullptr ) { m_aaSeed = boost::none; } else if( const IECore::IntData *d = reportedCast<const IECore::IntData>( value, "option", name ) ) { m_aaSeed = d->readable(); } return; } else if( name == g_sampleMotionOptionName ) { bool sampleMotion = true; if( value ) { if( const IECore::BoolData *d = reportedCast<const IECore::BoolData>( value, "option", name ) ) { sampleMotion = d->readable(); } } AiNodeSetBool( options, g_ignoreMotionBlurArnoldString, !sampleMotion ); return; } else if( name == g_pluginSearchPathOptionName ) { // We must include the OSL searchpaths in Arnold's shader // searchpaths so that the OSL shaders can be found. const char *searchPath = getenv( "OSL_SHADER_PATHS" ); std::string s( searchPath ? searchPath : "" ); if( value ) { if( const IECore::StringData *d = reportedCast<const IECore::StringData>( value, "option", name ) ) { s = d->readable() + ":" + s; } } AiNodeSetStr( options, g_pluginSearchPathArnoldString, AtString( s.c_str() ) ); return; } else if( name == g_colorManagerOptionName ) { m_colorManager = nullptr; if( value ) { if( const IECoreScene::ShaderNetwork *d = reportedCast<const IECoreScene::ShaderNetwork>( value, "option", name ) ) { m_colorManager = m_shaderCache->get( d, nullptr ); } } AiNodeSetPtr( options, g_colorManagerArnoldString, m_colorManager ? m_colorManager->root() : nullptr ); return; } else if( name == g_atmosphereOptionName ) { m_atmosphere = nullptr; if( value ) { if( const IECoreScene::ShaderNetwork *d = reportedCast<const IECoreScene::ShaderNetwork>( value, "option", name ) ) { m_atmosphere = m_shaderCache->get( d, nullptr ); } } AiNodeSetPtr( options, g_atmosphereArnoldString, m_atmosphere ? m_atmosphere->root() : nullptr ); return; } else if( name == g_backgroundOptionName ) { m_background = nullptr; if( value ) { if( const IECoreScene::ShaderNetwork *d = reportedCast<const IECoreScene::ShaderNetwork>( value, "option", name ) ) { m_background = m_shaderCache->get( d, nullptr ); } } AiNodeSetPtr( options, g_backgroundArnoldString, m_background ? m_background->root() : nullptr ); return; } else if( boost::starts_with( name.c_str(), "ai:aov_shader:" ) ) { m_aovShaders.erase( name ); if( value ) { if( const IECoreScene::ShaderNetwork *d = reportedCast<const IECoreScene::ShaderNetwork>( value, "option", name ) ) { m_aovShaders[name] = m_shaderCache->get( d, nullptr ); } } AtArray *array = AiArrayAllocate( m_aovShaders.size(), 1, AI_TYPE_NODE ); int i = 0; for( AOVShaderMap::const_iterator it = m_aovShaders.begin(); it != m_aovShaders.end(); ++it ) { AiArraySetPtr( array, i++, it->second->root() ); } AiNodeSetArray( options, g_aovShadersArnoldString, array ); return; } else if( boost::starts_with( name.c_str(), "ai:declare:" ) ) { AtString arnoldName( name.c_str() + 11 ); const AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( options ), arnoldName ); if( parameter ) { IECore::msg( IECore::Msg::Warning, "IECoreArnold::Renderer::option", boost::format( "Unable to declare existing option \"%s\"." ) % arnoldName.c_str() ); } else { const AtUserParamEntry *userParameter = AiNodeLookUpUserParameter( options, arnoldName ); if( userParameter ) { AiNodeResetParameter( options, arnoldName ); } const IECore::Data *dataValue = IECore::runTimeCast<const IECore::Data>( value ); if( dataValue ) { ParameterAlgo::setParameter( options, arnoldName, dataValue ); } } return; } else if( boost::starts_with( name.c_str(), "ai:" ) ) { if( name == "ai:ignore_motion_blur" ) { IECore::msg( IECore::Msg::Warning, "IECoreArnold::Renderer::option", boost::format( "ai:ignore_motion_blur is not supported directly - set generic Gaffer option sampleMotion to False to control this option." ) ); return; } AtString arnoldName( name.c_str() + 3 ); const AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( options ), arnoldName ); if( parameter ) { const IECore::Data *dataValue = IECore::runTimeCast<const IECore::Data>( value ); if( dataValue ) { ParameterAlgo::setParameter( options, arnoldName, dataValue ); } else { AiNodeResetParameter( options, arnoldName ); } return; } } else if( boost::starts_with( name.c_str(), "user:" ) ) { AtString arnoldName( name.c_str() ); const IECore::Data *dataValue = IECore::runTimeCast<const IECore::Data>( value ); if( dataValue ) { ParameterAlgo::setParameter( options, arnoldName, dataValue ); } else { AiNodeResetParameter( options, arnoldName ); } return; } else if( boost::contains( name.c_str(), ":" ) ) { // Ignore options prefixed for some other renderer. return; } IECore::msg( IECore::Msg::Warning, "IECoreArnold::Renderer::option", boost::format( "Unknown option \"%s\"." ) % name.c_str() ); } void output( const IECore::InternedString &name, const IECoreScene::Output *output ) { m_outputs.erase( name ); if( output ) { try { m_outputs[name] = new ArnoldOutput( m_universeBlock->universe(), name, output, nodeDeleter( m_renderType ) ); } catch( const std::exception &e ) { IECore::msg( IECore::Msg::Warning, "IECoreArnold::Renderer::output", e.what() ); } } } // Some of Arnold's globals come from camera parameters, so the // ArnoldRenderer calls this method to notify the ArnoldGlobals // of each camera as it is created. void camera( const std::string &name, IECoreScene::ConstCameraPtr camera ) { m_cameras[name] = camera; } void render() { updateCameraMeshes(); AtNode *options = AiUniverseGetOptions( m_universeBlock->universe() ); AiNodeSetInt( options, g_aaSeedArnoldString, m_aaSeed.get_value_or( m_frame.get_value_or( 1 ) ) ); AtNode *dicingCamera = nullptr; if( m_subdivDicingCameraName.size() ) { dicingCamera = AiNodeLookUpByName( m_universeBlock->universe(), AtString( m_subdivDicingCameraName.c_str() ) ); if( !dicingCamera ) { IECore::msg( IECore::Msg::Warning, "IECoreArnold::Renderer", "Could not find dicing camera named: " + m_subdivDicingCameraName ); } } if( dicingCamera ) { AiNodeSetPtr( options, g_subdivDicingCameraString, dicingCamera ); } else { AiNodeResetParameter( options, g_subdivDicingCameraString ); } m_shaderCache->clearUnused(); // Do the appropriate render based on // m_renderType. switch( m_renderType ) { case IECoreScenePreview::Renderer::Batch : { // Loop through all cameras referenced by any current outputs, // and do a render for each std::set<std::string> cameraOverrides; for( const auto &it : m_outputs ) { cameraOverrides.insert( it.second->cameraOverride() ); } for( const auto &cameraOverride : cameraOverrides ) { updateCamera( cameraOverride.size() ? cameraOverride : m_cameraName ); renderAndWait( m_renderSession.get() ); } break; } case IECoreScenePreview::Renderer::SceneDescription : { // A scene file can only contain options to render from one camera, // so just use the default camera. updateCamera( m_cameraName ); unique_ptr<AtParamValueMap, decltype(&AiParamValueMapDestroy)> params( AiParamValueMap(), AiParamValueMapDestroy ); AiSceneWrite( m_universeBlock->universe(), m_fileName.c_str(), params.get() ); break; } case IECoreScenePreview::Renderer::Interactive : // If we want to use Arnold's progressive refinement, we can't be constantly switching // the camera around, so just use the default camera if( m_renderBegun ) { AiRenderInterrupt( m_renderSession.get(), AI_BLOCKING ); } updateCamera( m_cameraName ); // Set progressive options. This is a bit of a mess. There are two different // "progressive" modes in Arnold : // // 1. A series of throwaway low-sampling renders of increasing resolution. // This is controlled by two render hints : `progressive` and // `progressive_min_AA_samples`. // 2. Progressive sample-by-sample rendering of the final high quality image. // This is controlled by `options.enable_progressive_render`, although // SolidAngle don't recommend it be used for batch rendering. // // Technically these are orthogonal and could be used independently, but that // makes for a confusing array of options and the necessity of explaining the // two different versions of "progressive". Instead we enable #1 only when #2 // is enabled. const int minAASamples = m_progressiveMinAASamples.get_value_or( -4 ); // Must never set `progressive_min_AA_samples > -1`, as it'll get stuck and // Arnold will never let us set it back. AiRenderSetHintInt( m_renderSession.get(), AtString( "progressive_min_AA_samples" ), std::min( minAASamples, -1 ) ); // It seems important to set `progressive` after `progressive_min_AA_samples`, // otherwise Arnold may ignore changes to the latter. Disable entirely for // `minAASamples == 0` to account for the workaround above. AiRenderSetHintBool( m_renderSession.get(), AtString( "progressive" ), m_enableProgressiveRender && minAASamples < 0 ); AiNodeSetBool( AiUniverseGetOptions( m_universeBlock->universe() ), g_enableProgressiveRenderString, m_enableProgressiveRender ); if( !m_renderBegun ) { AiRenderBegin( m_renderSession.get(), AI_RENDER_MODE_CAMERA ); // Arnold's AiRenderGetStatus is not particularly reliable - renders start up on a separate thread, // and the currently reported status may not include recent changes. So instead, we track a basic // status flag for whether we are already rendering ourselves m_renderBegun = true; } else { AiRenderRestart( m_renderSession.get() ); } break; } } void pause() { // We need to block here because pause() is used to make sure that the render isn't running // before performing IPR edits. AiRenderInterrupt( m_renderSession.get(), AI_BLOCKING ); } private : bool updateLogFlags( const std::string name, const IECore::Data *value, bool console ) { int flagToModify = AI_LOG_NONE; if( name == "info" ) { flagToModify = AI_LOG_INFO; } else if( name == "warnings" ) { flagToModify = AI_LOG_WARNINGS; } else if( name == "errors" ) { flagToModify = AI_LOG_ERRORS; } else if( name == "debug" ) { flagToModify = AI_LOG_DEBUG; } else if( name == "stats" ) { flagToModify = AI_LOG_STATS; } else if( name == "ass_parse" ) { flagToModify = AI_LOG_ASS_PARSE; } else if( name == "plugins" ) { flagToModify = AI_LOG_PLUGINS; } else if( name == "progress" ) { flagToModify = AI_LOG_PROGRESS; } else if( name == "nan" ) { flagToModify = AI_LOG_NAN; } else if( name == "timestamp" ) { flagToModify = AI_LOG_TIMESTAMP; } else if( name == "backtrace" ) { flagToModify = AI_LOG_BACKTRACE; } else if( name == "memory" ) { flagToModify = AI_LOG_MEMORY; } else if( name == "color" ) { flagToModify = AI_LOG_COLOR; } else { return false; } bool turnOn = false; if( value == nullptr ) { turnOn = flagToModify & ( console == false ? g_logFlagsDefault : g_consoleFlagsDefault ); } else if( const IECore::BoolData *d = reportedCast<const IECore::BoolData>( value, "option", name ) ) { turnOn = d->readable(); } else { return true; } int &flags = console ? m_consoleFlags : m_logFileFlags; if( turnOn ) { flags |= flagToModify; } else { flags = flags & ~flagToModify; } if( console ) { if( m_messageCallbackId ) { AiMsgSetCallbackMask( *m_messageCallbackId, flags ); } else { AiMsgSetConsoleFlags( m_renderSession.get(), flags ); } } else { AiMsgSetLogFileFlags( m_renderSession.get(), flags ); } return true; } void updateCamera( const std::string &cameraName ) { AtNode *options = AiUniverseGetOptions( m_universeBlock->universe() ); // Set the global output list in the options to all outputs matching the current camera IECore::StringVectorDataPtr outputs = new IECore::StringVectorData; IECore::StringVectorDataPtr lpes = new IECore::StringVectorData; for( OutputMap::const_iterator it = m_outputs.begin(), eIt = m_outputs.end(); it != eIt; ++it ) { std::string outputCamera = it->second->cameraOverride(); if( outputCamera == "" ) { outputCamera = m_cameraName; } if( outputCamera == cameraName ) { it->second->append( outputs->writable(), lpes->writable() ); } } if( m_interactiveOutput >= 0 ) { // Remove interactive output before the index is invalidated. We'll set it // again to the right index below. AiRenderRemoveInteractiveOutput( m_renderSession.get(), m_interactiveOutput ); } std::sort( outputs->writable().begin(), outputs->writable().end() ); IECoreArnold::ParameterAlgo::setParameter( options, "outputs", outputs.get() ); IECoreArnold::ParameterAlgo::setParameter( options, "light_path_expressions", lpes.get() ); // Set the beauty as the output to get frequent interactive updates m_interactiveOutput = 0; for( unsigned int i = 0; i < outputs->readable().size(); i++ ) { if( boost::starts_with( outputs->readable()[i], "RGBA " ) ) { m_interactiveOutput = i; break; } } AiRenderAddInteractiveOutput( m_renderSession.get(), m_interactiveOutput ); const IECoreScene::Camera *cortexCamera; AtNode *arnoldCamera = AiNodeLookUpByName( m_universeBlock->universe(), AtString( cameraName.c_str() ) ); if( arnoldCamera ) { cortexCamera = m_cameras[cameraName].get(); m_defaultCamera = nullptr; } else { if( !m_defaultCamera ) { IECoreScene::ConstCameraPtr defaultCortexCamera = new IECoreScene::Camera(); m_cameras["ieCoreArnold:defaultCamera"] = defaultCortexCamera; m_defaultCamera = SharedAtNodePtr( NodeAlgo::convert( defaultCortexCamera.get(), m_universeBlock->universe(), "ieCoreArnold:defaultCamera", nullptr ), nodeDeleter( m_renderType ) ); } cortexCamera = m_cameras["ieCoreArnold:defaultCamera"].get(); arnoldCamera = m_defaultCamera.get(); } AiNodeSetPtr( options, g_cameraArnoldString, arnoldCamera ); Imath::V2i resolution = cortexCamera->renderResolution(); Imath::Box2i renderRegion = cortexCamera->renderRegion(); AiNodeSetInt( options, g_xresArnoldString, resolution.x ); AiNodeSetInt( options, g_yresArnoldString, resolution.y ); AiNodeSetFlt( options, g_pixelAspectRatioArnoldString, cortexCamera->getPixelAspectRatio() ); if( renderRegion.min.x >= renderRegion.max.x || renderRegion.min.y >= renderRegion.max.y ) { // Arnold does not permit empty render regions. The user intent of an empty render // region is probably to render as little as possible ( it could happen if you // built a tool to crop to an object which passed out of frame ). // We just pick one pixel in the corner renderRegion = Imath::Box2i( Imath::V2i( 0 ), Imath::V2i( 1 ) ); } // Note that we have to flip Y and subtract 1 from the max value, because // renderRegion is stored in Gaffer image format ( +Y up and an exclusive upper bound ) AiNodeSetInt( options, g_regionMinXArnoldString, renderRegion.min.x ); AiNodeSetInt( options, g_regionMinYArnoldString, resolution.y - renderRegion.max.y ); AiNodeSetInt( options, g_regionMaxXArnoldString, renderRegion.max.x - 1 ); AiNodeSetInt( options, g_regionMaxYArnoldString, resolution.y - renderRegion.min.y - 1 ); Imath::V2f shutter = cortexCamera->getShutter(); AiNodeSetFlt( arnoldCamera, g_shutterStartArnoldString, shutter[0] ); AiNodeSetFlt( arnoldCamera, g_shutterEndArnoldString, shutter[1] ); } void updateCameraMeshes() { for( const auto &it : m_cameras ) { IECoreScene::ConstCameraPtr cortexCamera = it.second; std::string meshPath = parameter( cortexCamera->parameters(), "mesh", std::string("") ); if( !meshPath.size() ) { continue; } AtNode *arnoldCamera = AiNodeLookUpByName( m_universeBlock->universe(), AtString( it.first.c_str() ) ); if( !arnoldCamera ) { continue; } AtNode *meshNode = AiNodeLookUpByName( m_universeBlock->universe(), AtString( meshPath.c_str() ) ); if( meshNode ) { AtString meshType = AiNodeEntryGetNameAtString( AiNodeGetNodeEntry( meshNode ) ); if( meshType == g_ginstanceArnoldString ) { AiNodeSetPtr( arnoldCamera, g_meshArnoldString, AiNodeGetPtr( meshNode, g_nodeArnoldString ) ); AiNodeSetMatrix( arnoldCamera, g_matrixArnoldString, AiNodeGetMatrix( meshNode, g_matrixArnoldString ) ); continue; } else if( meshType == g_polymeshArnoldString ) { AiNodeSetPtr( arnoldCamera, g_meshArnoldString, meshNode ); AiNodeSetMatrix( arnoldCamera, g_matrixArnoldString, AiM4Identity() ); continue; } } throw IECore::Exception( boost::str( boost::format( "While outputting camera \"%s\", could not find target mesh at \"%s\"" ) % it.first % meshPath ) ); } } static void messageCallback( int mask, int severity, const char *message, AtParamValueMap *metadata, void *userPtr ) { const ArnoldGlobals *that = static_cast<ArnoldGlobals *>( userPtr ); #if ARNOLD_VERSION_NUM >= 70000 // We get given messages from all render sessions, but can filter them based on the // `render_session` metadata. void *renderSession = nullptr; if( AiParamValueMapGetPtr( metadata, g_renderSessionArnoldString, &renderSession ) ) { if( renderSession != that->m_renderSession.get() ) { return; } } #endif const IECore::Msg::Level level = \ ( mask == AI_LOG_DEBUG ) ? IECore::Msg::Level::Debug : g_ieMsgLevels[ min( severity, 3 ) ]; std::stringstream msg; if( that->m_consoleFlags & AI_LOG_TIMESTAMP ) { const boost::posix_time::time_duration elapsed = boost::posix_time::millisec( AiMsgUtilGetElapsedTime() ); msg << std::setfill( '0' ); msg << std::setw( 2 ) << elapsed.hours() << ":"; msg << std::setw( 2 ) << elapsed.minutes() << ":"; msg << std::setw( 2 ) << elapsed.seconds() << " "; } if( that->m_consoleFlags & AI_LOG_MEMORY ) { const size_t mb = AiMsgUtilGetUsedMemory() / 1024 / 1024; msg << std::setfill( ' ' ) << std::setw( 4 ); if( mb < 1024 ) { msg << mb << "MB "; } else { msg.setf( std::ios::fixed, std::ios::floatfield ); msg << setprecision( 1 ) << ( float( mb ) / 1024.0f ) << "GB "; } } msg << message; that->m_messageHandler->handle( level, "Arnold", msg.str() ); } static const std::vector<IECore::MessageHandler::Level> g_ieMsgLevels; // Members used by all render types IECoreScenePreview::Renderer::RenderType m_renderType; std::unique_ptr<UniverseBlock> m_universeBlock; std::unique_ptr<AtRenderSession, decltype(&AiRenderSessionDestroy)> m_renderSession; IECore::MessageHandlerPtr m_messageHandler; boost::optional<unsigned> m_messageCallbackId; typedef std::map<IECore::InternedString, ArnoldOutputPtr> OutputMap; OutputMap m_outputs; int m_interactiveOutput; // Negative if not yet set. typedef std::map<IECore::InternedString, ArnoldShaderPtr> AOVShaderMap; AOVShaderMap m_aovShaders; ArnoldShaderPtr m_colorManager; ArnoldShaderPtr m_atmosphere; ArnoldShaderPtr m_background; std::string m_cameraName; typedef tbb::concurrent_unordered_map<std::string, IECoreScene::ConstCameraPtr> CameraMap; CameraMap m_cameras; SharedAtNodePtr m_defaultCamera; std::string m_subdivDicingCameraName; int m_logFileFlags; int m_consoleFlags; boost::optional<int> m_frame; boost::optional<int> m_aaSeed; bool m_enableProgressiveRender; boost::optional<int> m_progressiveMinAASamples; ShaderCachePtr m_shaderCache; bool m_renderBegun; // Members used by SceneDescription "renders" std::string m_fileName; }; const std::vector<IECore::MessageHandler::Level> ArnoldGlobals::g_ieMsgLevels = { IECore::MessageHandler::Level::Info, IECore::MessageHandler::Level::Warning, IECore::MessageHandler::Level::Error, IECore::MessageHandler::Level::Error }; } // namespace ////////////////////////////////////////////////////////////////////////// // ArnoldRendererBase definition ////////////////////////////////////////////////////////////////////////// namespace { ArnoldRendererBase::ArnoldRendererBase( NodeDeleter nodeDeleter, AtUniverse *universe, AtNode *parentNode, const IECore::MessageHandlerPtr &messageHandler ) : m_nodeDeleter( nodeDeleter ), m_universe( universe ), m_shaderCache( new ShaderCache( nodeDeleter, universe, parentNode ) ), m_instanceCache( new InstanceCache( nodeDeleter, universe, parentNode ) ), m_messageHandler( messageHandler ), m_parentNode( parentNode ) { } ArnoldRendererBase::~ArnoldRendererBase() { } IECore::InternedString ArnoldRendererBase::name() const { return "Arnold"; } ArnoldRendererBase::AttributesInterfacePtr ArnoldRendererBase::attributes( const IECore::CompoundObject *attributes ) { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); return new ArnoldAttributes( attributes, m_shaderCache.get() ); } ArnoldRendererBase::ObjectInterfacePtr ArnoldRendererBase::camera( const std::string &name, const IECoreScene::Camera *camera, const AttributesInterface *attributes ) { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); Instance instance = m_instanceCache->get( camera, attributes, name ); ObjectInterfacePtr result = new ArnoldObject( instance ); result->attributes( attributes ); return result; } ArnoldRendererBase::ObjectInterfacePtr ArnoldRendererBase::camera( const std::string &name, const std::vector<const IECoreScene::Camera *> &samples, const std::vector<float> &times, const AttributesInterface *attributes ) { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); Instance instance = m_instanceCache->get( vector<const IECore::Object *>( samples.begin(), samples.end() ), times, attributes, name ); ObjectInterfacePtr result = new ArnoldObject( instance ); result->attributes( attributes ); return result; } ArnoldRendererBase::ObjectInterfacePtr ArnoldRendererBase::light( const std::string &name, const IECore::Object *object, const AttributesInterface *attributes ) { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); Instance instance = m_instanceCache->get( object, attributes, name ); ObjectInterfacePtr result = new ArnoldLight( name, instance, m_nodeDeleter, m_universe, m_parentNode ); result->attributes( attributes ); return result; } ArnoldRendererBase::ObjectInterfacePtr ArnoldRendererBase::lightFilter( const std::string &name, const IECore::Object *object, const AttributesInterface *attributes ) { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); Instance instance = m_instanceCache->get( object, attributes, name ); ObjectInterfacePtr result = new ArnoldLightFilter( name, instance, m_nodeDeleter, m_universe, m_parentNode ); result->attributes( attributes ); return result; } ArnoldRendererBase::ObjectInterfacePtr ArnoldRendererBase::object( const std::string &name, const IECore::Object *object, const AttributesInterface *attributes ) { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); Instance instance = m_instanceCache->get( object, attributes, name ); ObjectInterfacePtr result = new ArnoldObject( instance ); result->attributes( attributes ); return result; } ArnoldRendererBase::ObjectInterfacePtr ArnoldRendererBase::object( const std::string &name, const std::vector<const IECore::Object *> &samples, const std::vector<float> &times, const AttributesInterface *attributes ) { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); Instance instance = m_instanceCache->get( samples, times, attributes, name ); ObjectInterfacePtr result = new ArnoldObject( instance ); result->attributes( attributes ); return result; } } // namespace ////////////////////////////////////////////////////////////////////////// // ArnoldRenderer ////////////////////////////////////////////////////////////////////////// namespace { /// The full renderer implementation as presented to the outside world. class ArnoldRenderer final : public ArnoldRendererBase { public : // Public constructor makes ArnoldGlobals and delegates to a private internal // constructor. This allows us to pass the universe from the globals to the // ArnoldRendererBase constructor. ArnoldRenderer( RenderType renderType, const std::string &fileName, const IECore::MessageHandlerPtr &messageHandler ) : ArnoldRenderer( nodeDeleter( renderType ), std::make_unique<ArnoldGlobals>( renderType, fileName, messageHandler ), messageHandler ) { } ~ArnoldRenderer() override { pause(); // Delete cached nodes before universe is destroyed. m_instanceCache.reset( nullptr ); m_shaderCache.reset( nullptr ); } void option( const IECore::InternedString &name, const IECore::Object *value ) override { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); m_globals->option( name, value ); } void output( const IECore::InternedString &name, const IECoreScene::Output *output ) override { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); m_globals->output( name, output ); } ObjectInterfacePtr camera( const std::string &name, const IECoreScene::Camera *camera, const AttributesInterface *attributes ) override { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); m_globals->camera( name, camera ); return ArnoldRendererBase::camera( name, camera, attributes ); } ObjectInterfacePtr camera( const std::string &name, const std::vector<const IECoreScene::Camera *> &samples, const std::vector<float> &times, const AttributesInterface *attributes ) override { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); m_globals->camera( name, samples[0] ); return ArnoldRendererBase::camera( name, samples, times, attributes ); } void render() override { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); m_shaderCache->clearUnused(); m_instanceCache->clearUnused(); m_globals->render(); } void pause() override { const IECore::MessageHandler::Scope s( m_messageHandler.get() ); m_globals->pause(); } IECore::DataPtr command( const IECore::InternedString name, const IECore::CompoundDataMap &parameters ) override { if( name == "ai:queryUniverse" ) { // Provide access to the underlying `AtUniverse`, for debugging // and testing. return new IECore::UInt64Data( (uint64_t)m_universe ); } else if( name == "ai:cacheFlush" ) { const int flags = parameter<int>( parameters, "flags", AI_CACHE_ALL ); AiUniverseCacheFlush( m_universe, flags ); return nullptr; } throw IECore::Exception( "Unknown command" ); } private : ArnoldRenderer( NodeDeleter nodeDeleter, std::unique_ptr<ArnoldGlobals> globals, const IECore::MessageHandlerPtr &messageHandler ) : ArnoldRendererBase( nodeDeleter, globals->universe(), /* parentNode = */ nullptr, messageHandler ), m_globals( std::move( globals ) ) { } std::unique_ptr<ArnoldGlobals> m_globals; // Registration with factory static Renderer::TypeDescription<ArnoldRenderer> g_typeDescription; }; IECoreScenePreview::Renderer::TypeDescription<ArnoldRenderer> ArnoldRenderer::g_typeDescription( "Arnold" ); } // namespace
{ "content_hash": "afaa59a2f18c8bd4bc630b60d074fa32", "timestamp": "", "source": "github", "line_count": 4169, "max_line_length": 299, "avg_line_length": 33.64379947229551, "alnum_prop": 0.6850086624221986, "repo_name": "ImageEngine/gaffer", "id": "be77835eafee4fb7a4155131fe68ca63340e2f37", "size": "140261", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/IECoreArnold/Renderer.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "4486" }, { "name": "C++", "bytes": "5353598" }, { "name": "CSS", "bytes": "28027" }, { "name": "GLSL", "bytes": "6250" }, { "name": "Python", "bytes": "5296193" }, { "name": "Shell", "bytes": "8008" }, { "name": "Slash", "bytes": "41159" } ], "symlink_target": "" }
@class FBBezierContour; // FBBezierGraph is more or less an exploded version of an NSBezierPath, and // the two can be converted between easily. FBBezierGraph allows boolean // operations to be performed by allowing the curves to be annotated with // extra information such as where intersections happen. @interface FBBezierGraph : NSObject { NSMutableArray *_contours; NSRect _bounds; } + (id) bezierGraph; + (id) bezierGraphWithBezierPath:(NSBezierPath *)path; - (id) initWithBezierPath:(NSBezierPath *)path; - (FBBezierGraph *) unionWithBezierGraph:(FBBezierGraph *)graph; - (FBBezierGraph *) intersectWithBezierGraph:(FBBezierGraph *)graph; - (FBBezierGraph *) differenceWithBezierGraph:(FBBezierGraph *)graph; - (FBBezierGraph *) xorWithBezierGraph:(FBBezierGraph *)graph; - (NSBezierPath *) bezierPath; @property (readonly) NSArray* contours; - (void) debuggingInsertCrossingsForUnionWithBezierGraph:(FBBezierGraph *)otherGraph; - (void) debuggingInsertCrossingsForIntersectWithBezierGraph:(FBBezierGraph *)otherGraph; - (void) debuggingInsertCrossingsForDifferenceWithBezierGraph:(FBBezierGraph *)otherGraph; - (void) debuggingInsertIntersectionsWithBezierGraph:(FBBezierGraph *)otherGraph; - (NSBezierPath *) debugPathForContainmentOfContour:(FBBezierContour *)contour; - (NSBezierPath *) debugPathForJointsOfContour:(FBBezierContour *)testContour; @end
{ "content_hash": "d9980cb085c92e3d7eafe78c627829c4", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 90, "avg_line_length": 43.125, "alnum_prop": 0.7971014492753623, "repo_name": "adamwulf/vectorboolean", "id": "95cd3cff1ff74c324b33d3e738984cec37fb9264", "size": "1556", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VectorBoolean/FBBezierGraph.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "260875" } ], "symlink_target": "" }
Node module for uploading and downloading javascript files to and from a DOCUMENTS server. ## Warning The API of this will be changed. See [#11](https://github.com/otris/node-documents-scripting/issues/11)
{ "content_hash": "0370ae7022966889165eb515fc0ebff3", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 103, "avg_line_length": 41.6, "alnum_prop": 0.7788461538461539, "repo_name": "otris/node-documents-scripting", "id": "377c953cc199a7f9fe8b7aa3f78daff42f82f958", "size": "236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "58831" } ], "symlink_target": "" }
<?php namespace Oro\Bundle\EntityExtendBundle\Migration; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\QueryBag; use Oro\Bundle\EntityExtendBundle\Migration\Schema\ExtendSchema; use Oro\Bundle\EntityConfigBundle\Tools\CommandExecutor; class UpdateExtendConfigMigration implements Migration { /** * @var CommandExecutor */ protected $commandExecutor; /** * @var string */ protected $configProcessorOptionsPath; /** * @param CommandExecutor $commandExecutor * @param string $configProcessorOptionsPath */ public function __construct(CommandExecutor $commandExecutor, $configProcessorOptionsPath) { $this->commandExecutor = $commandExecutor; $this->configProcessorOptionsPath = $configProcessorOptionsPath; } /** * @inheritdoc */ public function up(Schema $schema, QueryBag $queries) { if ($schema instanceof ExtendSchema) { $queries->addQuery( new UpdateExtendConfigMigrationQuery( $schema->getExtendOptions(), $this->commandExecutor, $this->configProcessorOptionsPath ) ); $queries->addQuery( new RefreshExtendCacheMigrationQuery( $this->commandExecutor ) ); } } }
{ "content_hash": "bab74967353d761e7281f65cfe84f935", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 94, "avg_line_length": 28.056603773584907, "alnum_prop": 0.6200403496973773, "repo_name": "morontt/platform", "id": "de482f7f56432aa0fceb427eb9194169deb02058", "size": "1487", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/Oro/Bundle/EntityExtendBundle/Migration/UpdateExtendConfigMigration.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "567119" }, { "name": "Cucumber", "bytes": "660" }, { "name": "HTML", "bytes": "1298781" }, { "name": "JavaScript", "bytes": "4420161" }, { "name": "PHP", "bytes": "18280313" } ], "symlink_target": "" }
package org.gradle.api.internal.tasks.compile.daemon; import org.gradle.language.base.internal.compile.CompileSpec; import org.gradle.language.base.internal.compile.Compiler; import org.gradle.internal.concurrent.Stoppable; import org.gradle.internal.UncheckedException; import org.gradle.process.internal.WorkerProcess; import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; class CompilerDaemonClient implements CompilerDaemon, CompilerDaemonClientProtocol, Stoppable { private final DaemonForkOptions forkOptions; private final WorkerProcess workerProcess; private final CompilerDaemonServerProtocol server; private final BlockingQueue<CompileResult> compileResults = new SynchronousQueue<CompileResult>(); public CompilerDaemonClient(DaemonForkOptions forkOptions, WorkerProcess workerProcess, CompilerDaemonServerProtocol server) { this.forkOptions = forkOptions; this.workerProcess = workerProcess; this.server = server; } @Override public <T extends CompileSpec> CompileResult execute(Compiler<T> compiler, T spec) { // currently we just allow a single compilation thread at a time (per compiler daemon) // one problem to solve when allowing multiple threads is how to deal with memory requirements specified by compile tasks try { server.execute(compiler, spec); return compileResults.take(); } catch (InterruptedException e) { throw UncheckedException.throwAsUncheckedException(e); } } public boolean isCompatibleWith(DaemonForkOptions required) { return forkOptions.isCompatibleWith(required); } @Override public void stop() { server.stop(); workerProcess.waitForStop(); } @Override public void executed(CompileResult result) { try { compileResults.put(result); } catch (InterruptedException e) { throw UncheckedException.throwAsUncheckedException(e); } } }
{ "content_hash": "1faebcf52e96267671ab52bce1f81951", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 130, "avg_line_length": 37.29090909090909, "alnum_prop": 0.7303754266211604, "repo_name": "HenryHarper/Acquire-Reboot", "id": "4731b0b3f57a17e545b8d32aa89f2a2b29cbcb57", "size": "2666", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gradle/src/language-jvm/org/gradle/api/internal/tasks/compile/daemon/CompilerDaemonClient.java", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
 using UnityEngine; using System.Collections; public class StartSceneUIManager : MonoBehaviour { public TextMesh curADFId; public TextMesh curADFName; // Update is called once per frame void Update () { curADFId.text = Statics.curADFId; curADFName.text = Statics.curADFName; } }
{ "content_hash": "6c4d639798a4788be1c29711ac87fa60", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 50, "avg_line_length": 22.714285714285715, "alnum_prop": 0.6949685534591195, "repo_name": "wschorn/tango-examples-unity", "id": "8083cf03a76d4b511157a9e579de06a975629d42", "size": "936", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "UnityExamples/Assets/TangoExamples/ExperimentalPersistentState/Scripts/GameData/StartSceneUIManager.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "565912" }, { "name": "GLSL", "bytes": "319599" }, { "name": "HTML", "bytes": "51" }, { "name": "Java", "bytes": "91413" }, { "name": "JavaScript", "bytes": "149814" } ], "symlink_target": "" }
#include "Gun.h" #include "GameSettings.h" #include "Snake.h" #include "BoardManager.h" Gun::Gun(BoardManager* the_board): ammo(GUN_AMMO_INITIAL), theBoard(the_board) { bullets.clear(); } Gun::~Gun() { } void Gun::shoot(const Point& pt, int direction) { /* * Creating new bullet if there any ammo left. */ if (ammo > 0) { // Moving the @pt to next point Point ptNew = pt; ptNew.move(direction); // adding bullet the vector. Bullet bul = Bullet(direction, ptNew, theBoard); bullets.push_back(bul); // decreaing ammo size. ammo--; } } void Gun::cleanBullets() { for (Bullet bt : bullets) { bt.remove(); } bullets.clear(); } void Gun::reset() { cleanBullets(); ammo = GUN_AMMO_INITIAL; bullets.clear(); } bool Gun::moveBulletNextPosition(Bullet& bt) { /* * return True when bullet hitted something and need to be removed from game */ Point pos = bt.getNextPosition(); BasePlayerBoard* playerInterceted = theBoard->getPlayerAtPoint(pos); if (playerInterceted != nullptr) { if (!playerInterceted->getIsBulletproof()) { if (playerInterceted->type() == "snake") { Snake* snake = static_cast<Snake*>(playerInterceted); snake->gotHit(); } else { playerInterceted->destroy(); } } return true; } else if (theBoard->removeNumberByPoint(pos)) { return true; } else { bt.doNext(); } return false; } void Gun::doNext() { for (auto bt = bullets.begin(); bt != bullets.end();) { // moving the bullet twice if (moveBulletNextPosition(*bt) || moveBulletNextPosition(*bt)) { bt->remove(); bt = bullets.erase(bt); } else { ++bt; } } }
{ "content_hash": "934addfbefa43857b0ee712ca60e9238", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 78, "avg_line_length": 15.714285714285714, "alnum_prop": 0.636969696969697, "repo_name": "yuri1992/cpp_project", "id": "158604777a380147e7097f84290e0edf63f1f7e7", "size": "1650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Gun.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "955" }, { "name": "C++", "bytes": "53998" }, { "name": "CMake", "bytes": "222" }, { "name": "Objective-C", "bytes": "2524" } ], "symlink_target": "" }
package cz.ivoa.vocloud.view; import cz.ivoa.vocloud.ejb.UWSTypeFacade; import cz.ivoa.vocloud.ejb.UserSessionBean; import cz.ivoa.vocloud.entity.UWSType; import cz.ivoa.vocloud.entity.UserAccount; import cz.ivoa.vocloud.entity.UserGroupName; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Named; import org.primefaces.component.menuitem.UIMenuItem; import org.primefaces.component.submenu.UISubmenu; /** * @author radio.koza */ @Named @RequestScoped public class JobsCreateMenuBean { private UISubmenu jobsCreateSubmenu; @EJB private UWSTypeFacade facade; @EJB private UserSessionBean usb; private Set<String> possibleTypeIds; @PostConstruct private void init() { UserAccount userAcc = usb.getUser(); if (userAcc == null) { //user is not logged in - unnecessary to setup this bean return; } boolean restrictedAccess = userAcc.getGroupName().equals(UserGroupName.ADMIN) || userAcc.getGroupName().equals(UserGroupName.MANAGER); //populate menu List<UWSType> possibleUnrestrictedTypes = facade.findAllowedNonRestrictedTypes(); List<UWSType> possibleRestrictedTypes = facade.findAllowedRestrictedTypes(); if (possibleRestrictedTypes.isEmpty()) { restrictedAccess = false; } possibleTypeIds = new HashSet<>(); jobsCreateSubmenu = new UISubmenu(); jobsCreateSubmenu.setLabel("Create job"); if (!restrictedAccess) { for (UWSType type : possibleUnrestrictedTypes) { possibleTypeIds.add(type.getStringIdentifier()); jobsCreateSubmenu.getChildren().add(constructMenuItem(type)); } } else { UISubmenu basic = new UISubmenu(); basic.setLabel("Standard jobs"); for (UWSType type : possibleUnrestrictedTypes) { possibleTypeIds.add(type.getStringIdentifier()); basic.getChildren().add(constructMenuItem(type)); } jobsCreateSubmenu.getChildren().add(basic); UISubmenu restricted = new UISubmenu(); restricted.setLabel("Restricted jobs"); for (UWSType type : possibleRestrictedTypes) { possibleTypeIds.add(type.getStringIdentifier()); restricted.getChildren().add(constructMenuItem(type)); } jobsCreateSubmenu.getChildren().add(restricted); } } private UIMenuItem constructMenuItem(UWSType type) { UIMenuItem item = new UIMenuItem(); item.setAjax(false); item.setId(type.getStringIdentifier()); item.setValue(type.getShortDescription()); item.setActionExpression(FacesContext.getCurrentInstance().getApplication().getExpressionFactory(). createMethodExpression(FacesContext.getCurrentInstance().getELContext(), "#{jobsCreateMenuBean.navigateToCreateJob('" + type.getStringIdentifier() + "')}", String.class, new Class[]{String.class})); return item; } public UISubmenu getSubmenuBinding() { return this.jobsCreateSubmenu; } public void setSubmenuBinding(UISubmenu submenu) { this.jobsCreateSubmenu = submenu; } public String navigateToCreateJob(String uwsType) { //just to be sure check that it is one of possible types if (!possibleTypeIds.contains(uwsType)) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "This type is no longer possible to invoke", "")); return null; } return "/jobs/create?faces-redirect=true&uwsType=" + uwsType; } }
{ "content_hash": "e9f8ae3b72d96c724ac5d83c12a6d4dc", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 214, "avg_line_length": 38.10679611650485, "alnum_prop": 0.6764331210191082, "repo_name": "vodev/vocloud", "id": "9e176a8c2ed0c6b002098737f36d19fe709df8b7", "size": "3925", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vocloud/src/main/java/cz/ivoa/vocloud/view/JobsCreateMenuBean.java", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "9173" }, { "name": "Gherkin", "bytes": "4756" }, { "name": "HTML", "bytes": "150080" }, { "name": "Java", "bytes": "523696" }, { "name": "JavaScript", "bytes": "60881" } ], "symlink_target": "" }
<!--- Licensed to the Apache Software Foundation (ASF) under one --> <!--- or more contributor license agreements. See the NOTICE file --> <!--- distributed with this work for additional information --> <!--- regarding copyright ownership. The ASF licenses this file --> <!--- to you 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. --> # RNN Example for MXNet Scala This folder contains the following examples writing in new Scala type-safe API: - [x] LSTM Bucketing - [x] CharRNN Inference : Generate similar text based on the model - [x] CharRNN Training: Training the language model using RNN These example is only for Illustration and not modeled to achieve the best accuracy. ## Setup ### Download the Network Definition, Weights and Training Data `obama.zip` contains the training inputs (Obama's speech) for CharCNN examples and `sherlockholmes` contains the data for LSTM Bucketing ```bash https://s3.us-east-2.amazonaws.com/mxnet-scala/scala-example-ci/RNN/obama.zip https://s3.us-east-2.amazonaws.com/mxnet-scala/scala-example-ci/RNN/sherlockholmes.train.txt https://s3.us-east-2.amazonaws.com/mxnet-scala/scala-example-ci/RNN/sherlockholmes.valid.txt ``` ### Unzip the file ```bash unzip obama.zip ``` ### Arguement Configuration Then you need to define the arguments that you would like to pass in the model: #### LSTM Bucketing ```bash --data-train <path>/sherlockholmes.train.txt --data-val <path>/sherlockholmes.valid.txt --cpus <num_cpus> --gpus <num_gpu> ``` #### TrainCharRnn ```bash --data-path <path>/obama.txt --save-model-path <path>/ ``` #### TestCharRnn ```bash --data-path <path>/obama.txt --model-prefix <path>/obama ```
{ "content_hash": "102fc77c4d2df4e0c4c9f56381385868", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 136, "avg_line_length": 33.98461538461538, "alnum_prop": 0.7188773200543233, "repo_name": "mlperf/training_results_v0.7", "id": "2ef2f47c79831296d5b882e133b5824215ee878e", "size": "2209", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/scala-package/examples/src/main/scala/org/apache/mxnetexamples/rnn/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1731" }, { "name": "Awk", "bytes": "14530" }, { "name": "Batchfile", "bytes": "13130" }, { "name": "C", "bytes": "172914" }, { "name": "C++", "bytes": "13037795" }, { "name": "CMake", "bytes": "113458" }, { "name": "CSS", "bytes": "70255" }, { "name": "Clojure", "bytes": "622652" }, { "name": "Cuda", "bytes": "1974745" }, { "name": "Dockerfile", "bytes": "149523" }, { "name": "Groovy", "bytes": "160449" }, { "name": "HTML", "bytes": "171537" }, { "name": "Java", "bytes": "189275" }, { "name": "JavaScript", "bytes": "98224" }, { "name": "Julia", "bytes": "430755" }, { "name": "Jupyter Notebook", "bytes": "11091342" }, { "name": "Lua", "bytes": "17720" }, { "name": "MATLAB", "bytes": "34903" }, { "name": "Makefile", "bytes": "215967" }, { "name": "Perl", "bytes": "1551186" }, { "name": "PowerShell", "bytes": "13906" }, { "name": "Python", "bytes": "36943114" }, { "name": "R", "bytes": "134921" }, { "name": "Raku", "bytes": "7280" }, { "name": "Ruby", "bytes": "4930" }, { "name": "SWIG", "bytes": "140111" }, { "name": "Scala", "bytes": "1304960" }, { "name": "Shell", "bytes": "1312832" }, { "name": "Smalltalk", "bytes": "3497" }, { "name": "Starlark", "bytes": "69877" }, { "name": "TypeScript", "bytes": "243012" } ], "symlink_target": "" }
which git &>/dev/null || return # Shortcut for listing one-line summary of all commits. alias gl='git log --oneline --decorate'
{ "content_hash": "c345efd7c959dad664d3ca256bd84144", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 55, "avg_line_length": 32.25, "alnum_prop": 0.7209302325581395, "repo_name": "princebot/dotfiles", "id": "7329ec5fbb57bd9cf199b78f42fee17122cbbca6", "size": "481", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dotfiles.d/git.bash", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "29899" }, { "name": "Vim script", "bytes": "12529" } ], "symlink_target": "" }
<?php namespace OPNsense\Nginx\Api; use OPNsense\Base\ApiControllerBase; use OPNsense\Core\Backend; use OPNsense\Nginx\Nginx; class LogsController extends ApiControllerBase { private $nginx; public function accessesAction($uuid = null) { $this->nginx = new Nginx(); if (!isset($uuid)) { // emulate REST API -> /accesses delivers a list of servers with access logs return $this->list_vhosts(); } else { // emulate REST call for a specific log /accesses/uuid $this->call_configd('access', $uuid); } } public function errorsAction($uuid = null) { $this->nginx = new Nginx(); if (!isset($uuid)) { // emulate REST API -> /errors delivers a list of servers with error logs return $this->list_vhosts(); } else { // emulate REST call for a specific log /errors/uuid $this->call_configd('error', $uuid); } } public function stream_accessesAction($uuid = null) { $this->nginx = new Nginx(); if (!isset($uuid)) { // emulate REST API -> /stream_accesses delivers a list of servers with access logs return $this->list_streams(); } else { // emulate REST call for a specific log /stream_accesses/uuid $this->call_configd_stream('streamaccess', $uuid); } } public function stream_errorsAction($uuid = null) { $this->nginx = new Nginx(); if (!isset($uuid)) { // emulate REST API -> /stream_errors delivers a list of servers with error logs return $this->list_streams(); } else { // emulate REST call for a specific log /stream_errors/uuid $this->call_configd_stream('streamerror', $uuid); } } private function call_configd($type, $uuid) { if (!$this->vhost_exists($uuid)) { $this->response->setStatusCode(404, "Not Found"); } return $this->sendConfigdToClient('nginx log ' . $type . ' ' . $uuid); } private function call_configd_stream($type, $uuid) { if (!$this->stream_exists($uuid)) { $this->response->setStatusCode(404, "Not Found"); } return $this->sendConfigdToClient('nginx log ' . $type . ' ' . $uuid); } private function list_vhosts() { $data = []; foreach ($this->nginx->http_server->iterateItems() as $item) { $data[] = array('id' => $item->getAttributes()['uuid'], 'server_name' => (string)$item->servername); } return $data; } private function list_streams() { $data = []; foreach ($this->nginx->stream_server->iterateItems() as $item) { $data[] = array('id' => $item->getAttributes()['uuid'], 'port' => (string)$item->listen_port); } return $data; } private function vhost_exists($uuid) { $data = $this->nginx->getNodeByReference('http_server.'. $uuid); return isset($data); } private function stream_exists($uuid) { $data = $this->nginx->getNodeByReference('stream_server.'. $uuid); return isset($data); } /** * @param $command String JSON generating configd command * @return null * @throws \Exception ? */ private function sendConfigdToClient($command) { $backend = new Backend(); // must be passed directly -> OOM Problem $this->response->setContent($backend->configdRun($command)); $this->response->setStatusCode(200, "OK"); $this->response->setContentType('application/json', 'UTF-8'); return $this->response->send(); } }
{ "content_hash": "e2378555839c45703aaa7bfaa6963c13", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 112, "avg_line_length": 31.325, "alnum_prop": 0.5605214152700186, "repo_name": "fabianfrz/plugins", "id": "75bba032cc3734fef117ac3a145fb994d5bcde33", "size": "5074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/nginx/src/opnsense/mvc/app/controllers/OPNsense/Nginx/Api/LogsController.php", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "1013615" }, { "name": "HTML", "bytes": "32663" }, { "name": "JavaScript", "bytes": "1104047" }, { "name": "Makefile", "bytes": "29734" }, { "name": "Mathematica", "bytes": "286" }, { "name": "PHP", "bytes": "1523186" }, { "name": "Perl", "bytes": "3686" }, { "name": "Python", "bytes": "33405" }, { "name": "Ruby", "bytes": "61798" }, { "name": "Shell", "bytes": "37807" }, { "name": "SourcePawn", "bytes": "625" }, { "name": "Volt", "bytes": "627790" } ], "symlink_target": "" }
<?php /** * User: Kevin Blenner * Date: 27/03/2015 */ namespace Kid\KidBundle\Validateur; use Kid\KidBundle\Entity\Participant; use Symfony\Component\Translation\TranslatorInterface; /** * Class ParticipantValidateur * @package Kid\KidBundle\Validateur */ class ParticipantValidateur extends Validateur{ public function __construct(TranslatorInterface $translatorInterface){ parent::__construct($translatorInterface); } /** * @author Kevin Blenner * @since 27/03/2015 Création * Fonction permettant la validation de l'objet par ses règles métiers. * @param Participant $poParticipant * @return ResultatTestObjet */ public function valider(Participant $poParticipant){ #->Vérification des arguments if (!$poParticipant) { $this->getResultatTestObjet()->setEstValide(false); } #->Déclaration des variables #->Traitement de la fonction if ($poParticipant->getListDepense()->count() > 0) { $this->getResultatTestObjet()->addMessageErreur($this->translator->trans('ERREUR_VALIDATION_DEPENSE_PARTICIPANT')); } if ($poParticipant->getListDepenseBeneficiaire()->count() > 0) { $this->getResultatTestObjet()->addMessageErreur($this->translator->trans('ERREUR_VALIDATION_DEPENSE_PARTICIPANT_BENEFICIAIRE')); } #->Retour de la fonction return $this->getResultatTestObjet(); } }
{ "content_hash": "f99e272fbbde8ad2c10684610b649c21", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 140, "avg_line_length": 30.163265306122447, "alnum_prop": 0.6644113667117727, "repo_name": "SwagOverflow/kidoikoiaki", "id": "7d49367b9095625bf6fe79f1a2a657a8b873cf23", "size": "1483", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/Kid/KidBundle/Validateur/ParticipantValidateur.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "143" }, { "name": "CSS", "bytes": "36079" }, { "name": "HTML", "bytes": "221996" }, { "name": "JavaScript", "bytes": "127528" }, { "name": "PHP", "bytes": "174681" } ], "symlink_target": "" }
The TwoBasedIndexing.jl package is licensed under the MIT "Expat" License: > Copyright (c) 2015: Simon Kornblith. > > 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.
{ "content_hash": "79241c7fa683543a71009cda13488e1b", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 74, "avg_line_length": 53.36363636363637, "alnum_prop": 0.7793867120954003, "repo_name": "simonster/TwoBasedIndexing.jl", "id": "691dfdf6580782eca8a751db022633ab2df48ef9", "size": "1174", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "LICENSE.md", "mode": "33188", "license": "mit", "language": [ { "name": "Julia", "bytes": "880" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using CodeGeneration.Roslyn; using LanguageExt.CodeGen; namespace LanguageExt { /// <summary> /// Union attribute /// </summary> [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class, Inherited = false, AllowMultiple = false)] [CodeGenerationAttribute(typeof(RecordGenerator))] [Conditional("CodeGeneration")] public class RecordAttribute : Attribute { } }
{ "content_hash": "de67141bce15cf6e7cd3a1e75b43dbfb", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 112, "avg_line_length": 26.263157894736842, "alnum_prop": 0.7334669338677354, "repo_name": "StefanBertels/language-ext", "id": "6f5b6f4dff564d8982ce39f1ac16b2db63908eab", "size": "501", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "LanguageExt.CodeGen/RecordAttribute.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "350" }, { "name": "C#", "bytes": "16819927" } ], "symlink_target": "" }
 using MindTouch.Xml; using NUnit.Framework; namespace MindTouch.Dream.Test { [TestFixture] public class JsonUtilTests { [Test] public void Can_convert_doc_to_json() { var doc = new XDoc("x").Elem("foo", "bar"); Assert.AreEqual("{\"foo\":\"bar\"}",doc.ToJson()); } [Test] public void Will_not_escape_single_quote() { var doc = new XDoc("x").Value("F'oo"); Assert.AreEqual("\"F'oo\"", doc.ToJson()); } [Test] public void Will_escape_double_quote() { var doc = new XDoc("foo").Value("\"Foo\""); Assert.AreEqual("\"\\\"Foo\\\"\"", doc.ToJson()); } [Test] public void Will_escape_backslash_quote() { var doc = new XDoc("foo").Value("backslash: \\"); Assert.AreEqual("\"backslash: \\\\\"", doc.ToJson()); } [Test] public void Will_escape_backspace_quote() { var doc = new XDoc("foo").Value("backspace: \b"); Assert.AreEqual("\"backspace: \\b\"", doc.ToJson()); } [Test] public void Will_escape_formfeed_quote() { var doc = new XDoc("foo").Value("formfeed: \f"); Assert.AreEqual("\"formfeed: \\f\"", doc.ToJson()); } [Test] public void Will_escape_newline_quote() { var doc = new XDoc("foo").Value("newline: \n"); Assert.AreEqual("\"newline: \\n\"", doc.ToJson()); } [Test] public void Will_escape_carriage_return_quote() { var doc = new XDoc("foo").Value("carriage return: \r"); Assert.AreEqual("\"carriage return: \\r\"", doc.ToJson()); } [Test] public void Will_escape_tab_quote() { var doc = new XDoc("foo").Value("tab: \t"); Assert.AreEqual("\"tab: \\t\"", doc.ToJson()); } [Test] public void Will_escape_hex_quote() { var doc = new XDoc("foo").Value("hex: \u4f4f"); Assert.AreEqual("\"hex: \\u4f4f\"", doc.ToJson()); } } }
{ "content_hash": "b3f1197cde9f8cd48aa3cdd8326a0b43", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 70, "avg_line_length": 31.4, "alnum_prop": 0.4754322111010009, "repo_name": "PeteE/DReAM", "id": "8877f2bd62da2253bb91fdc727ba6a1f2817e0a9", "size": "3028", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/tests/DreamMisc/JsonUtilTests.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "3768397" }, { "name": "PowerShell", "bytes": "14891" }, { "name": "XSLT", "bytes": "474" } ], "symlink_target": "" }
<?php namespace JX\Twypo; class TwigContentObjectRender { const CONTENT_OBJECT_NAME = 'TWIG_CONTENT'; private $cObj = null; public function cObjGetSingleExt( $name, $conf, $TSkey, $parent ) { global $TSFE, $TWYPO; $this->cObj = $parent; // Get current page info $pageData = $TSFE->page; $page = array( 'title' => $pageData['title'], 'subtitle' => $pageData['subtitle'], 'url' => $TWYPO->get('baseUrl') . $TWYPO->get('currentPageUrl'), 'meta' => array( 'keywords' => $pageData['keywords'], 'description' => $pageData['description'], 'abstract' => $pageData['abstract'] ) ); $TWYPO->assign('page', $page); // Get current page layout $TWYPO->assignInternal('pageLayout', $pageData['layout'] ); // Get current page items and push to the array $colMapping = $TWYPO->getInternal('colMapping'); $items = $TWYPO->renderConf( $conf ); $content = array(); if( count($items) > 0 ) { foreach($items as $item) { if ( !isset($content[ $colMapping[intval($item['colPos'])] ]) ) $content[ $colMapping[intval($item['colPos'])] ] = array(); array_push($content[ $colMapping[intval($item['colPos'])] ], array( 'title' => $item['header'], 'text' => $this->parseRTE( $item['bodytext'] ), 'link' => array( 'url' => $this->getLink( $item['header_link'], 'url' ), 'target' => $this->getLink( $item['header_link'], 'target' ) ), 'files' => $this->getFiles($item['uid']) )); } } $TWYPO->assign('content', $content); } // Utility // @part = url|target private function getLink($link, $part = 'url') { return $this->cObj->typoLink( $link, array( 'parameter' => $link, 'forceAbsoluteUrl' => true, 'returnLast' => 'url' )); } private function parseRTE($text) { global $TSFE; $ret = ''; $parseFunc = $TSFE->tmpl->setup['lib.']['parseFunc_RTE.']; if ( is_array($parseFunc) ) $ret = $this->cObj->parseFunc($text, $parseFunc); return $ret; } /* Snippet got from Official WIKI documentation. @ref: http://wiki.typo3.org/File_Abstraction_Layer */ private function getFiles($uid, $conf) { global $TWYPO; $ret = array(); $fileRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\FileRepository'); $fileObjects = $fileRepository->findByRelation('tt_content', 'image', $uid); $files = array(); foreach ($fileObjects as $file) { array_push( $ret, array( 'url' => $TWYPO->get('baseUrl') . $file->getPublicUrl(), 'type' => $file->getType(), 'mime' => $file->getMimeType(), 'title' => $file->getTitle(), 'description' => $file->getDescription(), 'extension' => $file->getExtension(), 'missing' => $file->isMissing() )); } return $ret; } }
{ "content_hash": "681bbe5216ae2d70733f65440c9a9372", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 119, "avg_line_length": 27.107843137254903, "alnum_prop": 0.6010849909584087, "repo_name": "julianxhokaxhiu/twypo", "id": "6d33ca79a91740ce827027d7581baa60d86ef2d3", "size": "3870", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Classes/TwigContentObjectRender.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23" }, { "name": "JavaScript", "bytes": "119" }, { "name": "PHP", "bytes": "20910" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:layout_gravity="center" android:src="@drawable/potato_logo" android:contentDescription="@string/logo_descr"/> <Space android:layout_width="15dp" android:layout_height="fill_parent" /> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:layout_width="210dp" android:layout_height="wrap_content" android:text="@string/new_crossword" android:id="@+id/new_crossword_button" android:layout_gravity="center_horizontal" android:onClick="newCrossword"/> <Button android:layout_width="210dp" android:layout_height="wrap_content" android:text="@string/resume" android:id="@+id/resume_button" android:layout_gravity="center_horizontal" android:onClick="resumeCrossword"/> <Button android:layout_width="210dp" android:layout_height="wrap_content" android:text="@string/exit" android:id="@+id/exit_button" android:layout_gravity="center_horizontal" android:onClick="exit"/> </LinearLayout> </LinearLayout>
{ "content_hash": "759fdf3b440e4a5fc16af46eee609835", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 72, "avg_line_length": 35, "alnum_prop": 0.5893557422969188, "repo_name": "nikoblag/potato", "id": "55d8f44b9da09a6a58572e0200c0b0629a633b5a", "size": "1785", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/layout-land/activity_main.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "95668" } ], "symlink_target": "" }
SPEC_BEGIN(HNKGooglePlacesAutocompleteQueryConfigSpec) describe(@"HNKGooglePlacesAutocompleteQueryConfig", ^{ describe(@"configWithConfig", ^{ __block HNKGooglePlacesAutocompleteQueryConfig *testInstance; beforeEach(^{ HNKGooglePlacesAutocompleteQueryConfig *testConfig = [[HNKGooglePlacesAutocompleteQueryConfig alloc] init]; testConfig.country = @"fr"; testConfig.filter = HNKGooglePlaceTypeAutocompleteFilterCity; testConfig.language = @"pt"; testConfig.latitude = 100; testConfig.longitude = 50; testConfig.offset = 3; testConfig.searchRadius = 100000; testInstance = [HNKGooglePlacesAutocompleteQueryConfig configWithConfig:testConfig]; }); it(@"Should return a new config with same config values", ^{ [[testInstance.country should] equal:@"fr"]; [[theValue(testInstance.filter) should] equal:theValue(HNKGooglePlaceTypeAutocompleteFilterCity)]; [[testInstance.language should] equal:@"pt"]; [[theValue(testInstance.latitude) should] equal:theValue(100)]; [[theValue(testInstance.longitude) should] equal:theValue(50)]; [[theValue(testInstance.offset) should] equal:theValue(3)]; [[theValue(testInstance.searchRadius) should] equal:theValue(100000)]; }); }); describe(@"defaultConfig", ^{ it(@"Should have default config values", ^{ HNKGooglePlacesAutocompleteQueryConfig *defaultConfig = [HNKGooglePlacesAutocompleteQueryConfig defaultConfig]; [[defaultConfig.country should] beNil]; [[theValue(defaultConfig.filter) should] equal:theValue(HNKGooglePlaceTypeAutocompleteFilterAll)]; [[defaultConfig.language should] beNil]; [[theValue(defaultConfig.latitude) should] equal:theValue(0)]; [[theValue(defaultConfig.longitude) should] equal:theValue(0)]; [[theValue(defaultConfig.offset) should] equal:theValue(NSNotFound)]; [[theValue(defaultConfig.searchRadius) should] equal:theValue(20000000)]; }); }); describe(@"translateToServerRequestParameters", ^{ context(@"Latitude and longitude set to 0", ^{ __block HNKGooglePlacesAutocompleteQueryConfig *testInstanceNoLocation; beforeEach(^{ testInstanceNoLocation = [[HNKGooglePlacesAutocompleteQueryConfig alloc] init]; testInstanceNoLocation.country = @"abc"; testInstanceNoLocation.filter = HNKGooglePlaceTypeAutocompleteFilterRegion; testInstanceNoLocation.language = @"def"; testInstanceNoLocation.latitude = 0; testInstanceNoLocation.longitude = 0; testInstanceNoLocation.offset = 100; testInstanceNoLocation.searchRadius = 1000; }); it(@"Should not include location in parameters", ^{ NSDictionary *params = [testInstanceNoLocation translateToServerRequestParameters]; [[params should] equal:@{ @"components" : @"country:abc", @"language" : @"def", @"offset" : @(100), @"radius" : @(1000), @"types" : @"(regions)" }]; }); }); context(@"Latitude and Longitude set", ^{ it(@"Should return correct dictionary", ^{ HNKGooglePlacesAutocompleteQueryConfig *testInstance = [[HNKGooglePlacesAutocompleteQueryConfig alloc] init]; testInstance = [[HNKGooglePlacesAutocompleteQueryConfig alloc] init]; testInstance.country = nil; testInstance.filter = HNKGooglePlaceTypeAutocompleteFilterAll; testInstance.language = nil; testInstance.latitude = 0; testInstance.longitude = 0; testInstance.offset = NSNotFound; testInstance.searchRadius = NSNotFound; NSDictionary *params = [testInstance translateToServerRequestParameters]; [[params should] equal:@{}]; testInstance.latitude = 50.5; testInstance.longitude = 150.5; params = [testInstance translateToServerRequestParameters]; [[params should] equal:@{ @"location" : @"50.500000,150.500000" }]; testInstance.country = @"abc"; testInstance.language = @"def"; params = [testInstance translateToServerRequestParameters]; [[params should] equal:@{ @"components" : @"country:abc", @"language" : @"def", @"location" : @"50.500000,150.500000" }]; testInstance.offset = 100; testInstance.searchRadius = 1000; params = [testInstance translateToServerRequestParameters]; [[params should] equal:@{ @"components" : @"country:abc", @"language" : @"def", @"location" : @"50.500000,150.500000", @"offset" : @(100), @"radius" : @(1000) }]; testInstance.filter = HNKGooglePlaceTypeAutocompleteFilterRegion; params = [testInstance translateToServerRequestParameters]; [[params should] equal:@{ @"components" : @"country:abc", @"language" : @"def", @"location" : @"50.500000,150.500000", @"offset" : @(100), @"radius" : @(1000), @"types" : @"(regions)" }]; }); }); }); }); SPEC_END
{ "content_hash": "d036a2f15194eca3bf62fe90a8e9e304", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 123, "avg_line_length": 46.34355828220859, "alnum_prop": 0.44519459888800633, "repo_name": "anandmahajan/HNKGooglePlacesAutocomplete", "id": "e8f4e3855cb632eb007a25a8536b83c47699b141", "size": "7843", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "Example/HNKGooglePlacesAutocomplete-ExampleTests/HNKGooglePlacesAutocompleteQueryConfigSpec.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "30926" }, { "name": "Objective-C", "bytes": "1196137" }, { "name": "Ruby", "bytes": "2009" }, { "name": "Shell", "bytes": "9174" } ], "symlink_target": "" }
<dc:title>KPMG LLP v. COCCHI</dc:title> <dc:language>en-US</dc:language> <dc:creator opf:file-as="NYPL" opf:role="aut">NYPL</dc:creator> <dc:publisher>NYPL</dc:publisher> <dc:date opf:event="publication">2015-01-15</dc:date> <dc:rights>Copyright ©2015 by Cornell Law and NYPL</dc:rights>
{ "content_hash": "d99c9ac3fe8809bdc8b18a9edda4f33a", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 63, "avg_line_length": 47.833333333333336, "alnum_prop": 0.7317073170731707, "repo_name": "riordan/judiciary_ebooks", "id": "a164e693bf3ce28ccc8013231fa8da096485056a", "size": "288", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "titles/10-1521/metadata.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "438" }, { "name": "Python", "bytes": "734" }, { "name": "Ruby", "bytes": "2588" } ], "symlink_target": "" }
import { report, ruleMessages, styleSearch, validateOptions, } from "../../utils" export const ruleName = "color-hex-case" export const messages = ruleMessages(ruleName, { expected: (actual, expected) => `Expected "${actual}" to be "${expected}"`, }) export default function (expectation) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: expectation, possible: [ "lower", "upper", ], }) if (!validOptions) { return } root.walkDecls(decl => { const declString = decl.toString() styleSearch({ source: declString, target: "#" }, match => { const hexMatch = /^#[0-9A-Za-z]+/.exec(declString.substr(match.startIndex)) if (!hexMatch) { return } const hexValue = hexMatch[0] const hexValueLower = hexValue.toLowerCase() const hexValueUpper = hexValue.toUpperCase() const expectedHex = expectation === "lower" ? hexValueLower : hexValueUpper if (hexValue === expectedHex) { return } report({ message: messages.expected(hexValue, expectedHex), node: decl, index: match.startIndex, result, ruleName, }) }) }) } }
{ "content_hash": "96c990ffa253728493aa051865ee72db", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 83, "avg_line_length": 25.79591836734694, "alnum_prop": 0.5925632911392406, "repo_name": "evilebottnawi/stylelint", "id": "1c920bad005faff3bf11e06e4631bfa0f6cbcbef", "size": "1264", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/rules/color-hex-case/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "317" }, { "name": "JavaScript", "bytes": "1076070" }, { "name": "Shell", "bytes": "188" } ], "symlink_target": "" }
<?php /* Safe sample input : use exec to execute the script /tmp/tainted.php and store the output in $tainted sanitize : use of the function htmlentities. Sanitizes the query but has a high chance to produce unexpected results construction : interpretation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $script = "/tmp/tainted.php"; exec($script, $result, $return); $tainted = $result[0]; $tainted = htmlentities($tainted, ENT_QUOTES); $query = "SELECT * FROM ' $tainted '"; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
{ "content_hash": "e198944e05d975eac777b09f1dff8d6f", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 123, "avg_line_length": 25.757575757575758, "alnum_prop": 0.7458823529411764, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "5d7003617f3d37fc4f5747f9d492640bdc8295f3", "size": "1700", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Injection/CWE_89/safe/CWE_89__exec__func_htmlentities__select_from-interpretation_simple_quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
// ----- this file has been automatically generated - do not edit /** * | | | * |-----------|--------------------------------------------------| * | namespace |http://opcfoundation.org/UA/CommercialKitchenEquipment/| * | nodeClass |DataType | * | name |5:SpecialCookingModeEnumeration | * | isAbstract|false | */ export enum EnumSpecialCookingMode { NoSpecialMode = 0, Baking = 1, SousVide = 2, RestStage = 3, Humidification = 4, PerfectHold = 5, InfoStep = 6, Smoking = 7, "LowTemp-Cooking" = 8, DeltaTSteaming = 9, }
{ "content_hash": "d863e07d7ca7243e6edc6faa0f4d73db", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 72, "avg_line_length": 32.45454545454545, "alnum_prop": 0.4411764705882353, "repo_name": "node-opcua/node-opcua", "id": "39ef4fb50119aeaaf62fe3166c3e3650667fe15c", "size": "714", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/node-opcua-nodeset-commercial-kitchen-equipment/source/enum_special_cooking_mode.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2277" }, { "name": "Dockerfile", "bytes": "460" }, { "name": "JavaScript", "bytes": "2558006" }, { "name": "Makefile", "bytes": "2119" }, { "name": "Shell", "bytes": "4981" }, { "name": "TypeScript", "bytes": "8392344" }, { "name": "XSLT", "bytes": "5379" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>intermol.forces.three_fad_virtual_type &mdash; InterMol 0.2a1 documentation</title> <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" /> <link rel="top" title="InterMol 0.2a1 documentation" href="../../../index.html"/> <link rel="up" title="Module code" href="../../index.html"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"></script> </head> <body class="wy-body-for-nav" role="document"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-nav-search"> <a href="../../../index.html" class="fa fa-home"> InterMol</a> <div role="search"> <form id ="rtd-search-form" class="wy-form" action="../../../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <ul> <li class="toctree-l1"><a class="reference internal" href="../../../installation.html">Installation</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../../installation.html#install-with-pip-coming-soon">Install with pip (coming soon!)</a></li> <li class="toctree-l2"><a class="reference internal" href="../../../installation.html#install-from-source">Install from source</a></li> <li class="toctree-l2"><a class="reference internal" href="../../../installation.html#dependencies">Dependencies</a></li> </ul> </li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="../../../development.html">Contributing</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../../development.html#bug-reports">Bug Reports</a></li> <li class="toctree-l2"><a class="reference internal" href="../../../development.html#code-style">Code Style</a></li> <li class="toctree-l2"><a class="reference internal" href="../../../development.html#running-our-tests">Running our tests</a></li> <li class="toctree-l2"><a class="reference internal" href="../../../development.html#git-flow">Git Flow</a></li> </ul> </li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="../../../apidoc/intermol.html">intermol package</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../../apidoc/intermol.html#subpackages">Subpackages</a></li> <li class="toctree-l2"><a class="reference internal" href="../../../apidoc/intermol.html#submodules">Submodules</a></li> <li class="toctree-l2"><a class="reference internal" href="../../../apidoc/intermol.html#module-intermol">Module contents</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../../apidoc/intermol.gromacs.html">intermol.gromacs package</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../../apidoc/intermol.gromacs.html#submodules">Submodules</a></li> <li class="toctree-l2"><a class="reference internal" href="../../../apidoc/intermol.gromacs.html#module-intermol.gromacs">Module contents</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../../apidoc/intermol.lammps.html">intermol.lammps package</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../../apidoc/intermol.lammps.html#submodules">Submodules</a></li> <li class="toctree-l2"><a class="reference internal" href="../../../apidoc/intermol.lammps.html#module-intermol.lammps">Module contents</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../../apidoc/intermol.forces.html">intermol.forces package</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../../apidoc/intermol.forces.html#submodules">Submodules</a></li> <li class="toctree-l2"><a class="reference internal" href="../../../apidoc/intermol.forces.html#module-intermol.forces">Module contents</a></li> </ul> </li> </ul> </div> &nbsp; </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" role="navigation" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../../../index.html">InterMol</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="../../../index.html">Docs</a> &raquo;</li> <li><a href="../../index.html">Module code</a> &raquo;</li> <li>intermol.forces.three_fad_virtual_type</li> <li class="wy-breadcrumbs-aside"> </li> </ul> <hr/> </div> <div role="main"> <h1>Source code for intermol.forces.three_fad_virtual_type</h1><div class="highlight"><pre> <span class="kn">import</span> <span class="nn">simtk.unit</span> <span class="kn">as</span> <span class="nn">units</span> <span class="kn">from</span> <span class="nn">intermol.decorators</span> <span class="kn">import</span> <span class="n">accepts_compatible_units</span> <span class="kn">from</span> <span class="nn">abstract_3_virtual_type</span> <span class="kn">import</span> <span class="n">Abstract3VirtualType</span> <div class="viewcode-block" id="ThreeFadVirtualType"><a class="viewcode-back" href="../../../apidoc/intermol.forces.three_fad_virtual_type.html#intermol.forces.three_fad_virtual_type.ThreeFadVirtualType">[docs]</a><span class="k">class</span> <span class="nc">ThreeFadVirtualType</span><span class="p">(</span><span class="n">Abstract3VirtualType</span><span class="p">):</span> <span class="n">__slots__</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;theta&#39;</span><span class="p">,</span> <span class="s">&#39;d&#39;</span><span class="p">,</span> <span class="s">&#39;placeholder&#39;</span><span class="p">]</span> <span class="nd">@accepts_compatible_units</span><span class="p">(</span><span class="bp">None</span><span class="p">,</span> <span class="bp">None</span><span class="p">,</span> <span class="bp">None</span><span class="p">,</span> <span class="bp">None</span><span class="p">,</span> <span class="n">theta</span><span class="o">=</span><span class="n">units</span><span class="o">.</span><span class="n">degrees</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="n">units</span><span class="o">.</span><span class="n">nanometers</span><span class="p">,</span> <span class="n">placeholder</span><span class="o">=</span><span class="bp">None</span><span class="p">)</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bondingtype1</span><span class="p">,</span> <span class="n">bondingtype2</span><span class="p">,</span> <span class="n">bondingtype3</span><span class="p">,</span> <span class="n">bondingtype4</span><span class="p">,</span> <span class="n">theta</span><span class="o">=</span><span class="mf">0.0</span> <span class="o">*</span> <span class="n">units</span><span class="o">.</span><span class="n">degrees</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="mf">0.0</span> <span class="o">*</span> <span class="n">units</span><span class="o">.</span><span class="n">nanometers</span><span class="p">,</span> <span class="n">placeholder</span><span class="o">=</span><span class="bp">False</span><span class="p">):</span> <span class="n">Abstract3VirtualType</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bondingtype1</span><span class="p">,</span> <span class="n">bondingtype2</span><span class="p">,</span> <span class="n">bondingtype3</span><span class="p">,</span> <span class="n">bondingtype4</span><span class="p">,</span> <span class="n">placeholder</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">theta</span> <span class="o">=</span> <span class="n">theta</span> <span class="bp">self</span><span class="o">.</span><span class="n">d</span> <span class="o">=</span> <span class="n">d</span> </div> <div class="viewcode-block" id="ThreeFadVirtual"><a class="viewcode-back" href="../../../apidoc/intermol.forces.three_fad_virtual_type.html#intermol.forces.three_fad_virtual_type.ThreeFadVirtual">[docs]</a><span class="k">class</span> <span class="nc">ThreeFadVirtual</span><span class="p">(</span><span class="n">ThreeFadVirtualType</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> stub documentation</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">atom1</span><span class="p">,</span> <span class="n">atom2</span><span class="p">,</span> <span class="n">atom3</span><span class="p">,</span> <span class="n">atom4</span><span class="p">,</span> <span class="n">bondingtype1</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">bondingtype2</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">bondingtype3</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">bondingtype4</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">theta</span><span class="o">=</span><span class="mf">0.0</span> <span class="o">*</span> <span class="n">units</span><span class="o">.</span><span class="n">degrees</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="mf">0.0</span> <span class="o">*</span> <span class="n">units</span><span class="o">.</span><span class="n">nanometers</span><span class="p">,</span> <span class="n">placeholder</span><span class="o">=</span><span class="bp">False</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">atom1</span> <span class="o">=</span> <span class="n">atom1</span> <span class="bp">self</span><span class="o">.</span><span class="n">atom2</span> <span class="o">=</span> <span class="n">atom2</span> <span class="bp">self</span><span class="o">.</span><span class="n">atom3</span> <span class="o">=</span> <span class="n">atom3</span> <span class="bp">self</span><span class="o">.</span><span class="n">atom4</span> <span class="o">=</span> <span class="n">atom4</span> <span class="n">ThreeFadVirtualType</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bondingtype1</span><span class="p">,</span> <span class="n">bondingtype2</span><span class="p">,</span> <span class="n">bondingtype3</span><span class="p">,</span> <span class="n">bondingtype4</span><span class="p">,</span> <span class="n">theta</span><span class="o">=</span><span class="n">theta</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="n">d</span><span class="p">,</span> <span class="n">placeholder</span><span class="o">=</span><span class="n">placeholder</span><span class="p">)</span></div> </pre></div> </div> <footer> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2015, Christoph Klein, Christopher Lee, Ellen Zhong, and Michael Shirts. </p> </div> <a href="https://github.com/snide/sphinx_rtd_theme">Sphinx theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a> </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'../../../', VERSION:'0.2a1', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../../../_static/jquery.js"></script> <script type="text/javascript" src="../../../_static/underscore.js"></script> <script type="text/javascript" src="../../../_static/doctools.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="../../../_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); </script> </body> </html>
{ "content_hash": "7420aad6cb5f2486073c01a407ea9152", "timestamp": "", "source": "github", "line_count": 227, "max_line_length": 800, "avg_line_length": 60.13215859030837, "alnum_prop": 0.6176556776556776, "repo_name": "shirtsgroup/InterMol", "id": "afbd3013fd9bc0a47efe3c91df24749db47eb31d", "size": "13652", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "doc/_build/html/_modules/intermol/forces/three_fad_virtual_type.html", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "602113" }, { "name": "Shell", "bytes": "723" } ], "symlink_target": "" }
package org.elasticsearch.index.engine; import org.apache.logging.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.codecs.Codec; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.document.StoredField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.FilterDirectoryReader; import org.apache.lucene.index.FilterLeafReader; import org.apache.lucene.index.IndexCommit; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.LiveIndexWriterConfig; import org.apache.lucene.index.MergePolicy; import org.apache.lucene.index.NumericDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.ReferenceManager; import org.apache.lucene.search.ScoreMode; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TotalHitCountCollector; import org.apache.lucene.search.Weight; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.FixedBitSet; import org.elasticsearch.Version; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.support.replication.ReplicationResponse; import org.elasticsearch.cluster.ClusterModule; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.routing.AllocationId; import org.elasticsearch.common.CheckedBiFunction; import org.elasticsearch.common.CheckedFunction; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Randomness; import org.elasticsearch.common.Strings; import org.elasticsearch.common.breaker.CircuitBreaker; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.lucene.uid.Versions; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexModule; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.MapperTestUtils; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.codec.CodecService; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.IdFieldMapper; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.Mapping; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.ParsedDocument; import org.elasticsearch.index.mapper.SeqNoFieldMapper; import org.elasticsearch.index.mapper.SourceFieldMapper; import org.elasticsearch.index.mapper.SourceToParse; import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.mapper.VersionFieldMapper; import org.elasticsearch.index.seqno.LocalCheckpointTracker; import org.elasticsearch.index.seqno.ReplicationTracker; import org.elasticsearch.index.seqno.RetentionLeases; import org.elasticsearch.index.seqno.SequenceNumbers; import org.elasticsearch.index.shard.SearcherHelper; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.store.Store; import org.elasticsearch.index.translog.Translog; import org.elasticsearch.index.translog.TranslogConfig; import org.elasticsearch.index.translog.TranslogDeletionPolicy; import org.elasticsearch.indices.breaker.CircuitBreakerService; import org.elasticsearch.indices.breaker.NoneCircuitBreakerService; import org.elasticsearch.test.DummyShardLock; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.IndexSettingsModule; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; import org.junit.After; import org.junit.Before; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.LongSupplier; import java.util.function.Supplier; import java.util.function.ToLongBiFunction; import java.util.stream.Collectors; import static java.util.Collections.emptyList; import static java.util.Collections.shuffle; import static org.elasticsearch.index.engine.Engine.Operation.Origin.PEER_RECOVERY; import static org.elasticsearch.index.engine.Engine.Operation.Origin.PRIMARY; import static org.elasticsearch.index.engine.Engine.Operation.Origin.REPLICA; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.notNullValue; public abstract class EngineTestCase extends ESTestCase { protected final ShardId shardId = new ShardId(new Index("index", "_na_"), 0); protected final AllocationId allocationId = AllocationId.newInitializing(); protected static final IndexSettings INDEX_SETTINGS = IndexSettingsModule.newIndexSettings("index", Settings.EMPTY); protected ThreadPool threadPool; protected TranslogHandler translogHandler; protected Store store; protected Store storeReplica; protected InternalEngine engine; protected InternalEngine replicaEngine; protected IndexSettings defaultSettings; protected String codecName; protected Path primaryTranslogDir; protected Path replicaTranslogDir; // A default primary term is used by engine instances created in this test. protected final PrimaryTermSupplier primaryTerm = new PrimaryTermSupplier(1L); protected static void assertVisibleCount(Engine engine, int numDocs) throws IOException { assertVisibleCount(engine, numDocs, true); } protected static void assertVisibleCount(Engine engine, int numDocs, boolean refresh) throws IOException { if (refresh) { engine.refresh("test"); } try (Engine.Searcher searcher = engine.acquireSearcher("test")) { final TotalHitCountCollector collector = new TotalHitCountCollector(); searcher.search(new MatchAllDocsQuery(), collector); assertThat(collector.getTotalHits(), equalTo(numDocs)); } } protected Settings indexSettings() { // TODO randomize more settings return Settings.builder() .put(IndexSettings.INDEX_GC_DELETES_SETTING.getKey(), "1h") // make sure this doesn't kick in on us .put(EngineConfig.INDEX_CODEC_SETTING.getKey(), codecName) .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT) .put(IndexSettings.MAX_REFRESH_LISTENERS_PER_SHARD.getKey(), between(10, 10 * IndexSettings.MAX_REFRESH_LISTENERS_PER_SHARD.get(Settings.EMPTY))) .put(IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING.getKey(), between(0, 1000)) .build(); } @Override @Before public void setUp() throws Exception { super.setUp(); primaryTerm.set(randomLongBetween(1, Long.MAX_VALUE)); CodecService codecService = new CodecService(null, logger); String name = Codec.getDefault().getName(); if (Arrays.asList(codecService.availableCodecs()).contains(name)) { // some codecs are read only so we only take the ones that we have in the service and randomly // selected by lucene test case. codecName = name; } else { codecName = "default"; } defaultSettings = IndexSettingsModule.newIndexSettings("test", indexSettings()); threadPool = new TestThreadPool(getClass().getName()); store = createStore(); storeReplica = createStore(); Lucene.cleanLuceneIndex(store.directory()); Lucene.cleanLuceneIndex(storeReplica.directory()); primaryTranslogDir = createTempDir("translog-primary"); translogHandler = createTranslogHandler(defaultSettings); engine = createEngine(store, primaryTranslogDir); LiveIndexWriterConfig currentIndexWriterConfig = engine.getCurrentIndexWriterConfig(); assertEquals(engine.config().getCodec().getName(), codecService.codec(codecName).getName()); assertEquals(currentIndexWriterConfig.getCodec().getName(), codecService.codec(codecName).getName()); if (randomBoolean()) { engine.config().setEnableGcDeletes(false); } replicaTranslogDir = createTempDir("translog-replica"); replicaEngine = createEngine(storeReplica, replicaTranslogDir); currentIndexWriterConfig = replicaEngine.getCurrentIndexWriterConfig(); assertEquals(replicaEngine.config().getCodec().getName(), codecService.codec(codecName).getName()); assertEquals(currentIndexWriterConfig.getCodec().getName(), codecService.codec(codecName).getName()); if (randomBoolean()) { engine.config().setEnableGcDeletes(false); } } public EngineConfig copy(EngineConfig config, LongSupplier globalCheckpointSupplier) { return new EngineConfig(config.getShardId(), config.getThreadPool(), config.getIndexSettings(), config.getWarmer(), config.getStore(), config.getMergePolicy(), config.getAnalyzer(), config.getSimilarity(), new CodecService(null, logger), config.getEventListener(), config.getQueryCache(), config.getQueryCachingPolicy(), config.getTranslogConfig(), config.getFlushMergesAfter(), config.getExternalRefreshListener(), Collections.emptyList(), config.getIndexSort(), config.getCircuitBreakerService(), globalCheckpointSupplier, config.retentionLeasesSupplier(), config.getPrimaryTermSupplier(), tombstoneDocSupplier(), config.getSnapshotCommitSupplier()); } public EngineConfig copy(EngineConfig config, Analyzer analyzer) { return new EngineConfig(config.getShardId(), config.getThreadPool(), config.getIndexSettings(), config.getWarmer(), config.getStore(), config.getMergePolicy(), analyzer, config.getSimilarity(), new CodecService(null, logger), config.getEventListener(), config.getQueryCache(), config.getQueryCachingPolicy(), config.getTranslogConfig(), config.getFlushMergesAfter(), config.getExternalRefreshListener(), Collections.emptyList(), config.getIndexSort(), config.getCircuitBreakerService(), config.getGlobalCheckpointSupplier(), config.retentionLeasesSupplier(), config.getPrimaryTermSupplier(), config.getTombstoneDocSupplier(), config.getSnapshotCommitSupplier()); } public EngineConfig copy(EngineConfig config, MergePolicy mergePolicy) { return new EngineConfig(config.getShardId(), config.getThreadPool(), config.getIndexSettings(), config.getWarmer(), config.getStore(), mergePolicy, config.getAnalyzer(), config.getSimilarity(), new CodecService(null, logger), config.getEventListener(), config.getQueryCache(), config.getQueryCachingPolicy(), config.getTranslogConfig(), config.getFlushMergesAfter(), config.getExternalRefreshListener(), Collections.emptyList(), config.getIndexSort(), config.getCircuitBreakerService(), config.getGlobalCheckpointSupplier(), config.retentionLeasesSupplier(), config.getPrimaryTermSupplier(), config.getTombstoneDocSupplier(), config.getSnapshotCommitSupplier()); } @Override @After public void tearDown() throws Exception { super.tearDown(); try { if (engine != null && engine.isClosed.get() == false) { engine.getTranslog().getDeletionPolicy().assertNoOpenTranslogRefs(); assertNoInFlightDocuments(engine); assertConsistentHistoryBetweenTranslogAndLuceneIndex(engine); assertMaxSeqNoInCommitUserData(engine); assertAtMostOneLuceneDocumentPerSequenceNumber(engine); } if (replicaEngine != null && replicaEngine.isClosed.get() == false) { replicaEngine.getTranslog().getDeletionPolicy().assertNoOpenTranslogRefs(); assertNoInFlightDocuments(replicaEngine); assertConsistentHistoryBetweenTranslogAndLuceneIndex(replicaEngine); assertMaxSeqNoInCommitUserData(replicaEngine); assertAtMostOneLuceneDocumentPerSequenceNumber(replicaEngine); } assertThat(engine.config().getCircuitBreakerService().getBreaker(CircuitBreaker.ACCOUNTING).getUsed(), equalTo(0L)); assertThat(replicaEngine.config().getCircuitBreakerService().getBreaker(CircuitBreaker.ACCOUNTING).getUsed(), equalTo(0L)); } finally { IOUtils.close(replicaEngine, storeReplica, engine, store, () -> terminate(threadPool)); } } protected static ParseContext.Document testDocumentWithTextField() { return testDocumentWithTextField("test"); } protected static ParseContext.Document testDocumentWithTextField(String value) { ParseContext.Document document = testDocument(); document.add(new TextField("value", value, Field.Store.YES)); return document; } protected static ParseContext.Document testDocument() { return new ParseContext.Document(); } public static ParsedDocument createParsedDoc(String id, String routing) { return testParsedDocument(id, routing, testDocumentWithTextField(), new BytesArray("{ \"value\" : \"test\" }"), null); } public static ParsedDocument createParsedDoc(String id, String routing, boolean recoverySource) { return testParsedDocument(id, routing, testDocumentWithTextField(), new BytesArray("{ \"value\" : \"test\" }"), null, recoverySource); } protected static ParsedDocument testParsedDocument( String id, String routing, ParseContext.Document document, BytesReference source, Mapping mappingUpdate) { return testParsedDocument(id, routing, document, source, mappingUpdate, false); } protected static ParsedDocument testParsedDocument( String id, String routing, ParseContext.Document document, BytesReference source, Mapping mappingUpdate, boolean recoverySource) { Field uidField = new Field("_id", Uid.encodeId(id), IdFieldMapper.Defaults.FIELD_TYPE); Field versionField = new NumericDocValuesField("_version", 0); SeqNoFieldMapper.SequenceIDFields seqID = SeqNoFieldMapper.SequenceIDFields.emptySeqID(); document.add(uidField); document.add(versionField); document.add(seqID.seqNo); document.add(seqID.seqNoDocValue); document.add(seqID.primaryTerm); BytesRef ref = source.toBytesRef(); if (recoverySource) { document.add(new StoredField(SourceFieldMapper.RECOVERY_SOURCE_NAME, ref.bytes, ref.offset, ref.length)); document.add(new NumericDocValuesField(SourceFieldMapper.RECOVERY_SOURCE_NAME, 1)); } else { document.add(new StoredField(SourceFieldMapper.NAME, ref.bytes, ref.offset, ref.length)); } return new ParsedDocument(versionField, seqID, id, routing, Arrays.asList(document), source, XContentType.JSON, mappingUpdate); } public static CheckedBiFunction<String, Integer, ParsedDocument, IOException> nestedParsedDocFactory() throws Exception { final MapperService mapperService = createMapperService(); final String nestedMapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("nested_field").field("type", "nested").endObject().endObject() .endObject().endObject()); final DocumentMapper nestedMapper = mapperService.parse("type", new CompressedXContent(nestedMapping)); return (docId, nestedFieldValues) -> { final XContentBuilder source = XContentFactory.jsonBuilder().startObject().field("field", "value"); if (nestedFieldValues > 0) { XContentBuilder nestedField = source.startObject("nested_field"); for (int i = 0; i < nestedFieldValues; i++) { nestedField.field("field-" + i, "value-" + i); } source.endObject(); } source.endObject(); return nestedMapper.parse(new SourceToParse("test", docId, BytesReference.bytes(source), XContentType.JSON)); }; } /** * Creates a tombstone document that only includes uid, seq#, term and version fields. */ public static EngineConfig.TombstoneDocSupplier tombstoneDocSupplier(){ return new EngineConfig.TombstoneDocSupplier() { @Override public ParsedDocument newDeleteTombstoneDoc(String id) { final ParseContext.Document doc = new ParseContext.Document(); Field uidField = new Field(IdFieldMapper.NAME, Uid.encodeId(id), IdFieldMapper.Defaults.FIELD_TYPE); doc.add(uidField); Field versionField = new NumericDocValuesField(VersionFieldMapper.NAME, 0); doc.add(versionField); SeqNoFieldMapper.SequenceIDFields seqID = SeqNoFieldMapper.SequenceIDFields.emptySeqID(); doc.add(seqID.seqNo); doc.add(seqID.seqNoDocValue); doc.add(seqID.primaryTerm); seqID.tombstoneField.setLongValue(1); doc.add(seqID.tombstoneField); return new ParsedDocument(versionField, seqID, id, null, Collections.singletonList(doc), new BytesArray("{}"), XContentType.JSON, null); } @Override public ParsedDocument newNoopTombstoneDoc(String reason) { final ParseContext.Document doc = new ParseContext.Document(); SeqNoFieldMapper.SequenceIDFields seqID = SeqNoFieldMapper.SequenceIDFields.emptySeqID(); doc.add(seqID.seqNo); doc.add(seqID.seqNoDocValue); doc.add(seqID.primaryTerm); seqID.tombstoneField.setLongValue(1); doc.add(seqID.tombstoneField); Field versionField = new NumericDocValuesField(VersionFieldMapper.NAME, 0); doc.add(versionField); BytesRef byteRef = new BytesRef(reason); doc.add(new StoredField(SourceFieldMapper.NAME, byteRef.bytes, byteRef.offset, byteRef.length)); return new ParsedDocument(versionField, seqID, null, null, Collections.singletonList(doc), null, XContentType.JSON, null); } }; } protected Store createStore() throws IOException { return createStore(newDirectory()); } protected Store createStore(final Directory directory) throws IOException { return createStore(INDEX_SETTINGS, directory); } protected Store createStore(final IndexSettings indexSettings, final Directory directory) throws IOException { return new Store(shardId, indexSettings, directory, new DummyShardLock(shardId)); } protected Translog createTranslog(LongSupplier primaryTermSupplier) throws IOException { return createTranslog(primaryTranslogDir, primaryTermSupplier); } protected Translog createTranslog(Path translogPath, LongSupplier primaryTermSupplier) throws IOException { TranslogConfig translogConfig = new TranslogConfig(shardId, translogPath, INDEX_SETTINGS, BigArrays.NON_RECYCLING_INSTANCE); String translogUUID = Translog.createEmptyTranslog(translogPath, SequenceNumbers.NO_OPS_PERFORMED, shardId, primaryTermSupplier.getAsLong()); return new Translog(translogConfig, translogUUID, new TranslogDeletionPolicy(), () -> SequenceNumbers.NO_OPS_PERFORMED, primaryTermSupplier, seqNo -> {}); } protected TranslogHandler createTranslogHandler(IndexSettings indexSettings) { return new TranslogHandler(xContentRegistry(), indexSettings); } protected InternalEngine createEngine(Store store, Path translogPath) throws IOException { return createEngine(defaultSettings, store, translogPath, newMergePolicy(), null); } protected InternalEngine createEngine(Store store, Path translogPath, LongSupplier globalCheckpointSupplier) throws IOException { return createEngine(defaultSettings, store, translogPath, newMergePolicy(), null, null, globalCheckpointSupplier); } protected InternalEngine createEngine( Store store, Path translogPath, BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier) throws IOException { return createEngine(defaultSettings, store, translogPath, newMergePolicy(), null, localCheckpointTrackerSupplier, null); } protected InternalEngine createEngine( Store store, Path translogPath, BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier, ToLongBiFunction<Engine, Engine.Operation> seqNoForOperation) throws IOException { return createEngine( defaultSettings, store, translogPath, newMergePolicy(), null, localCheckpointTrackerSupplier, null, seqNoForOperation); } protected InternalEngine createEngine( IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy) throws IOException { return createEngine(indexSettings, store, translogPath, mergePolicy, null); } protected InternalEngine createEngine(IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy, @Nullable IndexWriterFactory indexWriterFactory) throws IOException { return createEngine(indexSettings, store, translogPath, mergePolicy, indexWriterFactory, null, null); } protected InternalEngine createEngine( IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy, @Nullable IndexWriterFactory indexWriterFactory, @Nullable BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier, @Nullable LongSupplier globalCheckpointSupplier) throws IOException { return createEngine( indexSettings, store, translogPath, mergePolicy, indexWriterFactory, localCheckpointTrackerSupplier, null, null, globalCheckpointSupplier); } protected InternalEngine createEngine( IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy, @Nullable IndexWriterFactory indexWriterFactory, @Nullable BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier, @Nullable LongSupplier globalCheckpointSupplier, @Nullable ToLongBiFunction<Engine, Engine.Operation> seqNoForOperation) throws IOException { return createEngine( indexSettings, store, translogPath, mergePolicy, indexWriterFactory, localCheckpointTrackerSupplier, seqNoForOperation, null, globalCheckpointSupplier); } protected InternalEngine createEngine( IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy, @Nullable IndexWriterFactory indexWriterFactory, @Nullable BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier, @Nullable ToLongBiFunction<Engine, Engine.Operation> seqNoForOperation, @Nullable Sort indexSort, @Nullable LongSupplier globalCheckpointSupplier) throws IOException { EngineConfig config = config(indexSettings, store, translogPath, mergePolicy, null, indexSort, globalCheckpointSupplier); return createEngine(indexWriterFactory, localCheckpointTrackerSupplier, seqNoForOperation, config); } protected InternalEngine createEngine(EngineConfig config) throws IOException { return createEngine(null, null, null, config); } protected InternalEngine createEngine(@Nullable IndexWriterFactory indexWriterFactory, @Nullable BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier, @Nullable ToLongBiFunction<Engine, Engine.Operation> seqNoForOperation, EngineConfig config) throws IOException { final Store store = config.getStore(); final Directory directory = store.directory(); if (Lucene.indexExists(directory) == false) { store.createEmpty(); final String translogUuid = Translog.createEmptyTranslog(config.getTranslogConfig().getTranslogPath(), SequenceNumbers.NO_OPS_PERFORMED, shardId, primaryTerm.get()); store.associateIndexWithNewTranslog(translogUuid); } InternalEngine internalEngine = createInternalEngine(indexWriterFactory, localCheckpointTrackerSupplier, seqNoForOperation, config); internalEngine.recoverFromTranslog(translogHandler, Long.MAX_VALUE); return internalEngine; } public static InternalEngine createEngine(EngineConfig engineConfig, int maxDocs) { return new InternalEngine(engineConfig, maxDocs, LocalCheckpointTracker::new); } @FunctionalInterface public interface IndexWriterFactory { IndexWriter createWriter(Directory directory, IndexWriterConfig iwc) throws IOException; } /** * Generate a new sequence number and return it. Only works on InternalEngines */ public static long generateNewSeqNo(final Engine engine) { assert engine instanceof InternalEngine : "expected InternalEngine, got: " + engine.getClass(); InternalEngine internalEngine = (InternalEngine) engine; return internalEngine.getLocalCheckpointTracker().generateSeqNo(); } public static InternalEngine createInternalEngine( @Nullable final IndexWriterFactory indexWriterFactory, @Nullable final BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier, @Nullable final ToLongBiFunction<Engine, Engine.Operation> seqNoForOperation, final EngineConfig config) { if (localCheckpointTrackerSupplier == null) { return new InternalTestEngine(config) { @Override IndexWriter createWriter(Directory directory, IndexWriterConfig iwc) throws IOException { return (indexWriterFactory != null) ? indexWriterFactory.createWriter(directory, iwc) : super.createWriter(directory, iwc); } @Override protected long doGenerateSeqNoForOperation(final Operation operation) { return seqNoForOperation != null ? seqNoForOperation.applyAsLong(this, operation) : super.doGenerateSeqNoForOperation(operation); } }; } else { return new InternalTestEngine(config, IndexWriter.MAX_DOCS, localCheckpointTrackerSupplier) { @Override IndexWriter createWriter(Directory directory, IndexWriterConfig iwc) throws IOException { return (indexWriterFactory != null) ? indexWriterFactory.createWriter(directory, iwc) : super.createWriter(directory, iwc); } @Override protected long doGenerateSeqNoForOperation(final Operation operation) { return seqNoForOperation != null ? seqNoForOperation.applyAsLong(this, operation) : super.doGenerateSeqNoForOperation(operation); } }; } } public EngineConfig config(IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy, ReferenceManager.RefreshListener refreshListener) { return config(indexSettings, store, translogPath, mergePolicy, refreshListener, null, () -> SequenceNumbers.NO_OPS_PERFORMED); } public EngineConfig config(IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy, ReferenceManager.RefreshListener refreshListener, Sort indexSort, LongSupplier globalCheckpointSupplier) { return config( indexSettings, store, translogPath, mergePolicy, refreshListener, indexSort, globalCheckpointSupplier, globalCheckpointSupplier == null ? null : () -> RetentionLeases.EMPTY); } public EngineConfig config( final IndexSettings indexSettings, final Store store, final Path translogPath, final MergePolicy mergePolicy, final ReferenceManager.RefreshListener refreshListener, final Sort indexSort, final LongSupplier globalCheckpointSupplier, final Supplier<RetentionLeases> retentionLeasesSupplier) { return config( indexSettings, store, translogPath, mergePolicy, refreshListener, null, indexSort, globalCheckpointSupplier, retentionLeasesSupplier, new NoneCircuitBreakerService()); } public EngineConfig config(IndexSettings indexSettings, Store store, Path translogPath, MergePolicy mergePolicy, ReferenceManager.RefreshListener externalRefreshListener, ReferenceManager.RefreshListener internalRefreshListener, Sort indexSort, @Nullable LongSupplier maybeGlobalCheckpointSupplier, CircuitBreakerService breakerService) { return config( indexSettings, store, translogPath, mergePolicy, externalRefreshListener, internalRefreshListener, indexSort, maybeGlobalCheckpointSupplier, maybeGlobalCheckpointSupplier == null ? null : () -> RetentionLeases.EMPTY, breakerService); } public EngineConfig config( final IndexSettings indexSettings, final Store store, final Path translogPath, final MergePolicy mergePolicy, final ReferenceManager.RefreshListener externalRefreshListener, final ReferenceManager.RefreshListener internalRefreshListener, final Sort indexSort, final @Nullable LongSupplier maybeGlobalCheckpointSupplier, final @Nullable Supplier<RetentionLeases> maybeRetentionLeasesSupplier, final CircuitBreakerService breakerService) { final IndexWriterConfig iwc = newIndexWriterConfig(); final TranslogConfig translogConfig = new TranslogConfig(shardId, translogPath, indexSettings, BigArrays.NON_RECYCLING_INSTANCE); final Engine.EventListener eventListener = new Engine.EventListener() {}; // we don't need to notify anybody in this test final List<ReferenceManager.RefreshListener> extRefreshListenerList = externalRefreshListener == null ? emptyList() : Collections.singletonList(externalRefreshListener); final List<ReferenceManager.RefreshListener> intRefreshListenerList = internalRefreshListener == null ? emptyList() : Collections.singletonList(internalRefreshListener); final LongSupplier globalCheckpointSupplier; final Supplier<RetentionLeases> retentionLeasesSupplier; if (maybeGlobalCheckpointSupplier == null) { assert maybeRetentionLeasesSupplier == null; final ReplicationTracker replicationTracker = new ReplicationTracker( shardId, allocationId.getId(), indexSettings, randomNonNegativeLong(), SequenceNumbers.NO_OPS_PERFORMED, update -> {}, () -> 0L, (leases, listener) -> listener.onResponse(new ReplicationResponse()), () -> SafeCommitInfo.EMPTY); globalCheckpointSupplier = replicationTracker; retentionLeasesSupplier = replicationTracker::getRetentionLeases; } else { assert maybeRetentionLeasesSupplier != null; globalCheckpointSupplier = maybeGlobalCheckpointSupplier; retentionLeasesSupplier = maybeRetentionLeasesSupplier; } return new EngineConfig( shardId, threadPool, indexSettings, null, store, mergePolicy, iwc.getAnalyzer(), iwc.getSimilarity(), new CodecService(null, logger), eventListener, IndexSearcher.getDefaultQueryCache(), IndexSearcher.getDefaultQueryCachingPolicy(), translogConfig, TimeValue.timeValueMinutes(5), extRefreshListenerList, intRefreshListenerList, indexSort, breakerService, globalCheckpointSupplier, retentionLeasesSupplier, primaryTerm, tombstoneDocSupplier(), IndexModule.DEFAULT_SNAPSHOT_COMMIT_SUPPLIER); } protected EngineConfig config(EngineConfig config, Store store, Path translogPath, EngineConfig.TombstoneDocSupplier tombstoneDocSupplier) { IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("test", Settings.builder().put(config.getIndexSettings().getSettings()) .put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true).build()); TranslogConfig translogConfig = new TranslogConfig(shardId, translogPath, indexSettings, BigArrays.NON_RECYCLING_INSTANCE); return new EngineConfig(config.getShardId(), config.getThreadPool(), indexSettings, config.getWarmer(), store, config.getMergePolicy(), config.getAnalyzer(), config.getSimilarity(), new CodecService(null, logger), config.getEventListener(), config.getQueryCache(), config.getQueryCachingPolicy(), translogConfig, config.getFlushMergesAfter(), config.getExternalRefreshListener(), config.getInternalRefreshListener(), config.getIndexSort(), config.getCircuitBreakerService(), config.getGlobalCheckpointSupplier(), config.retentionLeasesSupplier(), config.getPrimaryTermSupplier(), tombstoneDocSupplier, config.getSnapshotCommitSupplier()); } protected EngineConfig noOpConfig(IndexSettings indexSettings, Store store, Path translogPath) { return noOpConfig(indexSettings, store, translogPath, null); } protected EngineConfig noOpConfig(IndexSettings indexSettings, Store store, Path translogPath, LongSupplier globalCheckpointSupplier) { return config(indexSettings, store, translogPath, newMergePolicy(), null, null, globalCheckpointSupplier); } protected static final BytesReference B_1 = new BytesArray(new byte[]{1}); protected static final BytesReference B_2 = new BytesArray(new byte[]{2}); protected static final BytesReference B_3 = new BytesArray(new byte[]{3}); protected static final BytesArray SOURCE = bytesArray("{}"); protected static BytesArray bytesArray(String string) { return new BytesArray(string.getBytes(Charset.defaultCharset())); } public static Term newUid(String id) { return new Term("_id", Uid.encodeId(id)); } public static Term newUid(ParsedDocument doc) { return newUid(doc.id()); } protected Engine.Get newGet(boolean realtime, ParsedDocument doc) { return new Engine.Get(realtime, realtime, doc.id()); } protected Engine.Index indexForDoc(ParsedDocument doc) { return new Engine.Index(newUid(doc), primaryTerm.get(), doc); } protected Engine.Index replicaIndexForDoc(ParsedDocument doc, long version, long seqNo, boolean isRetry) { return new Engine.Index(newUid(doc), doc, seqNo, primaryTerm.get(), version, null, Engine.Operation.Origin.REPLICA, System.nanoTime(), IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, isRetry, SequenceNumbers.UNASSIGNED_SEQ_NO, 0); } protected Engine.Delete replicaDeleteForDoc(String id, long version, long seqNo, long startTime) { return new Engine.Delete(id, newUid(id), seqNo, 1, version, null, Engine.Operation.Origin.REPLICA, startTime, SequenceNumbers.UNASSIGNED_SEQ_NO, 0); } protected static void assertVisibleCount(InternalEngine engine, int numDocs) throws IOException { assertVisibleCount(engine, numDocs, true); } protected static void assertVisibleCount(InternalEngine engine, int numDocs, boolean refresh) throws IOException { if (refresh) { engine.refresh("test"); } try (Engine.Searcher searcher = engine.acquireSearcher("test")) { final TotalHitCountCollector collector = new TotalHitCountCollector(); searcher.search(new MatchAllDocsQuery(), collector); assertThat(collector.getTotalHits(), equalTo(numDocs)); } } public static List<Engine.Operation> generateSingleDocHistory(boolean forReplica, VersionType versionType, long primaryTerm, int minOpCount, int maxOpCount, String docId) { final int numOfOps = randomIntBetween(minOpCount, maxOpCount); final List<Engine.Operation> ops = new ArrayList<>(); final Term id = newUid(docId); final int startWithSeqNo = 0; final String valuePrefix = (forReplica ? "r_" : "p_" ) + docId + "_"; final boolean incrementTermWhenIntroducingSeqNo = randomBoolean(); for (int i = 0; i < numOfOps; i++) { final Engine.Operation op; final long version; switch (versionType) { case INTERNAL: version = forReplica ? i : Versions.MATCH_ANY; break; case EXTERNAL: version = i; break; case EXTERNAL_GTE: version = randomBoolean() ? Math.max(i - 1, 0) : i; break; default: throw new UnsupportedOperationException("unknown version type: " + versionType); } if (randomBoolean()) { op = new Engine.Index(id, testParsedDocument(docId, null, testDocumentWithTextField(valuePrefix + i), SOURCE, null), forReplica && i >= startWithSeqNo ? i * 2 : SequenceNumbers.UNASSIGNED_SEQ_NO, forReplica && i >= startWithSeqNo && incrementTermWhenIntroducingSeqNo ? primaryTerm + 1 : primaryTerm, version, forReplica ? null : versionType, forReplica ? REPLICA : PRIMARY, System.currentTimeMillis(), -1, false, SequenceNumbers.UNASSIGNED_SEQ_NO, 0); } else { op = new Engine.Delete(docId, id, forReplica && i >= startWithSeqNo ? i * 2 : SequenceNumbers.UNASSIGNED_SEQ_NO, forReplica && i >= startWithSeqNo && incrementTermWhenIntroducingSeqNo ? primaryTerm + 1 : primaryTerm, version, forReplica ? null : versionType, forReplica ? REPLICA : PRIMARY, System.currentTimeMillis(), SequenceNumbers.UNASSIGNED_SEQ_NO, 0); } ops.add(op); } return ops; } public List<Engine.Operation> generateHistoryOnReplica(int numOps, boolean allowGapInSeqNo, boolean allowDuplicate, boolean includeNestedDocs) throws Exception { return generateHistoryOnReplica(numOps, 0L, allowGapInSeqNo, allowDuplicate, includeNestedDocs); } public List<Engine.Operation> generateHistoryOnReplica(int numOps, long startingSeqNo, boolean allowGapInSeqNo, boolean allowDuplicate, boolean includeNestedDocs) throws Exception { long seqNo = startingSeqNo; final int maxIdValue = randomInt(numOps * 2); final List<Engine.Operation> operations = new ArrayList<>(numOps); CheckedBiFunction<String, Integer, ParsedDocument, IOException> nestedParsedDocFactory = nestedParsedDocFactory(); for (int i = 0; i < numOps; i++) { final String id = Integer.toString(randomInt(maxIdValue)); final Engine.Operation.TYPE opType = randomFrom(Engine.Operation.TYPE.values()); final boolean isNestedDoc = includeNestedDocs && opType == Engine.Operation.TYPE.INDEX && randomBoolean(); final int nestedValues = between(0, 3); final long startTime = threadPool.relativeTimeInNanos(); final int copies = allowDuplicate && rarely() ? between(2, 4) : 1; for (int copy = 0; copy < copies; copy++) { final ParsedDocument doc = isNestedDoc ? nestedParsedDocFactory.apply(id, nestedValues) : createParsedDoc(id, null); switch (opType) { case INDEX: operations.add(new Engine.Index(EngineTestCase.newUid(doc), doc, seqNo, primaryTerm.get(), i, null, randomFrom(REPLICA, PEER_RECOVERY), startTime, -1, true, SequenceNumbers.UNASSIGNED_SEQ_NO, 0)); break; case DELETE: operations.add(new Engine.Delete(doc.id(), EngineTestCase.newUid(doc), seqNo, primaryTerm.get(), i, null, randomFrom(REPLICA, PEER_RECOVERY), startTime, SequenceNumbers.UNASSIGNED_SEQ_NO, 0)); break; case NO_OP: operations.add(new Engine.NoOp(seqNo, primaryTerm.get(), randomFrom(REPLICA, PEER_RECOVERY), startTime, "test-" + i)); break; default: throw new IllegalStateException("Unknown operation type [" + opType + "]"); } } seqNo++; if (allowGapInSeqNo && rarely()) { seqNo++; } } Randomness.shuffle(operations); return operations; } public static void assertOpsOnReplica( final List<Engine.Operation> ops, final InternalEngine replicaEngine, boolean shuffleOps, final Logger logger) throws IOException { final Engine.Operation lastOp = ops.get(ops.size() - 1); final String lastFieldValue; if (lastOp instanceof Engine.Index) { Engine.Index index = (Engine.Index) lastOp; lastFieldValue = index.docs().get(0).get("value"); } else { // delete lastFieldValue = null; } if (shuffleOps) { int firstOpWithSeqNo = 0; while (firstOpWithSeqNo < ops.size() && ops.get(firstOpWithSeqNo).seqNo() < 0) { firstOpWithSeqNo++; } // shuffle ops but make sure legacy ops are first shuffle(ops.subList(0, firstOpWithSeqNo), random()); shuffle(ops.subList(firstOpWithSeqNo, ops.size()), random()); } boolean firstOp = true; for (Engine.Operation op : ops) { logger.info("performing [{}], v [{}], seq# [{}], term [{}]", op.operationType().name().charAt(0), op.version(), op.seqNo(), op.primaryTerm()); if (op instanceof Engine.Index) { Engine.IndexResult result = replicaEngine.index((Engine.Index) op); // replicas don't really care to about creation status of documents // this allows to ignore the case where a document was found in the live version maps in // a delete state and return false for the created flag in favor of code simplicity // as deleted or not. This check is just signal regression so a decision can be made if it's // intentional assertThat(result.isCreated(), equalTo(firstOp)); assertThat(result.getVersion(), equalTo(op.version())); assertThat(result.getResultType(), equalTo(Engine.Result.Type.SUCCESS)); } else { Engine.DeleteResult result = replicaEngine.delete((Engine.Delete) op); // Replicas don't really care to about found status of documents // this allows to ignore the case where a document was found in the live version maps in // a delete state and return true for the found flag in favor of code simplicity // his check is just signal regression so a decision can be made if it's // intentional assertThat(result.isFound(), equalTo(firstOp == false)); assertThat(result.getVersion(), equalTo(op.version())); assertThat(result.getResultType(), equalTo(Engine.Result.Type.SUCCESS)); } if (randomBoolean()) { replicaEngine.refresh("test"); } if (randomBoolean()) { replicaEngine.flush(); replicaEngine.refresh("test"); } firstOp = false; } assertVisibleCount(replicaEngine, lastFieldValue == null ? 0 : 1); if (lastFieldValue != null) { try (Engine.Searcher searcher = replicaEngine.acquireSearcher("test")) { final TotalHitCountCollector collector = new TotalHitCountCollector(); searcher.search(new TermQuery(new Term("value", lastFieldValue)), collector); assertThat(collector.getTotalHits(), equalTo(1)); } } } public static void concurrentlyApplyOps(List<Engine.Operation> ops, InternalEngine engine) throws InterruptedException { Thread[] thread = new Thread[randomIntBetween(3, 5)]; CountDownLatch startGun = new CountDownLatch(thread.length); AtomicInteger offset = new AtomicInteger(-1); for (int i = 0; i < thread.length; i++) { thread[i] = new Thread(() -> { startGun.countDown(); try { startGun.await(); } catch (InterruptedException e) { throw new AssertionError(e); } int docOffset; while ((docOffset = offset.incrementAndGet()) < ops.size()) { try { applyOperation(engine, ops.get(docOffset)); if ((docOffset + 1) % 4 == 0) { engine.refresh("test"); } if (rarely()) { engine.flush(); } } catch (IOException e) { throw new AssertionError(e); } } }); thread[i].start(); } for (int i = 0; i < thread.length; i++) { thread[i].join(); } } public static void applyOperations(Engine engine, List<Engine.Operation> operations) throws IOException { for (Engine.Operation operation : operations) { applyOperation(engine, operation); if (randomInt(100) < 10) { engine.refresh("test"); } if (rarely()) { engine.flush(); } } } public static Engine.Result applyOperation(Engine engine, Engine.Operation operation) throws IOException { final Engine.Result result; switch (operation.operationType()) { case INDEX: result = engine.index((Engine.Index) operation); break; case DELETE: result = engine.delete((Engine.Delete) operation); break; case NO_OP: result = engine.noOp((Engine.NoOp) operation); break; default: throw new IllegalStateException("No operation defined for [" + operation + "]"); } return result; } /** * Gets a collection of tuples of docId, sequence number, and primary term of all live documents in the provided engine. */ public static List<DocIdSeqNoAndSource> getDocIds(Engine engine, boolean refresh) throws IOException { if (refresh) { engine.refresh("test_get_doc_ids"); } try (Engine.Searcher searcher = engine.acquireSearcher("test_get_doc_ids", Engine.SearcherScope.INTERNAL)) { List<DocIdSeqNoAndSource> docs = new ArrayList<>(); for (LeafReaderContext leafContext : searcher.getIndexReader().leaves()) { LeafReader reader = leafContext.reader(); NumericDocValues seqNoDocValues = reader.getNumericDocValues(SeqNoFieldMapper.NAME); NumericDocValues primaryTermDocValues = reader.getNumericDocValues(SeqNoFieldMapper.PRIMARY_TERM_NAME); NumericDocValues versionDocValues = reader.getNumericDocValues(VersionFieldMapper.NAME); Bits liveDocs = reader.getLiveDocs(); for (int i = 0; i < reader.maxDoc(); i++) { if (liveDocs == null || liveDocs.get(i)) { if (primaryTermDocValues.advanceExact(i) == false) { // We have to skip non-root docs because its _id field is not stored (indexed only). continue; } final long primaryTerm = primaryTermDocValues.longValue(); Document doc = reader.document(i, Set.of(IdFieldMapper.NAME, SourceFieldMapper.NAME)); BytesRef binaryID = doc.getBinaryValue(IdFieldMapper.NAME); String id = Uid.decodeId(Arrays.copyOfRange(binaryID.bytes, binaryID.offset, binaryID.offset + binaryID.length)); final BytesRef source = doc.getBinaryValue(SourceFieldMapper.NAME); if (seqNoDocValues.advanceExact(i) == false) { throw new AssertionError("seqNoDocValues not found for doc[" + i + "] id[" + id + "]"); } final long seqNo = seqNoDocValues.longValue(); if (versionDocValues.advanceExact(i) == false) { throw new AssertionError("versionDocValues not found for doc[" + i + "] id[" + id + "]"); } final long version = versionDocValues.longValue(); docs.add(new DocIdSeqNoAndSource(id, source, seqNo, primaryTerm, version)); } } } docs.sort(Comparator.comparingLong(DocIdSeqNoAndSource::getSeqNo) .thenComparingLong(DocIdSeqNoAndSource::getPrimaryTerm) .thenComparing((DocIdSeqNoAndSource::getId))); return docs; } } /** * Reads all engine operations that have been processed by the engine from Lucene index. * The returned operations are sorted and de-duplicated, thus each sequence number will be have at most one operation. */ public static List<Translog.Operation> readAllOperationsInLucene(Engine engine) throws IOException { final List<Translog.Operation> operations = new ArrayList<>(); try (Translog.Snapshot snapshot = engine.newChangesSnapshot("test", 0, Long.MAX_VALUE, false)) { Translog.Operation op; while ((op = snapshot.next()) != null){ operations.add(op); } } return operations; } /** * Asserts the provided engine has a consistent document history between translog and Lucene index. */ public static void assertConsistentHistoryBetweenTranslogAndLuceneIndex(Engine engine) throws IOException { if (engine instanceof InternalEngine == false) { return; } final List<Translog.Operation> translogOps = new ArrayList<>(); try (Translog.Snapshot snapshot = EngineTestCase.getTranslog(engine).newSnapshot()) { Translog.Operation op; while ((op = snapshot.next()) != null) { translogOps.add(op); } } final Map<Long, Translog.Operation> luceneOps = readAllOperationsInLucene(engine).stream() .collect(Collectors.toMap(Translog.Operation::seqNo, Function.identity())); final long maxSeqNo = ((InternalEngine) engine).getLocalCheckpointTracker().getMaxSeqNo(); for (Translog.Operation op : translogOps) { assertThat("translog operation [" + op + "] > max_seq_no[" + maxSeqNo + "]", op.seqNo(), lessThanOrEqualTo(maxSeqNo)); } for (Translog.Operation op : luceneOps.values()) { assertThat("lucene operation [" + op + "] > max_seq_no[" + maxSeqNo + "]", op.seqNo(), lessThanOrEqualTo(maxSeqNo)); } final long globalCheckpoint = EngineTestCase.getTranslog(engine).getLastSyncedGlobalCheckpoint(); final long retainedOps = engine.config().getIndexSettings().getSoftDeleteRetentionOperations(); final long minSeqNoToRetain; if (engine.config().getIndexSettings().isSoftDeleteEnabled()) { try (Engine.IndexCommitRef safeCommit = engine.acquireSafeIndexCommit()) { final long seqNoForRecovery = Long.parseLong( safeCommit.getIndexCommit().getUserData().get(SequenceNumbers.LOCAL_CHECKPOINT_KEY)) + 1; minSeqNoToRetain = Math.min(seqNoForRecovery, globalCheckpoint + 1 - retainedOps); } } else { minSeqNoToRetain = engine.getMinRetainedSeqNo(); } for (Translog.Operation translogOp : translogOps) { final Translog.Operation luceneOp = luceneOps.get(translogOp.seqNo()); if (luceneOp == null) { if (minSeqNoToRetain <= translogOp.seqNo()) { fail("Operation not found seq# [" + translogOp.seqNo() + "], global checkpoint [" + globalCheckpoint + "], " + "retention policy [" + retainedOps + "], maxSeqNo [" + maxSeqNo + "], translog op [" + translogOp + "]"); } else { continue; } } assertThat(luceneOp, notNullValue()); assertThat(luceneOp.toString(), luceneOp.primaryTerm(), equalTo(translogOp.primaryTerm())); assertThat(luceneOp.opType(), equalTo(translogOp.opType())); if (luceneOp.opType() == Translog.Operation.Type.INDEX) { assertThat(luceneOp.getSource().source, equalTo(translogOp.getSource().source)); } } } /** * Asserts that the max_seq_no stored in the commit's user_data is never smaller than seq_no of any document in the commit. */ public static void assertMaxSeqNoInCommitUserData(Engine engine) throws Exception { List<IndexCommit> commits = DirectoryReader.listCommits(engine.store.directory()); for (IndexCommit commit : commits) { try (DirectoryReader reader = DirectoryReader.open(commit)) { assertThat(Long.parseLong(commit.getUserData().get(SequenceNumbers.MAX_SEQ_NO)), greaterThanOrEqualTo(maxSeqNosInReader(reader))); } } } public static void assertAtMostOneLuceneDocumentPerSequenceNumber(Engine engine) throws IOException { if (engine instanceof InternalEngine) { try { engine.refresh("test"); try (Engine.Searcher searcher = engine.acquireSearcher("test")) { assertAtMostOneLuceneDocumentPerSequenceNumber(engine.config().getIndexSettings(), searcher.getDirectoryReader()); } } catch (AlreadyClosedException ignored) { // engine was closed } } } public static void assertAtMostOneLuceneDocumentPerSequenceNumber(IndexSettings indexSettings, DirectoryReader reader) throws IOException { Set<Long> seqNos = new HashSet<>(); final DirectoryReader wrappedReader = indexSettings.isSoftDeleteEnabled() ? Lucene.wrapAllDocsLive(reader) : reader; for (LeafReaderContext leaf : wrappedReader.leaves()) { NumericDocValues primaryTermDocValues = leaf.reader().getNumericDocValues(SeqNoFieldMapper.PRIMARY_TERM_NAME); NumericDocValues seqNoDocValues = leaf.reader().getNumericDocValues(SeqNoFieldMapper.NAME); int docId; while ((docId = seqNoDocValues.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { assertTrue(seqNoDocValues.advanceExact(docId)); long seqNo = seqNoDocValues.longValue(); assertThat(seqNo, greaterThanOrEqualTo(0L)); if (primaryTermDocValues.advanceExact(docId)) { if (seqNos.add(seqNo) == false) { IdStoredFieldLoader idLoader = new IdStoredFieldLoader(leaf.reader()); throw new AssertionError("found multiple documents for seq=" + seqNo + " id=" + idLoader.id(docId)); } } } } } public static MapperService createMapperService() throws IOException { IndexMetadata indexMetadata = IndexMetadata.builder("test") .settings(Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT) .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1)) .putMapping("{\"properties\": {}}") .build(); MapperService mapperService = MapperTestUtils.newMapperService(new NamedXContentRegistry(ClusterModule.getNamedXWriteables()), createTempDir(), Settings.EMPTY, "test"); mapperService.merge(indexMetadata, MapperService.MergeReason.MAPPING_UPDATE); return mapperService; } public static DocumentMapper docMapper() { try { return createMapperService().documentMapper(); } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Exposes a translog associated with the given engine for testing purpose. */ public static Translog getTranslog(Engine engine) { assert engine instanceof InternalEngine : "only InternalEngines have translogs, got: " + engine.getClass(); InternalEngine internalEngine = (InternalEngine) engine; return internalEngine.getTranslog(); } /** * Waits for all operations up to the provided sequence number to complete in the given internal engine. * * @param seqNo the sequence number that the checkpoint must advance to before this method returns * @throws InterruptedException if the thread was interrupted while blocking on the condition */ public static void waitForOpsToComplete(InternalEngine engine, long seqNo) throws InterruptedException { engine.getLocalCheckpointTracker().waitForProcessedOpsToComplete(seqNo); } public static boolean hasSnapshottedCommits(Engine engine) { assert engine instanceof InternalEngine : "only InternalEngines have snapshotted commits, got: " + engine.getClass(); InternalEngine internalEngine = (InternalEngine) engine; return internalEngine.hasSnapshottedCommits(); } public static final class PrimaryTermSupplier implements LongSupplier { private final AtomicLong term; PrimaryTermSupplier(long initialTerm) { this.term = new AtomicLong(initialTerm); } public long get() { return term.get(); } public void set(long newTerm) { this.term.set(newTerm); } @Override public long getAsLong() { return get(); } } static long maxSeqNosInReader(DirectoryReader reader) throws IOException { long maxSeqNo = SequenceNumbers.NO_OPS_PERFORMED; for (LeafReaderContext leaf : reader.leaves()) { final NumericDocValues seqNoDocValues = leaf.reader().getNumericDocValues(SeqNoFieldMapper.NAME); while (seqNoDocValues.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) { maxSeqNo = SequenceNumbers.max(maxSeqNo, seqNoDocValues.longValue()); } } return maxSeqNo; } /** * Returns the number of times a version was looked up either from version map or from the index. */ public static long getNumVersionLookups(Engine engine) { return ((InternalEngine) engine).getNumVersionLookups(); } public static long getInFlightDocCount(Engine engine) { if (engine instanceof InternalEngine) { return ((InternalEngine) engine).getInFlightDocCount(); } else { return 0; } } public static void assertNoInFlightDocuments(Engine engine) throws Exception { assertBusy(() -> assertThat(getInFlightDocCount(engine), equalTo(0L))); } public static final class MatchingDirectoryReader extends FilterDirectoryReader { private final Query query; public MatchingDirectoryReader(DirectoryReader in, Query query) throws IOException { super(in, new SubReaderWrapper() { @Override public LeafReader wrap(LeafReader leaf) { try { final IndexSearcher searcher = new IndexSearcher(leaf); final Weight weight = searcher.createWeight(query, ScoreMode.COMPLETE_NO_SCORES, 1.0f); final Scorer scorer = weight.scorer(leaf.getContext()); final DocIdSetIterator iterator = scorer != null ? scorer.iterator() : null; final FixedBitSet liveDocs = new FixedBitSet(leaf.maxDoc()); if (iterator != null) { for (int docId = iterator.nextDoc(); docId != DocIdSetIterator.NO_MORE_DOCS; docId = iterator.nextDoc()) { if (leaf.getLiveDocs() == null || leaf.getLiveDocs().get(docId)) { liveDocs.set(docId); } } } return new FilterLeafReader(leaf) { @Override public Bits getLiveDocs() { return liveDocs; } @Override public CacheHelper getCoreCacheHelper() { return leaf.getCoreCacheHelper(); } @Override public CacheHelper getReaderCacheHelper() { return null; // modify liveDocs } }; } catch (IOException e) { throw new UncheckedIOException(e); } } }); this.query = query; } @Override protected DirectoryReader doWrapDirectoryReader(DirectoryReader in) throws IOException { return new MatchingDirectoryReader(in, query); } @Override public CacheHelper getReaderCacheHelper() { // TODO: We should not return the ReaderCacheHelper if we modify the liveDocs, // but some caching components (e.g., global ordinals) require this cache key. return in.getReaderCacheHelper(); } } public static CheckedFunction<DirectoryReader, DirectoryReader, IOException> randomReaderWrapper() { if (randomBoolean()) { return reader -> reader; } else { return reader -> new MatchingDirectoryReader(reader, new MatchAllDocsQuery()); } } public static Function<Engine.Searcher, Engine.Searcher> randomSearcherWrapper() { if (randomBoolean()) { return Function.identity(); } else { final CheckedFunction<DirectoryReader, DirectoryReader, IOException> readerWrapper = randomReaderWrapper(); return searcher -> SearcherHelper.wrapSearcher(searcher, readerWrapper); } } }
{ "content_hash": "5b4609c7941e60f2a198714ce3e20354", "timestamp": "", "source": "github", "line_count": 1340, "max_line_length": 140, "avg_line_length": 50.25223880597015, "alnum_prop": 0.6468561584840654, "repo_name": "nknize/elasticsearch", "id": "0b677c0d5d26f121849c3e8687d0914b2cc0c5bb", "size": "68126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/framework/src/main/java/org/elasticsearch/index/engine/EngineTestCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "12298" }, { "name": "Batchfile", "bytes": "16353" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "251795" }, { "name": "HTML", "bytes": "5348" }, { "name": "Java", "bytes": "36849935" }, { "name": "Perl", "bytes": "7116" }, { "name": "Python", "bytes": "76127" }, { "name": "Shell", "bytes": "102829" } ], "symlink_target": "" }
package org.jfree.data.xy; import org.jfree.data.ComparableObjectItem; import org.jfree.data.ComparableObjectSeries; import org.jfree.data.general.SeriesChangeEvent; /** * A list of (x,y, deltaX, deltaY) data items. * * @since 1.0.6 * * @see VectorSeriesCollection */ public class VectorSeries extends ComparableObjectSeries { /** * Creates a new empty series. * * @param key the series key (<code>null</code> not permitted). */ public VectorSeries(Comparable key) { this(key, false, true); } /** * Constructs a new series that contains no data. You can specify * whether or not duplicate x-values are allowed for the series. * * @param key the series key (<code>null</code> not permitted). * @param autoSort a flag that controls whether or not the items in the * series are sorted. * @param allowDuplicateXValues a flag that controls whether duplicate * x-values are allowed. */ public VectorSeries(Comparable key, boolean autoSort, boolean allowDuplicateXValues) { super(key, autoSort, allowDuplicateXValues); } /** * Adds a data item to the series. * * @param x the x-value. * @param y the y-value. * @param deltaX the vector x. * @param deltaY the vector y. */ public void add(double x, double y, double deltaX, double deltaY) { add(new VectorDataItem(x, y, deltaX, deltaY), true); } /** * Adds a data item to the series and, if requested, sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param item the data item (<code>null</code> not permitted). * @param notify notify listeners? * * @since 1.0.18 */ public void add(VectorDataItem item, boolean notify) { super.add(item, notify); } /** * Removes the item at the specified index and sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param index the index. * * @return The item removed. */ @Override public ComparableObjectItem remove(int index) { VectorDataItem result = (VectorDataItem) this.data.remove(index); fireSeriesChanged(); return result; } /** * Returns the x-value for the specified item. * * @param index the item index. * * @return The x-value. */ public double getXValue(int index) { VectorDataItem item = (VectorDataItem) this.getDataItem(index); return item.getXValue(); } /** * Returns the y-value for the specified item. * * @param index the item index. * * @return The y-value. */ public double getYValue(int index) { VectorDataItem item = (VectorDataItem) getDataItem(index); return item.getYValue(); } /** * Returns the x-component of the vector for an item in the series. * * @param index the item index. * * @return The x-component of the vector. */ public double getVectorXValue(int index) { VectorDataItem item = (VectorDataItem) getDataItem(index); return item.getVectorX(); } /** * Returns the y-component of the vector for an item in the series. * * @param index the item index. * * @return The y-component of the vector. */ public double getVectorYValue(int index) { VectorDataItem item = (VectorDataItem) getDataItem(index); return item.getVectorY(); } /** * Returns the data item at the specified index. * * @param index the item index. * * @return The data item. */ @Override public ComparableObjectItem getDataItem(int index) { // overridden to make public return super.getDataItem(index); } }
{ "content_hash": "b663db004fd7f913692c3eb30f66147c", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 76, "avg_line_length": 27.405594405594407, "alnum_prop": 0.6050012758356723, "repo_name": "SESoS/SIMSoS", "id": "32ade5dcb5e7f252d1a155146086f9f779f5906d", "size": "5797", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "jfreechart-1.0.19/source/org/jfree/data/xy/VectorSeries.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "191094" }, { "name": "Python", "bytes": "523" } ], "symlink_target": "" }
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2022] EMBL-European Bioinformatics Institute 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. =cut package EnsEMBL::Web::Data::Bio::RegulatoryFeature; ### NAME: EnsEMBL::Web::Data::Bio::RegulatoryFeature ### Base class - wrapper around a Bio::EnsEMBL::RegulatoryFeature API object ### STATUS: Under Development ### Replacement for EnsEMBL::Web::Object::RegulatoryFeature ### DESCRIPTION: ### This module provides additional data-handling ### capabilities on top of those provided by the API use strict; use warnings; no warnings qw(uninitialized); use base qw(EnsEMBL::Web::Data::Bio); sub convert_to_drawing_parameters { ### Converts a set of API objects into simple parameters ### for use by drawing code and HTML components my $self = shift; my $data = $self->data_objects; my $results = []; foreach my $reg (@$data) { my ($gene_links, @stable_ids, $mirna_id); if (ref($reg) =~ /Mirna/) { my $stable_id = $reg->gene_stable_id; @stable_ids = ($stable_id); $mirna_id = $reg->accession; } elsif (ref($reg) !~ /ExternalFeature/) { my $db_ent = $reg->get_all_DBEntries; foreach ( @{ $db_ent} ) { push @stable_ids, $_->primary_id; } } foreach my $stable_id (@stable_ids) { my $url = $self->hub->url({'type' => 'Gene', 'action' => 'Summary', 'g' => $stable_id }); $gene_links .= qq(<a href="$url">$stable_id</a>); } my @extra_results = $reg->analysis->description; ## Sort out any links/URLs if ($extra_results[0] =~ /tarbase/i) { @extra_results = ($self->hub->get_ExtURL_link($mirna_id, 'TARBASE_V8', $mirna_id)); } elsif ($extra_results[0] =~ /a href/i) { $extra_results[0] =~ s/a href/a rel="external" href/ig; } else { $extra_results[0] =~ s/(https?:\/\/\S+[\w\/])/<a rel="external" href="$1">$1<\/a>/ig; } ## Final value has to be a string, to aid auto-display my $analyses = join(', ', @extra_results); $gene_links ||= '-'; push @$results, { 'region' => $reg->seq_region_name, 'start' => $reg->start, 'end' => $reg->end, 'strand' => $reg->strand, 'length' => $reg->end-$reg->start+1, 'label' => $reg->display_label, 'gene_id' => \@stable_ids, 'extra' => { 'gene' => $gene_links, 'analysis' => $analyses, }, } } my $extra_columns = [ {'key' => 'gene', 'title' => 'Associated gene'}, {'key' => 'analysis', 'title' => 'Link to external resource', 'sort' => 'html'}, ]; return [$results, $extra_columns]; } 1;
{ "content_hash": "5adb2ba2d493168b6b8f558ce250d1cf", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 100, "avg_line_length": 32.75, "alnum_prop": 0.6033587786259542, "repo_name": "Ensembl/ensembl-webcode", "id": "9d11e5dbf53eca0a7e0fc47e0ef4ca2b582fd62e", "size": "3275", "binary": false, "copies": "1", "ref": "refs/heads/release/108", "path": "modules/EnsEMBL/Web/Data/Bio/RegulatoryFeature.pm", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "22238" }, { "name": "CSS", "bytes": "357082" }, { "name": "Elixir", "bytes": "99" }, { "name": "HTML", "bytes": "239145" }, { "name": "JavaScript", "bytes": "1088839" }, { "name": "Perl", "bytes": "7118006" }, { "name": "Raku", "bytes": "11199" }, { "name": "Shell", "bytes": "16094" }, { "name": "XS", "bytes": "315" }, { "name": "XSLT", "bytes": "35709" } ], "symlink_target": "" }
package org.basex.query.func.fn; import static org.basex.util.Token.*; import org.basex.query.*; import org.basex.query.func.*; import org.basex.query.value.item.*; import org.basex.util.*; /** * Function implementation. * * @author BaseX Team 2005-15, BSD License * @author Christian Gruen */ public final class FnCodepointEqual extends StandardFunc { @Override public Item item(final QueryContext qc, final InputInfo ii) throws QueryException { final Item it1 = exprs[0].atomItem(qc, info), it2 = exprs[1].atomItem(qc, info); return it1 == null || it2 == null ? null : Bln.get(eq(toToken(it1), toToken(it2))); } }
{ "content_hash": "a28fb4e4562c76b0529315371636d33d", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 87, "avg_line_length": 29, "alnum_prop": 0.7068965517241379, "repo_name": "deshmnnit04/basex", "id": "8bfc9bbbcf276693f033b05406addbd3689d3a49", "size": "638", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "basex-core/src/main/java/org/basex/query/func/fn/FnCodepointEqual.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "9372" }, { "name": "Batchfile", "bytes": "2502" }, { "name": "C", "bytes": "17146" }, { "name": "C#", "bytes": "15295" }, { "name": "C++", "bytes": "7796" }, { "name": "CSS", "bytes": "3386" }, { "name": "Common Lisp", "bytes": "3211" }, { "name": "HTML", "bytes": "1057" }, { "name": "Haskell", "bytes": "4065" }, { "name": "Java", "bytes": "23497050" }, { "name": "JavaScript", "bytes": "8926" }, { "name": "Makefile", "bytes": "1234" }, { "name": "PHP", "bytes": "8690" }, { "name": "Perl", "bytes": "7801" }, { "name": "Python", "bytes": "26123" }, { "name": "QMake", "bytes": "377" }, { "name": "Rebol", "bytes": "4731" }, { "name": "Ruby", "bytes": "7359" }, { "name": "Scala", "bytes": "11692" }, { "name": "Shell", "bytes": "3557" }, { "name": "Visual Basic", "bytes": "11957" }, { "name": "XQuery", "bytes": "310833" }, { "name": "XSLT", "bytes": "172" } ], "symlink_target": "" }
package network; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.SocketException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.tuple.Pair; import core.Action; import core.Config; import core.Joueur; public class Client extends Thread { private Socket client; private DispatcherServeur serveur; private boolean attendTop; private static final String TOP = "1"; private static final String SOLDE = "2"; private static final String OPERATIONS = "3"; private static final String ACHATS = "4 "; private static final String VENTES = "5 "; private static final String HISTO = "6 "; // on définit un dictionnaire qui permettra une communication private static final String ASK = "7 "; // client/serveur avec des messages très courts private static final String BID = "8 "; // sans perdre de lisibilité du code private static final String SUIVRE = "9 "; private static final String ANNULER = "A "; private static final String FIN = "B"; private static final String CREATE = "C "; private static final String JOIN = "D "; private static final String LISTECOUPS = "E"; private static final String AVANTTOP = "F"; public Client(Socket client, DispatcherServeur serveur) { super(); this.client = client; this.serveur = serveur; this.attendTop=false; start(); } public void run() { System.out.println("Client connecté"); int nombreActions = Action.values().length; Partie current = null; Joueur joueur = null; int numero_partie = -1; boolean create = false; String identifier = ""; try { BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()), Config.getInstance().MAX_PACKET_SIZE_INPUT); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); envoyer(out, Config.getInstance().VERSION); identifier = childishness(out, in); String userInput; boolean join = false; while ((userInput = in.readLine()) != null) { // System.out.println(userInput + "\n"); String[] arguments = userInput.split(" "); boolean peut_jouer = (create || join) && current.getMarche().est_ouvert() && !current.getMarche().est_fini(); // Utilisateur n'ayant ni créé ni rejoint peut créer if (userInput.startsWith(SOLDE) && (create || join) && current.getMarche().est_ouvert()) { String begin = "{'euros':" + String.valueOf(joueur.getSolde_euros()) + ", "; envoyer(out, begin + MapToStringPython(joueur.getSolde_actions()) + "}"); } else if (userInput.startsWith(OPERATIONS) && peut_jouer) { envoyer(out, String.valueOf(ListPairToStringPythonKeyOnly(joueur.getOperationsOuvertes()))); } else if (userInput.startsWith(ACHATS)) { if (arguments.length == 2 && StringUtils.isNumeric(arguments[1]) && peut_jouer) { int arg = Integer.parseInt(arguments[1]); if (arg < nombreActions && arg >= 0) { Action a = Action.values()[arg]; envoyer(out, current.getMarche().getListeAchatsString(a, 0)); } else envoyer(out, "-4"); } else if (arguments.length == 3 && StringUtils.isNumeric(arguments[1]) && StringUtils.isNumeric(arguments[2]) && peut_jouer) { int arg1 = Integer.parseInt(arguments[1]); if (arg1 < nombreActions && arg1 >= 0) { int arg2 = Integer.parseInt(arguments[2]); Action a = Action.values()[arg1]; envoyer(out, current.getMarche().getListeAchatsString(a, arg2)); } else envoyer(out, "-4"); } else envoyer(out, "-4"); } else if (userInput.startsWith(VENTES)) { if (arguments.length == 2 && StringUtils.isNumeric(arguments[1]) && peut_jouer) { int arg = Integer.parseInt(arguments[1]); if (arg < nombreActions && arg >= 0) { Action a = Action.values()[arg]; envoyer(out, current.getMarche().getListeVentesString(a, 0)); } else envoyer(out, "-4"); } else if (arguments.length == 3 && StringUtils.isNumeric(arguments[1]) && StringUtils.isNumeric(arguments[2]) && peut_jouer) { int arg1 = Integer.parseInt(arguments[1]); if (arg1 < nombreActions && arg1 >= 0) { int arg2 = Integer.parseInt(arguments[2]); Action a = Action.values()[arg1]; envoyer(out, current.getMarche().getListeVentesString(a, arg2)); } else envoyer(out, "-4"); } else envoyer(out, "-4"); } else if (userInput.startsWith(HISTO) && arguments.length == 3 && StringUtils.isNumeric(arguments[1]) && StringUtils.isNumeric(arguments[2]) && (create || join) && current.getMarche().est_ouvert()) { int arg = Integer.parseInt(arguments[1]); if (arg < nombreActions && arg >= 0) { Action a = Action.values()[arg]; envoyer(out, String .valueOf(current.getMarche().getHistoriqueEchanges(a, Integer.parseInt(arguments[2])))); } else envoyer(out, "-4"); } else if (userInput.startsWith(ASK) && arguments.length == 4 && StringUtils.isNumeric(arguments[1]) && NumberUtils.isCreatable(arguments[2]) && StringUtils.isNumeric(arguments[3]) && peut_jouer) { int arg = Integer.parseInt(arguments[1]); if (arg < nombreActions && arg >= 0) { Action a = Action.values()[arg]; float prix = Float.parseFloat(arguments[2]); int volume = Integer.parseInt(arguments[3]); envoyer(out, String.valueOf(current.getMarche().achat(joueur, a, prix, volume))); } else envoyer(out, "-12"); } else if (userInput.startsWith(BID) && arguments.length == 4 && StringUtils.isNumeric(arguments[1]) && NumberUtils.isCreatable(arguments[2]) && StringUtils.isNumeric(arguments[3]) && peut_jouer) { int arg = Integer.parseInt(arguments[1]); if (arg < nombreActions && arg >= 0) { Action a = Action.values()[arg]; float prix = Float.parseFloat(arguments[2]); int volume = Integer.parseInt(arguments[3]); envoyer(out, String.valueOf(current.getMarche().vend(joueur, a, prix, volume))); } else envoyer(out, "-12"); } else if (userInput.startsWith(SUIVRE) && arguments.length == 2 && StringUtils.isNumeric(arguments[1]) && peut_jouer) { int ordre = Integer.parseInt(arguments[1]); envoyer(out, String.valueOf(current.getMarche().suivre(joueur, ordre))); } else if (userInput.startsWith(ANNULER) && arguments.length == 2 && StringUtils.isNumeric(arguments[1]) && peut_jouer) { int ordre = Integer.parseInt(arguments[1]); envoyer(out, String.valueOf(current.getMarche().annuler(joueur, ordre))); } else if (userInput.startsWith(FIN) && arguments.length == 1 && (create || join) && current.getMarche().est_ouvert()) { envoyer(out, String.valueOf(current.getMarche().fin())); } else if (userInput.startsWith(LISTECOUPS) && (create || join) && current.getMarche().est_fini()) { envoyer(out, current.getMarche().getListeOperationsString()); } else if (userInput.startsWith(AVANTTOP) && create && !current.getMarche().est_ouvert()) { envoyer(out, current.getMarche().getListeJoueursStringDico()); } else if (userInput.startsWith(CREATE) && arguments.length == 4 && !create && !join) { String nom = arguments[1]; String modeBanque= arguments[2]; String modeExam= arguments[3]; numero_partie = (int) (Math.random() * 100000); if ((modeBanque.equals("1")||modeBanque.equals("2")||modeBanque.equals("3")) && (modeExam.equals("0")||modeExam.equals("1"))){ if(modeExam.equals("1") && !Config.getInstance().cles.containsKey(nom)) { envoyer(out,"-5"); } else{ envoyer(out, String.valueOf(numero_partie)); current = new Partie(Integer.parseInt(modeBanque),Integer.parseInt(modeExam)); joueur = current.ajouter_client(this, nom, identifier); serveur.ajouterPartie(numero_partie, current); create = true; } } else envoyer(out,"-4"); } else if (userInput.startsWith(JOIN) && arguments.length == 3 && StringUtils.isNumeric(arguments[1]) && !create && !join) { numero_partie = Integer.parseInt(arguments[1]); String nom = arguments[2]; if (!serveur.partieExiste(numero_partie)) { envoyer(out, "-1"); continue; } if (!serveur.getListepartie(numero_partie).getMarche().nom_possible(nom)) { envoyer(out, "-2"); continue; } if (serveur.getListepartie(numero_partie).getMarche().est_ouvert()) { envoyer(out, "-3"); continue; } current = serveur.getListepartie(numero_partie); if (current.isModeExamen()&&( !Config.getInstance().cles.containsKey(nom) || !current.testUniciteDeLaConnexion(client,nom))) { envoyer(out, "-5"); continue; } envoyer(out, "0"); join=true; joueur = current.ajouter_client(this, nom, identifier); } else if (userInput.startsWith(TOP) && create && !current.getMarche().est_ouvert()) { String retour = current.getMarche().getListeJoueursStringDico(); long futureTop = System.currentTimeMillis() + 3500;//in 3.5 seconds for (Client c : current.getListe_client()){ Socket s = c.getSock(); try { if (!s.equals(client) && c.isAttendTop()) { BufferedWriter outAdvers = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); envoyer(outAdvers, "("+String.valueOf((int)(futureTop - System.currentTimeMillis()))+",)"); } } catch(Exception e) { //peu importe client perdu } } envoyer(out, "("+String.valueOf((int)(futureTop - System.currentTimeMillis())+","+retour+")")); long reste = futureTop - System.currentTimeMillis() - 50; if(reste > 0) Thread.sleep(reste); current.getMarche().commence(); } else if (userInput.startsWith(TOP) && !current.getMarche().est_ouvert()) { // attend le top attendTop = true; } else if (userInput.startsWith(TOP) && current.getMarche().est_ouvert() && join && !attendTop && !create) { // retardataires qui ont oublie d'appeller top envoyer(out, "0"); attendTop = true; } else { System.out.println("FAIL |" + userInput + "|"); envoyer(out, "-4"); } } libererPartie(current, numero_partie, create, joueur,identifier); } catch (Exception e) { if (!(e instanceof SocketException)) e.printStackTrace(); try { libererPartie(current, numero_partie, create, joueur,identifier); } catch (Exception e1) { e1.printStackTrace(); if (!(e1 instanceof SocketException)) e.printStackTrace(); } } } public Socket getSock() { return client; } public boolean isAttendTop() { return attendTop; } private String childishness(BufferedWriter out, BufferedReader in) throws IOException, NoSuchAlgorithmException { int ids = (int) (Math.random() * 100000); envoyer(out, String.valueOf(ids)); envoyer(out, Config.getInstance().CHILDISHNESS); String identifier = in.readLine(); MessageDigest mdj = MessageDigest.getInstance("MD5"); mdj.update(identifier.getBytes()); byte[] digest = mdj.digest(); StringBuffer sb = new StringBuffer(); for (byte b : digest) { sb.append(String.format("%02x", b & 0xff)); } String md = in.readLine(); if(!md.equals(new String(sb))) throw new IOException("child"); return identifier.substring(identifier.indexOf(":")+1, identifier.length()); } private void envoyer(BufferedWriter out, String packet) throws IOException { StringBuilder length = new StringBuilder(Config.getInstance().PACKET_SIZE); String llength = String.valueOf(packet.length()); if (packet.length() > Config.getInstance().RESERVED_SIZE_SEND_PACKET) { System.out.println("ERROR : packet too small"); System.err.println("ERROR : packet too small"); } for (int i = llength.length(); i < Config.getInstance().PACKET_SIZE; i++) length.insert(0, "0"); length.append(llength); out.write(new String(length)); out.write(packet); out.flush(); } private void libererPartie(Partie current, int numero_partie, boolean create, Joueur joueur, String identifier) throws IOException { if (joueur != null && current != null) { current.getMarche().retirer_joueur(joueur); } if (current != null && create) { for (Client c : current.getListe_client()){ Socket s = c.getSock(); s.close(); } current.getMarche().destroy(); serveur.retirerPartie(numero_partie); } else if (!create) { if(current != null) current.retirerJoueur(client,identifier); client.close(); } System.out.println("Client déconnecté"); } private <E, V> String MapToStringPython(Map<E, V> map) { StringBuffer sb = new StringBuffer(12 * map.size()); for (Map.Entry<E, V> v : map.entrySet()) { sb.append('\''); sb.append(String.valueOf(v.getKey())); sb.append("':"); sb.append(String.valueOf(v.getValue())); sb.append(','); } if (map.size() != 0) sb.deleteCharAt(sb.length() - 1); return new String(sb); } private <E, V> String ListPairToStringPythonKeyOnly(List<Pair<E, V>> list) { StringBuffer sb = new StringBuffer(12 * list.size()); sb.append('['); for (Pair<E, V> v : list) { sb.append(String.valueOf(v.getKey())); sb.append(','); } if (list.size() != 0) sb.deleteCharAt(sb.length() - 1); sb.append(']'); return new String(sb); } }
{ "content_hash": "3c51a033b9e972c76a2674a20d48ace2", "timestamp": "", "source": "github", "line_count": 360, "max_line_length": 133, "avg_line_length": 37.94722222222222, "alnum_prop": 0.653100065880975, "repo_name": "matthieu637/cpp-2a-info", "id": "e00466e412cc8dc1466f6359ba84cdb9ea254628", "size": "13670", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "2017/SimBourse/src/network/Client.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "51077" }, { "name": "Python", "bytes": "24181" }, { "name": "Shell", "bytes": "627" } ], "symlink_target": "" }
package validators import ( "reflect" "strings" "github.com/go-playground/locales/en" ut "github.com/go-playground/universal-translator" validator "gopkg.in/go-playground/validator.v9" en_translations "gopkg.in/go-playground/validator.v9/translations/en" ) var ( DefaultValidator *validator.Validate DefaultTranslator ut.Translator ) func init() { DefaultValidator = validator.New() DefaultValidator.RegisterTagNameFunc(func(field reflect.StructField) string { jsonName := strings.Split(field.Tag.Get("json"), ",")[0] if jsonName != "" { return jsonName } return field.Name }) en := en.New() uni := ut.New(en, en) DefaultTranslator, _ = uni.GetTranslator("en") en_translations.RegisterDefaultTranslations(DefaultValidator, DefaultTranslator) }
{ "content_hash": "b457f0172de58981dbd5e48fffa4f2bc", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 81, "avg_line_length": 23.545454545454547, "alnum_prop": 0.7438867438867439, "repo_name": "sy264115809/goblin", "id": "322733f79b63325a8ad360b0a9f0aca8c9f018f7", "size": "777", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "app/validators/init.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "439" }, { "name": "Go", "bytes": "135818" }, { "name": "HTML", "bytes": "9420" }, { "name": "JavaScript", "bytes": "72401" }, { "name": "Makefile", "bytes": "541" }, { "name": "Shell", "bytes": "636" }, { "name": "Vue", "bytes": "256987" } ], "symlink_target": "" }
<?php namespace Krautoload; interface InjectedAPI_ClassFileVisitor_Interface { /** * Set the namespace, before searching for class files in this namespace. * * @param string $namespace * Namespace without preceding separator, but with trailing separator. * E.g. 'MyVendor\\' or 'MyVendor\\MyPackage\\', * or just '' for the root namespace. */ function setNamespace($namespace); /** * Get the current namespace. * * @return string * The namespace for the current discovery operation. * E.g. 'MyVendor\\' or 'MyVendor\\MyPackage\\', * or just '' for the root namespace. */ function getNamespace(); /** * Get the absolute class name, * by appending the relative class name to the current namespace. * * @param $relativeClassName * Class name relative to the current namespace. * @return string * The fully-qualified class name. */ function getClassName($relativeClassName); /** * A file was discovered that is expected to define the class. * * @param string $file * The file that was found and is expected to contain a class. * @param string $relativeClassName * The class name relative to the namespace previously specified with * ->setNamespace(). * E.g. 'Foo\\Bar', so that the fully-qualified class name would be * 'MyVendor\\MyPackage\\Foo\\Bar', */ function fileWithClass($file, $relativeClassName); /** * A file was discovered that may define any of the given classes. * * @param string $file * The file that was found and may contain any or none of the classes. * @param array $relativeClassNames * Array of relative class names for classes that *could* be in this file. * With PSR-0, these can be different variations of the underscore. * The one with the least underscores will always be at index 0. * Class names are relative to the namespace previously specified with * ->setNamespace(). */ function fileWithClassCandidates($file, array $relativeClassNames); }
{ "content_hash": "41600b2063700bec07752e6008144c4c", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 78, "avg_line_length": 32.25, "alnum_prop": 0.6773255813953488, "repo_name": "donquixote/krautoload", "id": "6b3ad13a7451af4eed7fbb2a5cdf6995a15705c3", "size": "2064", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Krautoload/InjectedAPI/ClassFileVisitor/Interface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "156144" } ], "symlink_target": "" }
package com.lius.sudo.dialog; import android.content.Context; import android.support.annotation.NonNull; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.lius.sudo.R; /** * Created by UsielLau on 2017/9/21 0021 9:37. */ public class InquiryDialog extends ColorDialogBase { private Context context; private Button positiveBtn; private Button negativeBtn; private String positiveBtnText; private String negativeBtnText; private OnClickDialogBtnListener positiveBtnListener; private OnClickDialogBtnListener negativeBtnListener; public InquiryDialog(@NonNull Context context) { super(context); this.context=context; } @Override void setLogoIv(ImageView logoIv) { logoIv.setImageResource(R.drawable.ic_help); } @Override void addButtons(LinearLayout btnGroupLayout) { positiveBtn=getDefaultButton(); positiveBtn.setText(positiveBtnText); positiveBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(positiveBtnListener!=null){ positiveBtnListener.onClick(); } } }); negativeBtn=getDefaultButton(); negativeBtn.setText(negativeBtnText); negativeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(negativeBtnListener!=null){ negativeBtnListener.onClick(); } } }); btnGroupLayout.addView(positiveBtn); btnGroupLayout.addView(negativeBtn); } public void setPositiveBtnText(String positiveBtnText) { positiveBtn.setText(positiveBtnText); } public void setNegativeBtnText(String negativeBtnText) { negativeBtn.setText(negativeBtnText); } public void setPositiveBtnListener(OnClickDialogBtnListener positiveBtnListener) { this.positiveBtnListener = positiveBtnListener; } public void setNegativeBtnListener(OnClickDialogBtnListener negativeBtnListener) { this.negativeBtnListener = negativeBtnListener; } @Override int getDialogColor() { return context.getResources().getColor(R.color.colorAccent); } @Override boolean setContentView(RelativeLayout contentLayout) { return false; } }
{ "content_hash": "0e219e373d2b55a4437aede021d5f23d", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 86, "avg_line_length": 26.31958762886598, "alnum_prop": 0.6764590677634156, "repo_name": "benxhinGH/Sudo", "id": "d23e5879cf8d7fd7d097f66289f38ba750413b8b", "size": "2553", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/lius/sudo/dialog/InquiryDialog.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "107760" } ], "symlink_target": "" }
function newValue = rtbApplyPropertyOperation(property, oldValue) %% Apply a mappings property operator to an old value, to make a new value. % % newValue = rtbApplyPropertyOperation(property, oldValue) computes a new % property value based on the given mappings property.value and an old % value for that property. The computation depends on the given % property.operation. % % The default operation is simply to replace the old value with the % new value. % % Other operations are also supportd by supplying a Matlab expression to % evaluate. The expression may refer to certain variables, which will be % bound automatically before evaluation: % 'oldValue' will be bound to the oldValue passed to this function % 'value' will be bound to the property.value passed to this function % The new, computed value will be the result of the expression evaluation. % % Returns a new value based on the given property.value, % property.operation, and oldValue. % % newValue = rtbApplyPropertyOperation(property, oldValue) % % Copyright (c) 2016 mexximp Team parser = inputParser(); parser.addRequired('property', @isstruct); parser.addRequired('oldValue'); parser.parse(property, oldValue); property = parser.Results.property; oldValue = parser.Results.oldValue; if isempty(oldValue) newValue = property.value; return; end %% Compute the new value. isSimpleAssignment = isempty(property.operation) || strcmp('=', property.operation); if isSimpleAssignment if isempty(property.value) newValue = oldValue; else newValue = property.value; end return; end % evaluate the given expression against oldValue and property.value newValue = evalClean(property.operation, oldValue, property.value); %% Evaluate in a clean workspace with oldValue and value bound. function newValue = evalClean(expression, oldValue, value) newValue = eval(expression);
{ "content_hash": "342f7407c8c3906aae4c78a0143bd9a9", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 84, "avg_line_length": 34.888888888888886, "alnum_prop": 0.7653927813163482, "repo_name": "RenderToolbox/RenderToolbox4", "id": "617406b33eec2836e31ec0a3f33f60a14d277a38", "size": "1884", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BatchRenderer/AssimpStrategy/BasicMappings/rtbApplyPropertyOperation.m", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "7832" }, { "name": "MATLAB", "bytes": "799912" }, { "name": "Python", "bytes": "32125" }, { "name": "Shell", "bytes": "9346" } ], "symlink_target": "" }
#region Copyright // // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // 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. #endregion #region Usings using System; using System.Collections.Generic; using DotNetNuke.Services.Search.Entities; #endregion namespace DotNetNuke.Services.Search.Internals { /// <summary> /// Internal Search Controller Helper Interface. /// <remarks>This is an Internal interface and should not be used outside of Core.</remarks> /// </summary> public interface ISearchHelper { #region SearchType APIs // /// <summary> // /// Commits the added search documents into the search database // /// </summary> // void Commit(); /// <summary> /// Returns a list of SearchTypes defined in the system /// </summary> /// <returns></returns> IEnumerable<SearchType> GetSearchTypes(); /// <summary> /// Gets a SearchType Item for the given name. /// </summary> /// <returns></returns> SearchType GetSearchTypeByName(string searchTypeName); #endregion #region Synonym Management APIs /// <summary> /// Returns a list of Synonyms for a given word. E.g. leap, hop for jump /// </summary> /// <param name="term">word for which to obtain synonyms</param> /// <param name="portalId">portal id</param> /// <param name="cultureCode">culture code</param> /// <returns>List of synonyms</returns> /// <remarks>Synonyms must be defined in system first</remarks> IEnumerable<string> GetSynonyms(int portalId, string cultureCode, string term); /// <summary> /// Returns a list of SynonymsGroup defined in the system /// </summary> /// <returns></returns> IEnumerable<SynonymsGroup> GetSynonymsGroups(int portalId, string cultureCode); /// <summary> /// Adds a synonymsgroup to system /// </summary> /// <param name="synonymsTags">synonyms tags seperated by comma, like this: dnn,dotnetnuke</param> /// <param name="portalId"></param> /// <param name="cultureCode">culture code</param> /// <returns></returns> int AddSynonymsGroup(string synonymsTags, int portalId, string cultureCode, out string duplicateWord); /// <summary> /// Updates a sysnonymsGroup /// </summary> /// <param name="synonymsGroupId"></param> /// <param name="synonymsTags">synonyms tags seperated by comma, like this: dnn,dotnetnuke</param> /// <param name="portalId"></param> /// <param name="cultureCode">culture code</param> /// <returns></returns> int UpdateSynonymsGroup(int synonymsGroupId, string synonymsTags, int portalId, string cultureCode, out string duplicateWord); /// <summary> /// Deletes a synonyms group /// </summary> /// <param name="synonymsGroupId"></param> /// <param name="portalId"></param> /// <param name="cultureCode">culture code</param> void DeleteSynonymsGroup(int synonymsGroupId, int portalId, string cultureCode); #endregion #region Stop Word Management APIs /// <summary> /// Gets a search stop words /// </summary> /// <param name="portalId"></param> /// <param name="cultureCode"></param> /// <returns></returns> SearchStopWords GetSearchStopWords(int portalId, string cultureCode); /// <summary> /// Adds a search stop words /// </summary> /// <param name="stopWords"></param> /// <param name="portalId"></param> /// <param name="cultureCode"></param> /// <returns></returns> int AddSearchStopWords(string stopWords, int portalId, string cultureCode); /// <summary> /// Updates a search stop words /// </summary> /// <param name="stopWordsId"></param> /// <param name="stopWords"></param> /// <param name="portalId"></param> /// <param name="cultureCode"></param> /// <returns></returns> int UpdateSearchStopWords(int stopWordsId, string stopWords, int portalId, string cultureCode); /// <summary> /// Deletes a search stop words /// </summary> /// <param name="stopWordsId"></param> /// <param name="portalId"></param> /// <param name="cultureCode"></param> void DeleteSearchStopWords(int stopWordsId, int portalId, string cultureCode); #endregion #region Reindex and Compact settings DateTime GetSearchReindexRequestTime(int portalId); DateTime SetSearchReindexRequestTime(int portalId); bool GetSearchCompactFlag(); void SetSearchReindexRequestTime(bool turnOn); bool IsReindexRequested(int portalId, DateTime startDate); IEnumerable<int> GetPortalsToReindex(DateTime startDate); DateTime GetLastSuccessfulIndexingDateTime(int scheduleId); void SetLastSuccessfulIndexingDateTime(int scheduleId, DateTime startDateLocal); DateTime GetIndexerCheckpointUtcTime(int scheduleId, string indexerKey); void SetIndexerCheckpointUtcTime(int scheduleId, string indexerKey, DateTime lastUtcTime); string GetIndexerCheckpointData(int scheduleId, string indexerKey); void SetIndexerCheckpointData(int scheduleId, string indexerKey, string checkPointData); #endregion #region Other Search Helper methods Tuple<int, int> GetSearchMinMaxLength(); string RephraseSearchText(string searchPhrase, bool useWildCard, bool allowLeadingWildcard = false); string StripTagsNoAttributes(string html, bool retainSpace); #endregion } }
{ "content_hash": "961f2a7dcb3182eb2f4f7a63031afd09", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 134, "avg_line_length": 40.63529411764706, "alnum_prop": 0.6522872032426172, "repo_name": "robsiera/Dnn.Platform", "id": "57ef44d49b69b1a2762a8a86b66d81f0550b8973", "size": "6911", "binary": false, "copies": "2", "ref": "refs/heads/development", "path": "DNN Platform/Library/Services/Search/Internals/ISearchHelper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "572469" }, { "name": "Batchfile", "bytes": "405" }, { "name": "C#", "bytes": "21903627" }, { "name": "CSS", "bytes": "1653926" }, { "name": "HTML", "bytes": "528314" }, { "name": "JavaScript", "bytes": "8361433" }, { "name": "PLpgSQL", "bytes": "53478" }, { "name": "PowerShell", "bytes": "10762" }, { "name": "Smalltalk", "bytes": "2410" }, { "name": "TSQL", "bytes": "56906" }, { "name": "Visual Basic", "bytes": "139195" }, { "name": "XSLT", "bytes": "11388" } ], "symlink_target": "" }
from __future__ import print_function import sys import argparse import maskgen.scenario_model from maskgen.graph_rules import processProjectProperties from maskgen.batch import pick_projects, BatchProcessor from maskgen.userinfo import get_username, setPwdX,CustomPwdX from maskgen.validation.core import hasErrorMessages from maskgen.preferences_initializer import initialize from maskgen.external.exporter import ExportManager import logging export_manager = ExportManager() def upload_projects(args, project): """ Uploads project directories to S3 bucket :param s3dir: bucket/dir S3 location :param dir: directory of project directories :param qa: bool for if the projects need to be qa'd :param username: export and qa username :param updatename: change the project username to match username value :param organization: change project organization """ s3dir = args.s3 qa = args.qa username = args.username organization = args.organization updatename = args.updatename ignore_errors = args.ignore log = logging.getLogger('maskgen') redactions= [redaction.strip() for redaction in args.redacted.split(',')] scModel = maskgen.scenario_model.loadProject(project) if username is None: setPwdX(CustomPwdX(scModel.getGraph().getDataItem("username"))) else: if updatename: oldValue = scModel.getProjectData('username') scModel.setProjectData('creator', username) scModel.setProjectData('username', username) scModel.getGraph().replace_attribute_value('username', oldValue, username) if organization is not None: scModel.setProjectData('organization', organization) scModel.save() processProjectProperties(scModel) if qa: username = username if username is not None else get_username() scModel.set_validation_properties("yes", username, "QA redone via Batch Updater") errors = [] if args.skipValidation else scModel.validate(external=True) if ignore_errors or not hasErrorMessages(errors, contentCheck=lambda x: len([m for m in redactions if m not in x]) == 0 ): path, error_list = scModel.export('.', redacted=redactions) if path is not None and (ignore_errors or len(error_list) == 0): export_manager.sync_upload(path, s3dir) if len(error_list) > 0: for err in error_list: log.error(str(err)) raise ValueError('Export Failed') return errors def main(argv=sys.argv[1:]): from functools import partial parser = argparse.ArgumentParser() parser.add_argument('--threads', default=1, required=False, help='number of projects to build') parser.add_argument('-d', '--projects', help='directory of projects') parser.add_argument('-s', '--s3', help='bucket/path of s3 storage', required=False) parser.add_argument('--qa', help="option argument to QA the journal prior to uploading", required=False, action="store_true") parser.add_argument('-u', '--username', help="optional username", required=False) parser.add_argument('-o', '--organization', help="update organization in project", required=False) parser.add_argument('-n', '--updatename', help="should update username in project", required=False, action="store_true") parser.add_argument('-r', '--redacted', help='comma separated list of file argument to exclude from export', default='', required=False) parser.add_argument('-v', '--skipValidation', help='skip validation',action="store_true") parser.add_argument('-i', '--ignore', help='ignore errors', default='', required=False) parser.add_argument('--completeFile', default=None, help='A file recording completed projects') args = parser.parse_args(argv) iterator = pick_projects(args.projects) processor = BatchProcessor(args.completeFile, iterator, threads=args.threads) func = partial(upload_projects, args) return processor.process(func) if __name__ == '__main__': main(sys.argv[1:])
{ "content_hash": "b9662aa380a31bf4d4585bfe6cb139cc", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 127, "avg_line_length": 46.30337078651685, "alnum_prop": 0.6918223732103859, "repo_name": "rwgdrummer/maskgen", "id": "c0ae73732af2457a6d7a8a8c62c62ec8e9d4f3bb", "size": "4391", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "maskgen/batch/bulk_export.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "544" }, { "name": "Dockerfile", "bytes": "4825" }, { "name": "NSIS", "bytes": "4907" }, { "name": "Python", "bytes": "2768871" }, { "name": "Shell", "bytes": "8086" } ], "symlink_target": "" }
'use strict'; //eslint-disable-line strict // Inspired from the babel gulpfile: https://github.com/babel/babel/blob/685006433b0231dbf4b9d306e43c46ed7bcdacad/Gulpfile.js const path = require('path'); const babel = require('gulp-babel'); const gulp = require('gulp'); const newer = require('gulp-newer'); const through = require('through2'); const watch = require('gulp-watch'); const base = path.join(__dirname, 'packages'); const scripts = ['./packages/*/src/**/*.js', '!./packages/*/src/**/__tests__/**/*']; function swapSrcWithLib(name) { return function (srcPath) { const parts = srcPath.split(path.sep); parts[1] = name; return parts.join(path.sep); }; } gulp.task('default', ['build']); gulp.task('build', ['build-lib', 'build-module']); gulp.task('build-lib', function () { return gulp.src(scripts, {base}) .pipe(newer({ dest: base, map: swapSrcWithLib('lib') })) .pipe(babel()) .pipe(through.obj(function (file, enc, callback) { // Passing 'file.relative' because newer() above uses a relative path and this keeps it consistent. file.path = path.resolve(file.base, swapSrcWithLib('lib')(file.relative)); callback(null, file); })) .pipe(gulp.dest(base)); }); gulp.task('build-module', function () { return gulp.src(scripts, {base}) .pipe(newer({ dest: base, map: swapSrcWithLib('lib-module') })) .pipe(babel({ babelrc: false, plugins: ['syntax-dynamic-import'], presets: ['flow'] })) .pipe(through.obj(function (file, enc, callback) { // Passing 'file.relative' because newer() above uses a relative path and this keeps it consistent. file.path = path.resolve(file.base, swapSrcWithLib('lib-module')(file.relative)); callback(null, file); })) .pipe(gulp.dest(base)); }); gulp.task('watch', ['build'], function () { watch(scripts, {debounceDelay: 200}, function () { gulp.start('build'); }); });
{ "content_hash": "d0e3198b3dd2c8af337fb35a8958cedd", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 125, "avg_line_length": 32.707692307692305, "alnum_prop": 0.5870178739416745, "repo_name": "neptunejs/larissa", "id": "0d666d899c776f758edadb3ec6add62d038d89f8", "size": "2126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gulpfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "90062" } ], "symlink_target": "" }
/***************************************************************************** process_data.hpp process data functions declaration Author: F. Herrera Institution: KTH Deparment: Electronic Systems Date: 2014 January *****************************************************************************/ extern "C" char process_my_type(char char_par, unsigned int a); extern "C" char process_my_char(char char_par);
{ "content_hash": "165af884a6fd2d790d3f627a465fd407", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 79, "avg_line_length": 22.894736842105264, "alnum_prop": 0.45057471264367815, "repo_name": "nandohca/kista", "id": "c4da92784bdcc831a4b17c415d2d92ef9e4d1488", "size": "435", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/xml_if/ex9/fun/process_data.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "259396" }, { "name": "C++", "bytes": "1933806" }, { "name": "Makefile", "bytes": "25912" }, { "name": "Objective-C", "bytes": "49776" }, { "name": "Shell", "bytes": "315" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a5a9273f0afc498ef147fec6e8f2ff46", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "df93935024585427879d83c3c7c5d102dd4c673a", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Thymelaeaceae/Passerina/Passerina grandiflora/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
require 'test_helper' module SessionTest module BruteForceProtectionTest class ConfigTest < ActiveSupport::TestCase def test_consecutive_failed_logins_limit UserSession.consecutive_failed_logins_limit = 10 assert_equal 10, UserSession.consecutive_failed_logins_limit UserSession.consecutive_failed_logins_limit 50 assert_equal 50, UserSession.consecutive_failed_logins_limit end def test_failed_login_ban_for UserSession.failed_login_ban_for = 10 assert_equal 10, UserSession.failed_login_ban_for UserSession.failed_login_ban_for 2.hours assert_equal 2.hours.to_i, UserSession.failed_login_ban_for end end class InstanceMethodsTest < ActiveSupport::TestCase def test_under_limit ben = users(:ben) ben.failed_login_count = UserSession.consecutive_failed_logins_limit - 1 assert ben.save assert UserSession.create(:login => ben.login, :password => "benrocks") end def test_exceeded_limit ben = users(:ben) ben.failed_login_count = UserSession.consecutive_failed_logins_limit assert ben.save assert UserSession.create(:login => ben.login, :password => "benrocks").new_session? assert UserSession.create(ben).new_session? ben.reload ben.updated_at = (UserSession.failed_login_ban_for + 2.hours.to_i).seconds.ago assert !UserSession.create(ben).new_session? end def test_exceeding_failed_logins_limit UserSession.consecutive_failed_logins_limit = 2 ben = users(:ben) 2.times do |i| session = UserSession.new(:login => ben.login, :password => "badpassword1") assert !session.save assert session.errors[:password].size > 0 assert_equal i + 1, ben.reload.failed_login_count end session = UserSession.new(:login => ben.login, :password => "badpassword2") assert !session.save assert session.errors[:password].size == 0 assert_equal 3, ben.reload.failed_login_count UserSession.consecutive_failed_logins_limit = 50 end def test_exceeded_ban_for UserSession.consecutive_failed_logins_limit = 2 UserSession.generalize_credentials_error_messages true ben = users(:ben) 2.times do |i| session = UserSession.new(:login => ben.login, :password => "badpassword1") assert !session.save assert session.invalid_password? assert_equal i + 1, ben.reload.failed_login_count end ActiveRecord::Base.connection.execute("update users set updated_at = '#{1.day.ago.to_s(:db)}' where login = '#{ben.login}'") session = UserSession.new(:login => ben.login, :password => "benrocks") assert session.save assert_equal 0, ben.reload.failed_login_count UserSession.consecutive_failed_logins_limit = 50 UserSession.generalize_credentials_error_messages false end def test_exceeded_ban_and_failed_doesnt_ban_again UserSession.consecutive_failed_logins_limit = 2 ben = users(:ben) 2.times do |i| session = UserSession.new(:login => ben.login, :password => "badpassword1") assert !session.save assert session.errors[:password].size > 0 assert_equal i + 1, ben.reload.failed_login_count end ActiveRecord::Base.connection.execute("update users set updated_at = '#{1.day.ago.to_s(:db)}' where login = '#{ben.login}'") session = UserSession.new(:login => ben.login, :password => "badpassword1") assert !session.save assert_equal 1, ben.reload.failed_login_count UserSession.consecutive_failed_logins_limit = 50 end end end end
{ "content_hash": "ba009a031489df39697626c502148a60", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 132, "avg_line_length": 37.077669902912625, "alnum_prop": 0.6496465043205027, "repo_name": "janusnic/authlogic", "id": "f625250900980c8cd59d80e2456787dc878638d0", "size": "3819", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "test/session_test/brute_force_protection_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Logos", "bytes": "863" }, { "name": "Ruby", "bytes": "272973" } ], "symlink_target": "" }
#include <wdt/util/CommonImpl.h> namespace facebook { namespace wdt { Buffer::Buffer(const int64_t size) { WDT_CHECK_EQ(0, size % kDiskBlockSize); isAligned_ = false; size_ = 0; #ifdef HAS_POSIX_MEMALIGN // always allocate aligned buffer if possible int ret = posix_memalign((void**)&data_, kDiskBlockSize, size); if (ret || data_ == nullptr) { WLOG(ERROR) << "posix_memalign failed " << strerrorStr(ret) << " size " << size; return; } WVLOG(1) << "Allocated aligned memory " << size; isAligned_ = true; size_ = size; return; #else data_ = (char*)malloc(size); if (data_ == nullptr) { WLOG(ERROR) << "Failed to allocate memory using malloc " << size; return; } WVLOG(1) << "Allocated unaligned memory " << size; size_ = size; #endif } char* Buffer::getData() const { return data_; } bool Buffer::isAligned() const { return isAligned_; } int64_t Buffer::getSize() const { return size_; } Buffer::~Buffer() { if (data_ != nullptr) { free(data_); } } ThreadCtx::ThreadCtx(const WdtOptions& options, bool allocateBuffer) : options_(options), perfReport_(options) { if (!allocateBuffer) { return; } buffer_ = std::make_unique<Buffer>(options_.buffer_size); } ThreadCtx::ThreadCtx(const WdtOptions& options, bool allocateBuffer, int threadIndex) : ThreadCtx(options, allocateBuffer) { threadIndex_ = threadIndex; } const WdtOptions& ThreadCtx::getOptions() const { return options_; } int ThreadCtx::getThreadIndex() const { WDT_CHECK_GE(threadIndex_, 0); return threadIndex_; } const Buffer* ThreadCtx::getBuffer() const { return buffer_.get(); } PerfStatReport& ThreadCtx::getPerfReport() { return perfReport_; } void ThreadCtx::setAbortChecker(IAbortChecker const* abortChecker) { abortChecker_ = abortChecker; } const IAbortChecker* ThreadCtx::getAbortChecker() const { return abortChecker_; } } }
{ "content_hash": "cea1af84473f5488d899ab3fc922e5d4", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 75, "avg_line_length": 21.35164835164835, "alnum_prop": 0.6598044261451363, "repo_name": "ldemailly/wdt", "id": "5346a79f024dad823d07e7e1aa2ad1e2a32d22c5", "size": "2251", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "util/CommonImpl.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "921" }, { "name": "C++", "bytes": "775745" }, { "name": "CMake", "bytes": "15187" }, { "name": "Python", "bytes": "29989" }, { "name": "Shell", "bytes": "77234" }, { "name": "Tcl", "bytes": "21356" } ], "symlink_target": "" }
/** * WikimediaUI Base v0.11.0 * Wikimedia Foundation user interface base variables */ .oo-ui-window { background: transparent; } .oo-ui-window-frame { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .oo-ui-window-content { position: absolute; top: 0; left: 0; right: 0; bottom: 0; overflow: hidden; } .oo-ui-window-content:focus { outline: 0; } .oo-ui-window-head, .oo-ui-window-foot { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .oo-ui-window-body { margin: 0; padding: 0; background: none; } .oo-ui-window-overlay { position: absolute; top: 0; /* @noflip */ left: 0; } .oo-ui-dialog-content > .oo-ui-window-head, .oo-ui-dialog-content > .oo-ui-window-body, .oo-ui-dialog-content > .oo-ui-window-foot { position: absolute; left: 0; right: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .oo-ui-dialog-content > .oo-ui-window-head { overflow: hidden; z-index: 1; top: 0; } .oo-ui-dialog-content > .oo-ui-window-body { overflow: auto; z-index: 2; top: 0; bottom: 0; } .oo-ui-dialog-content > .oo-ui-window-foot { z-index: 3; bottom: 0; } .oo-ui-messageDialog-actions .oo-ui-actionWidget { position: relative; text-align: center; } .oo-ui-messageDialog-actions .oo-ui-actionWidget .oo-ui-buttonElement-button { display: block; } .oo-ui-messageDialog-actions .oo-ui-actionWidget .oo-ui-labelElement-label { position: relative; top: auto; bottom: auto; } .oo-ui-messageDialog-actions-horizontal { display: table; table-layout: fixed; width: 100%; } .oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget { display: table-cell; width: 1%; } .oo-ui-messageDialog-actions-vertical { display: block; } .oo-ui-messageDialog-actions-vertical .oo-ui-actionWidget { display: block; overflow: hidden; text-overflow: ellipsis; } .oo-ui-messageDialog-content > .oo-ui-window-foot { outline: 1px solid #a2a9b1; } .oo-ui-messageDialog-title, .oo-ui-messageDialog-message { display: block; line-height: 1.42857143em; text-align: center; } .oo-ui-messageDialog-title { font-size: 1.5em; color: #000; } .oo-ui-messageDialog-message { font-size: 1.1em; color: #222; text-align: left; } .oo-ui-messageDialog-actions .oo-ui-actionWidget { min-height: 2.85714286em; margin-right: 0; } .oo-ui-messageDialog-actions .oo-ui-actionWidget:last-child { margin-right: 0; } .oo-ui-messageDialog-actions .oo-ui-actionWidget:first-child { margin-left: 0; } .oo-ui-messageDialog-actions .oo-ui-actionWidget .oo-ui-buttonElement-button { border: 0; border-radius: 0; padding: 0; } .oo-ui-messageDialog-actions .oo-ui-actionWidget.oo-ui-labelElement .oo-ui-labelElement-label { line-height: 2.85714286em; text-align: center; } .oo-ui-messageDialog-actions .oo-ui-actionWidget.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive .oo-ui-buttonElement-button:active { background-color: rgba(8, 126, 204, 0.1); } .oo-ui-messageDialog-actions .oo-ui-actionWidget.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive .oo-ui-buttonElement-button:active { background-color: rgba(212, 83, 83, 0.1); } .oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget { border-right: 1px solid #a2a9b1; margin: 0; } .oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget:first-child > .oo-ui-buttonElement-button { border-radius: 0 0 0 2px; } .oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget:last-child { border-right-width: 0; } .oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget:last-child > .oo-ui-buttonElement-button { border-radius: 0 0 2px 0; } .oo-ui-messageDialog-actions-horizontal .oo-ui-actionWidget:only-child > .oo-ui-buttonElement-button { border-radius: 0 0 2px 2px; } .oo-ui-messageDialog-actions-vertical .oo-ui-actionWidget { border-bottom: 1px solid #a2a9b1; margin: 0; } .oo-ui-messageDialog-actions-vertical .oo-ui-actionWidget:last-child { border-bottom-width: 0; } .oo-ui-messageDialog-actions-vertical .oo-ui-actionWidget:last-child > .oo-ui-buttonElement-button { border-radius: 0 0 2px 2px; } .oo-ui-processDialog-location { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .oo-ui-processDialog-title { display: inline; padding: 0; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget, .oo-ui-processDialog-actions-other .oo-ui-actionWidget { white-space: nowrap; } .oo-ui-processDialog-actions-safe, .oo-ui-processDialog-actions-primary { position: absolute; top: 0; bottom: 0; } .oo-ui-processDialog-actions-safe { left: 0; } .oo-ui-processDialog-actions-primary { right: 0; } .oo-ui-processDialog-errors { position: absolute; top: 0; left: 0; right: 0; bottom: 0; z-index: 4; overflow-x: hidden; overflow-y: auto; } .oo-ui-processDialog-content .oo-ui-window-head { height: 3.14285714em; } .oo-ui-processDialog-content .oo-ui-window-body { top: 3.14285714em; outline: 1px solid #c8ccd1; } .oo-ui-processDialog-navigation { position: relative; height: 3.14285714em; } .oo-ui-processDialog-location { height: 3.14285714em; cursor: default; text-align: center; } .oo-ui-processDialog-title { font-weight: bold; line-height: 3.14285714em; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-framed, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-framed, .oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-framed { margin: 0.42857143em; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement:first-child, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement:first-child, .oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement:first-child { margin-left: 0; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button, .oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button { padding-left: 2.42857143em; padding-top: 0; min-height: 3.14285714em; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon, .oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon { left: 0.5em; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement:first-child, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement:first-child, .oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement:first-child { margin-left: 0; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement > .oo-ui-buttonElement-button, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement > .oo-ui-buttonElement-button, .oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement > .oo-ui-buttonElement-button { padding: 0.75em 1em; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement.oo-ui-iconElement > .oo-ui-buttonElement-button, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement.oo-ui-iconElement > .oo-ui-buttonElement-button, .oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-labelElement.oo-ui-iconElement > .oo-ui-buttonElement-button { padding-left: 2.17857143em; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless .oo-ui-labelElement-label, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless .oo-ui-labelElement-label, .oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement-frameless .oo-ui-labelElement-label { line-height: 1.42857143em; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless:hover, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless:hover { background-color: rgba(0, 0, 0, 0.05); } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless:active, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless:active { background-color: rgba(0, 0, 0, 0.1); } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive:hover, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive:hover { background-color: rgba(8, 126, 204, 0.05); } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive:active, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive:active { background-color: rgba(8, 126, 204, 0.1); } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive .oo-ui-labelElement-label, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-progressive .oo-ui-labelElement-label { font-weight: bold; } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-destructive:hover, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-destructive:hover { background-color: rgba(212, 83, 83, 0.05); } .oo-ui-processDialog-actions-safe .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-destructive:active, .oo-ui-processDialog-actions-primary .oo-ui-actionWidget.oo-ui-buttonElement-frameless.oo-ui-flaggedElement-destructive:active { background-color: rgba(212, 83, 83, 0.1); } .oo-ui-processDialog-actions-other .oo-ui-actionWidget.oo-ui-buttonElement { margin-right: 0; } .oo-ui-processDialog > .oo-ui-window-frame { min-height: 5em; } .oo-ui-processDialog-errors { background-color: rgba(255, 255, 255, 0.9); padding: 3em 3em 1.5em 3em; text-align: center; } .oo-ui-processDialog-errors .oo-ui-buttonWidget { margin: 2em 1em 2em 1em; } .oo-ui-processDialog-errors-title { font-size: 1.5em; color: #000; margin-bottom: 2em; } .oo-ui-processDialog-error { text-align: left; margin: 1em; padding: 1em; border: 1px solid #d33; background-color: #fff7f7; border-radius: 2px; } .oo-ui-windowManager-modal > .oo-ui-dialog { position: fixed; width: 0; height: 0; overflow: hidden; z-index: 4; } .oo-ui-windowManager-modal > .oo-ui-dialog.oo-ui-window-active { width: auto; height: auto; top: 0; right: 0; bottom: 0; left: 0; padding: 1em; } .oo-ui-windowManager-modal > .oo-ui-dialog.oo-ui-window-active > .oo-ui-window-frame { position: absolute; right: 0; left: 0; margin: auto; max-width: 100%; max-height: 100%; } .oo-ui-windowManager-fullscreen > .oo-ui-dialog > .oo-ui-window-frame { width: 100%; height: 100%; top: 0; bottom: 0; } .oo-ui-windowManager-modal > .oo-ui-dialog { background-color: rgba(255, 255, 255, 0.5); opacity: 0; -webkit-transition: opacity ease-out 250ms; -moz-transition: opacity ease-out 250ms; transition: opacity ease-out 250ms; } .oo-ui-windowManager-modal > .oo-ui-dialog > .oo-ui-window-frame { background-color: #fff; opacity: 0; -webkit-transform: scale(0.5); -moz-transform: scale(0.5); -ms-transform: scale(0.5); transform: scale(0.5); -webkit-transition: all ease-out 250ms; -moz-transition: all ease-out 250ms; transition: all ease-out 250ms; } .oo-ui-windowManager-modal > .oo-ui-dialog.oo-ui-window-setup { opacity: 1; } .oo-ui-windowManager-modal > .oo-ui-dialog.oo-ui-window-setup > .oo-ui-window-frame { opacity: 1; -webkit-transform: scale(1); -moz-transform: scale(1); -ms-transform: scale(1); transform: scale(1); } .oo-ui-windowManager-modal.oo-ui-windowManager-floating > .oo-ui-dialog > .oo-ui-window-frame { top: 1em; bottom: 1em; max-height: 100%; max-height: calc( 100% - 2em ); border: 1px solid #a2a9b1; border-radius: 2px; box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.25); }
{ "content_hash": "01ffd795dece43ecd76e86c12ef7dba3", "timestamp": "", "source": "github", "line_count": 386, "max_line_length": 161, "avg_line_length": 33.818652849740936, "alnum_prop": 0.7385475716255554, "repo_name": "joeyparrish/cdnjs", "id": "8d12c165e78d5c31c812c8b630fee61d42576234", "size": "13276", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "ajax/libs/oojs-ui/0.28.0/oojs-ui-windows-wikimediaui.css", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php namespace DTS\eBaySDK\Trading\Types; /** * * @property string $TimeZoneID * @property string $StandardLabel * @property string $StandardOffset * @property string $DaylightSavingsLabel * @property string $DaylightSavingsOffset * @property boolean $DaylightSavingsInEffect * @property string $DetailVersion * @property \DateTime $UpdateTime */ class TimeZoneDetailsType extends \DTS\eBaySDK\Types\BaseType { /** * @var array Properties belonging to objects of this class. */ private static $propertyTypes = array( 'TimeZoneID' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'TimeZoneID' ), 'StandardLabel' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'StandardLabel' ), 'StandardOffset' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'StandardOffset' ), 'DaylightSavingsLabel' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'DaylightSavingsLabel' ), 'DaylightSavingsOffset' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'DaylightSavingsOffset' ), 'DaylightSavingsInEffect' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'DaylightSavingsInEffect' ), 'DetailVersion' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'DetailVersion' ), 'UpdateTime' => array( 'type' => 'DateTime', 'unbound' => false, 'attribute' => false, 'elementName' => 'UpdateTime' ) ); /** * @param array $values Optional properties and values to assign to the object. */ public function __construct(array $values = array()) { list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values); parent::__construct($parentValues); if (!array_key_exists(__CLASS__, self::$properties)) { self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes); } if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) { self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents'; } $this->setValues(__CLASS__, $childValues); } }
{ "content_hash": "f88652086eec5c2d9e689d3ddf120644", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 116, "avg_line_length": 30.630434782608695, "alnum_prop": 0.5305180979418027, "repo_name": "emullaraj/ebay-sdk-php", "id": "30720db80d927c6edd6b625bfa85d0e4ab205757", "size": "3548", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/DTS/eBaySDK/Trading/Types/TimeZoneDetailsType.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "1933" }, { "name": "PHP", "bytes": "8374034" } ], "symlink_target": "" }
'use strict'; const redis = require('redis'), Cacheman = require('cacheman-redis'); const client = redis.createClient({ url: process.env.REDIS_URL || process.env.REDISCLOUD_URL, no_ready_check: true }); client.on('error', err => console.error(err) ); client.cache = new Cacheman(client); module.exports = client;
{ "content_hash": "66f69658c0fb03e39102635aabb3990d", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 58, "avg_line_length": 22.857142857142858, "alnum_prop": 0.703125, "repo_name": "lucasmonteverde/youtube-box", "id": "570c59f77c5dd66315a081c3c6a04da25e7cb838", "size": "320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/config/cache.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "36085" }, { "name": "JavaScript", "bytes": "37767" }, { "name": "SCSS", "bytes": "6685" } ], "symlink_target": "" }
<?php header('Transfer-Encoding: chunked'); echo "e\r\n"; echo "This is a test\r\n";
{ "content_hash": "eb12c8c982b385b2b3d36aca52a77e7b", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 37, "avg_line_length": 12.571428571428571, "alnum_prop": 0.6363636363636364, "repo_name": "econosys-system/flatmemo", "id": "d5af4f8b2bd9baf8b4a55ec0663fb448fd98f62d", "size": "689", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "flatmemo/vendor/pear/http_request2/tests/_network/bug20228.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20450" }, { "name": "HTML", "bytes": "69860" }, { "name": "JavaScript", "bytes": "363028" }, { "name": "PHP", "bytes": "627819" }, { "name": "Shell", "bytes": "4517" }, { "name": "Smarty", "bytes": "3562" } ], "symlink_target": "" }
require 'ffi' module LibNova module Data class HypOrbit < FFI::Struct # Hyperbolic Orbital elements # Maps to struct ln_hyp_orbit # http://libnova.sourceforge.net/structln__hyp__orbit.html layout :q, :double, # Perihelion distance (AU) :e, :double, # Eccentricity :i, :double, # Inclination (degrees) :w, :double, # Argument of perihelion (degrees) :omega, :double, # Longitude of ascending node (degrees) :jd, :double # Time of last passage in Perihelion (julian day) end end end
{ "content_hash": "96941e81d1ecccd5393deeb37406185f", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 79, "avg_line_length": 30.3, "alnum_prop": 0.5858085808580858, "repo_name": "hosh/libnova-ffi", "id": "5498ee3bdbd3214322726b2272d864667e27d56d", "size": "606", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/libnova-ffi/data/hyp_orbit.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "4070" } ], "symlink_target": "" }
<?php namespace CodeIgniter\Cookie; use CodeIgniter\Cookie\Exceptions\CookieException; use CodeIgniter\Test\CIUnitTestCase; use Config\Cookie as CookieConfig; use DateTimeImmutable; use DateTimeZone; use InvalidArgumentException; use LogicException; /** * @internal */ final class CookieTest extends CIUnitTestCase { private array $defaults; protected function setUp(): void { parent::setUp(); $this->defaults = Cookie::setDefaults(); } protected function tearDown(): void { Cookie::setDefaults($this->defaults); } public function testCookieInitializationWithDefaults(): void { $cookie = new Cookie('test', 'value'); $options = Cookie::setDefaults(); $this->assertSame($options['prefix'] . 'test', $cookie->getPrefixedName()); $this->assertSame('test', $cookie->getName()); $this->assertSame('value', $cookie->getValue()); $this->assertSame($options['prefix'], $cookie->getPrefix()); $this->assertSame($options['expires'], $cookie->getExpiresTimestamp()); $this->assertSame($options['path'], $cookie->getPath()); $this->assertSame($options['domain'], $cookie->getDomain()); $this->assertSame($options['secure'], $cookie->isSecure()); $this->assertSame($options['httponly'], $cookie->isHTTPOnly()); $this->assertSame($options['samesite'], $cookie->getSameSite()); $this->assertSame($options['raw'], $cookie->isRaw()); } public function testConfigInjectionForDefaults(): void { /** * @var CookieConfig $config */ $config = new CookieConfig(); $old = Cookie::setDefaults($config); $cookie = new Cookie('test', 'value'); $this->assertSame($config->prefix . 'test', $cookie->getPrefixedName()); $this->assertSame('test', $cookie->getName()); $this->assertSame('value', $cookie->getValue()); $this->assertSame($config->prefix, $cookie->getPrefix()); $this->assertSame($config->expires, $cookie->getExpiresTimestamp()); $this->assertSame($config->path, $cookie->getPath()); $this->assertSame($config->domain, $cookie->getDomain()); $this->assertSame($config->secure, $cookie->isSecure()); $this->assertSame($config->httponly, $cookie->isHTTPOnly()); $this->assertSame($config->samesite, $cookie->getSameSite()); $this->assertSame($config->raw, $cookie->isRaw()); Cookie::setDefaults($old); } public function testValidationOfRawCookieName(): void { $this->expectException(CookieException::class); new Cookie("test;\n", '', ['raw' => true]); } public function testValidationOfEmptyCookieName(): void { $this->expectException(CookieException::class); new Cookie('', 'value'); } public function testValidationOfSecurePrefix(): void { $this->expectException(CookieException::class); new Cookie('test', 'value', ['prefix' => '__Secure-', 'secure' => false]); } public function testValidationOfHostPrefix(): void { $this->expectException(CookieException::class); new Cookie('test', 'value', ['prefix' => '__Host-', 'domain' => 'localhost']); } public function testValidationOfSameSite(): void { Cookie::setDefaults(['samesite' => '']); $this->assertInstanceOf(Cookie::class, new Cookie('test')); $this->expectException(CookieException::class); new Cookie('test', '', ['samesite' => 'Yes']); } public function testValidationOfSameSiteNone(): void { $this->expectException(CookieException::class); new Cookie('test', '', ['samesite' => Cookie::SAMESITE_NONE, 'secure' => false]); } public function testExpirationTime(): void { // expires => 0 $cookie = new Cookie('test', 'value'); $this->assertSame(0, $cookie->getExpiresTimestamp()); $this->assertSame('Thu, 01-Jan-1970 00:00:00 GMT', $cookie->getExpiresString()); $this->assertTrue($cookie->isExpired()); $this->assertSame(0, $cookie->getMaxAge()); $date = new DateTimeImmutable('2021-01-10 00:00:00 GMT', new DateTimeZone('UTC')); $cookie = new Cookie('test', 'value', ['expires' => $date]); $this->assertSame((int) $date->format('U'), $cookie->getExpiresTimestamp()); $this->assertSame('Sun, 10-Jan-2021 00:00:00 GMT', $cookie->getExpiresString()); } /** * @dataProvider invalidExpiresProvider * * @param mixed $expires */ public function testInvalidExpires($expires): void { $this->expectException(CookieException::class); new Cookie('test', 'value', ['expires' => $expires]); } public static function invalidExpiresProvider(): iterable { $cases = [ 'non-numeric-string' => ['yes'], 'boolean' => [true], 'float' => [10.0], ]; foreach ($cases as $type => $case) { yield $type => $case; } } /** * @dataProvider setCookieHeaderProvider */ public function testSetCookieHeaderCreation(string $header, array $changed): void { $cookie = Cookie::fromHeaderString($header); $cookie = $cookie->toArray(); $this->assertSame(array_merge($cookie, $changed), $cookie); } public static function setCookieHeaderProvider(): iterable { yield 'basic' => [ 'test=value', ['name' => 'test', 'value' => 'value'], ]; yield 'empty-value' => [ 'test', ['name' => 'test', 'value' => ''], ]; yield 'with-other-attrs' => [ 'test=value; Max-Age=3600; Path=/web', ['name' => 'test', 'value' => 'value', 'path' => '/web'], ]; yield 'with-flags' => [ 'test=value; Secure; HttpOnly; SameSite=Lax', ['name' => 'test', 'value' => 'value', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax'], ]; } public function testValidNamePerRfcYieldsSameNameRegardlessOfRawParam(): void { $cookie1 = new Cookie('testing', '', ['raw' => false]); $cookie2 = new Cookie('testing', '', ['raw' => true]); $this->assertSame($cookie1->getPrefixedName(), $cookie2->getPrefixedName()); } public function testCloningCookies(): void { $a = new Cookie('dev', 'cookie'); $b = $a->withRaw(); $c = $a->withPrefix('my_'); $d = $a->withName('prod'); $e = $a->withValue('muffin'); $f = $a->withExpires('+30 days'); $g = $a->withExpired(); $h = $a->withNeverExpiring(); $i = $a->withDomain('localhost'); $j = $a->withPath('/web'); $k = $a->withSecure(); $l = $a->withHTTPOnly(); $m = $a->withSameSite(Cookie::SAMESITE_STRICT); $this->assertNotSame($a, $b); $this->assertNotSame($a, $c); $this->assertNotSame($a, $d); $this->assertNotSame($a, $e); $this->assertNotSame($a, $f); $this->assertNotSame($a, $g); $this->assertNotSame($a, $h); $this->assertNotSame($a, $i); $this->assertNotSame($a, $j); $this->assertNotSame($a, $k); $this->assertNotSame($a, $l); $this->assertNotSame($a, $m); } public function testStringCastingOfCookies(): void { $date = new DateTimeImmutable('2021-02-14 00:00:00 GMT', new DateTimeZone('UTC')); $a = new Cookie('cookie', 'lover'); $b = $a->withValue('monster')->withPath('/web')->withDomain('localhost')->withExpires($date); $c = $a->withSecure()->withHTTPOnly(false)->withSameSite(Cookie::SAMESITE_STRICT); $max = (string) $b->getMaxAge(); $old = Cookie::setDefaults(['samesite' => '']); $d = $a->withValue('')->withSameSite(''); $this->assertSame( 'cookie=lover; Path=/; HttpOnly; SameSite=Lax', $a->toHeaderString() ); $this->assertSame( "cookie=monster; Expires=Sun, 14-Feb-2021 00:00:00 GMT; Max-Age={$max}; Path=/web; Domain=localhost; HttpOnly; SameSite=Lax", (string) $b ); $this->assertSame( 'cookie=lover; Path=/; Secure; SameSite=Strict', (string) $c ); $this->assertSame( 'cookie=deleted; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/; HttpOnly; SameSite=Lax', (string) $d ); Cookie::setDefaults($old); } public function testArrayAccessOfCookie(): void { $cookie = new Cookie('cookie', 'monster'); $this->assertArrayHasKey('expire', $cookie); $this->assertSame($cookie['expire'], $cookie->getExpiresTimestamp()); $this->assertArrayHasKey('httponly', $cookie); $this->assertSame($cookie['httponly'], $cookie->isHTTPOnly()); $this->assertArrayHasKey('samesite', $cookie); $this->assertSame($cookie['samesite'], $cookie->getSameSite()); $this->assertArrayHasKey('path', $cookie); $this->assertSame($cookie['path'], $cookie->getPath()); $this->expectException(InvalidArgumentException::class); $cookie['expiry']; } public function testCannotSetPropertyViaArrayAccess(): void { $this->expectException(LogicException::class); $cookie = new Cookie('cookie', 'monster'); $cookie['expires'] = 7200; } public function testCannotUnsetPropertyViaArrayAccess(): void { $this->expectException(LogicException::class); $cookie = new Cookie('cookie', 'monster'); unset($cookie['path']); } }
{ "content_hash": "76559c3aaea669febc15d72ae076249e", "timestamp": "", "source": "github", "line_count": 287, "max_line_length": 137, "avg_line_length": 34.20209059233449, "alnum_prop": 0.57059902200489, "repo_name": "bcit-ci/CodeIgniter4", "id": "34d9d59955e60b1753d619678ff72b9b7dc43031", "size": "10059", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "tests/system/Cookie/CookieTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "BlitzBasic", "bytes": "2795" }, { "name": "CSS", "bytes": "143659" }, { "name": "HTML", "bytes": "24162" }, { "name": "Hack", "bytes": "2832" }, { "name": "JavaScript", "bytes": "23661" }, { "name": "Makefile", "bytes": "4622" }, { "name": "PHP", "bytes": "2728879" }, { "name": "Python", "bytes": "11561" }, { "name": "Shell", "bytes": "10172" } ], "symlink_target": "" }
package com.sun.jini.test.spec.jeri.basicjeritrustverifier.util; /** * Implementation class for test remote services */ public class TestServiceImpl implements TestService { private final static String returnVal = "I did something"; public Object doSomething() { return returnVal; } }
{ "content_hash": "2b76013e31183cbcbdf126f820c478b8", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 64, "avg_line_length": 20.8, "alnum_prop": 0.7243589743589743, "repo_name": "cdegroot/river", "id": "a06c06ef3fb6f86187f93d61718f6978ab32c33a", "size": "1118", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "qa/src/com/sun/jini/test/spec/jeri/basicjeritrustverifier/util/TestServiceImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2047" }, { "name": "Groovy", "bytes": "16876" }, { "name": "Java", "bytes": "22265383" }, { "name": "Shell", "bytes": "117083" } ], "symlink_target": "" }
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "CNullDriver.h" #include "os.h" #include "CImage.h" #include "CAttributes.h" #include "IReadFile.h" #include "IWriteFile.h" #include "IImageLoader.h" #include "IImageWriter.h" #include "IMaterialRenderer.h" #include "IAnimatedMeshSceneNode.h" #include "CMeshManipulator.h" #include "CColorConverter.h" #include "IAttributeExchangingObject.h" namespace irr { namespace video { //! creates a loader which is able to load windows bitmaps IImageLoader* createImageLoaderBMP(); //! creates a loader which is able to load jpeg images IImageLoader* createImageLoaderJPG(); //! creates a loader which is able to load targa images IImageLoader* createImageLoaderTGA(); //! creates a loader which is able to load psd images IImageLoader* createImageLoaderPSD(); //! creates a loader which is able to load dds images IImageLoader* createImageLoaderDDS(); //! creates a loader which is able to load pcx images IImageLoader* createImageLoaderPCX(); //! creates a loader which is able to load png images IImageLoader* createImageLoaderPNG(); //! creates a loader which is able to load WAL images IImageLoader* createImageLoaderWAL(); //! creates a loader which is able to load halflife images IImageLoader* createImageLoaderHalfLife(); //! creates a loader which is able to load lmp images IImageLoader* createImageLoaderLMP(); //! creates a loader which is able to load ppm/pgm/pbm images IImageLoader* createImageLoaderPPM(); //! creates a loader which is able to load rgb images IImageLoader* createImageLoaderRGB(); //! creates a writer which is able to save bmp images IImageWriter* createImageWriterBMP(); //! creates a writer which is able to save jpg images IImageWriter* createImageWriterJPG(); //! creates a writer which is able to save tga images IImageWriter* createImageWriterTGA(); //! creates a writer which is able to save psd images IImageWriter* createImageWriterPSD(); //! creates a writer which is able to save pcx images IImageWriter* createImageWriterPCX(); //! creates a writer which is able to save png images IImageWriter* createImageWriterPNG(); //! creates a writer which is able to save ppm images IImageWriter* createImageWriterPPM(); //! constructor CNullDriver::CNullDriver(io::IFileSystem* io, const core::dimension2d<u32>& screenSize) : FileSystem(io), MeshManipulator(0), ViewPort(0,0,0,0), ScreenSize(screenSize), PrimitivesDrawn(0), MinVertexCountForVBO(500), TextureCreationFlags(0), OverrideMaterial2DEnabled(false), AllowZWriteOnTransparent(false) { #ifdef _DEBUG setDebugName("CNullDriver"); #endif DriverAttributes = new io::CAttributes(); DriverAttributes->addInt("MaxTextures", _IRR_MATERIAL_MAX_TEXTURES_); DriverAttributes->addInt("MaxSupportedTextures", _IRR_MATERIAL_MAX_TEXTURES_); DriverAttributes->addInt("MaxLights", getMaximalDynamicLightAmount()); DriverAttributes->addInt("MaxAnisotropy", 1); // DriverAttributes->addInt("MaxUserClipPlanes", 0); // DriverAttributes->addInt("MaxAuxBuffers", 0); DriverAttributes->addInt("MaxMultipleRenderTargets", 1); DriverAttributes->addInt("MaxIndices", -1); DriverAttributes->addInt("MaxTextureSize", -1); // DriverAttributes->addInt("MaxGeometryVerticesOut", 0); // DriverAttributes->addFloat("MaxTextureLODBias", 0.f); DriverAttributes->addInt("Version", 1); // DriverAttributes->addInt("ShaderLanguageVersion", 0); // DriverAttributes->addInt("AntiAlias", 0); setFog(); setTextureCreationFlag(ETCF_ALWAYS_32_BIT, true); setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, true); ViewPort = core::rect<s32>(core::position2d<s32>(0,0), core::dimension2di(screenSize)); // create manipulator MeshManipulator = new scene::CMeshManipulator(); if (FileSystem) FileSystem->grab(); // create surface loader #ifdef _IRR_COMPILE_WITH_HALFLIFE_LOADER_ SurfaceLoader.push_back(video::createImageLoaderHalfLife()); #endif #ifdef _IRR_COMPILE_WITH_WAL_LOADER_ SurfaceLoader.push_back(video::createImageLoaderWAL()); #endif #ifdef _IRR_COMPILE_WITH_LMP_LOADER_ SurfaceLoader.push_back(video::createImageLoaderLMP()); #endif #ifdef _IRR_COMPILE_WITH_PPM_LOADER_ SurfaceLoader.push_back(video::createImageLoaderPPM()); #endif #ifdef _IRR_COMPILE_WITH_RGB_LOADER_ SurfaceLoader.push_back(video::createImageLoaderRGB()); #endif #ifdef _IRR_COMPILE_WITH_PSD_LOADER_ SurfaceLoader.push_back(video::createImageLoaderPSD()); #endif #ifdef _IRR_COMPILE_WITH_DDS_LOADER_ SurfaceLoader.push_back(video::createImageLoaderDDS()); #endif #ifdef _IRR_COMPILE_WITH_PCX_LOADER_ SurfaceLoader.push_back(video::createImageLoaderPCX()); #endif #ifdef _IRR_COMPILE_WITH_TGA_LOADER_ SurfaceLoader.push_back(video::createImageLoaderTGA()); #endif #ifdef _IRR_COMPILE_WITH_PNG_LOADER_ SurfaceLoader.push_back(video::createImageLoaderPNG()); #endif #ifdef _IRR_COMPILE_WITH_JPG_LOADER_ SurfaceLoader.push_back(video::createImageLoaderJPG()); #endif #ifdef _IRR_COMPILE_WITH_BMP_LOADER_ SurfaceLoader.push_back(video::createImageLoaderBMP()); #endif #ifdef _IRR_COMPILE_WITH_PPM_WRITER_ SurfaceWriter.push_back(video::createImageWriterPPM()); #endif #ifdef _IRR_COMPILE_WITH_PCX_WRITER_ SurfaceWriter.push_back(video::createImageWriterPCX()); #endif #ifdef _IRR_COMPILE_WITH_PSD_WRITER_ SurfaceWriter.push_back(video::createImageWriterPSD()); #endif #ifdef _IRR_COMPILE_WITH_TGA_WRITER_ SurfaceWriter.push_back(video::createImageWriterTGA()); #endif #ifdef _IRR_COMPILE_WITH_JPG_WRITER_ SurfaceWriter.push_back(video::createImageWriterJPG()); #endif #ifdef _IRR_COMPILE_WITH_PNG_WRITER_ SurfaceWriter.push_back(video::createImageWriterPNG()); #endif #ifdef _IRR_COMPILE_WITH_BMP_WRITER_ SurfaceWriter.push_back(video::createImageWriterBMP()); #endif // set ExposedData to 0 memset(&ExposedData, 0, sizeof(ExposedData)); for (u32 i=0; i<video::EVDF_COUNT; ++i) FeatureEnabled[i]=true; InitMaterial2D.AntiAliasing=video::EAAM_OFF; InitMaterial2D.Lighting=false; InitMaterial2D.ZWriteEnable=false; InitMaterial2D.ZBuffer=video::ECFN_NEVER; InitMaterial2D.UseMipMaps=false; for (u32 i=0; i<video::MATERIAL_MAX_TEXTURES; ++i) { InitMaterial2D.TextureLayer[i].BilinearFilter=false; InitMaterial2D.TextureLayer[i].TextureWrapU=video::ETC_REPEAT; InitMaterial2D.TextureLayer[i].TextureWrapV=video::ETC_REPEAT; } OverrideMaterial2D=InitMaterial2D; } //! destructor CNullDriver::~CNullDriver() { if (DriverAttributes) DriverAttributes->drop(); if (FileSystem) FileSystem->drop(); if (MeshManipulator) MeshManipulator->drop(); deleteAllTextures(); u32 i; for (i=0; i<SurfaceLoader.size(); ++i) SurfaceLoader[i]->drop(); for (i=0; i<SurfaceWriter.size(); ++i) SurfaceWriter[i]->drop(); // delete material renderers deleteMaterialRenders(); // delete hardware mesh buffers removeAllHardwareBuffers(); } //! Adds an external surface loader to the engine. void CNullDriver::addExternalImageLoader(IImageLoader* loader) { if (!loader) return; loader->grab(); SurfaceLoader.push_back(loader); } //! Adds an external surface writer to the engine. void CNullDriver::addExternalImageWriter(IImageWriter* writer) { if (!writer) return; writer->grab(); SurfaceWriter.push_back(writer); } //! Retrieve the number of image loaders u32 CNullDriver::getImageLoaderCount() const { return SurfaceLoader.size(); } //! Retrieve the given image loader IImageLoader* CNullDriver::getImageLoader(u32 n) { if (n < SurfaceLoader.size()) return SurfaceLoader[n]; return 0; } //! Retrieve the number of image writers u32 CNullDriver::getImageWriterCount() const { return SurfaceWriter.size(); } //! Retrieve the given image writer IImageWriter* CNullDriver::getImageWriter(u32 n) { if (n < SurfaceWriter.size()) return SurfaceWriter[n]; return 0; } //! deletes all textures void CNullDriver::deleteAllTextures() { // we need to remove previously set textures which might otherwise be kept in the // last set material member. Could be optimized to reduce state changes. setMaterial(SMaterial()); for (u32 i=0; i<Textures.size(); ++i) Textures[i].Surface->drop(); Textures.clear(); } //! applications must call this method before performing any rendering. returns false if failed. bool CNullDriver::beginScene(bool backBuffer, bool zBuffer, SColor color, const SExposedVideoData& videoData, core::rect<s32>* sourceRect) { core::clearFPUException(); PrimitivesDrawn = 0; return true; } //! applications must call this method after performing any rendering. returns false if failed. bool CNullDriver::endScene() { FPSCounter.registerFrame(os::Timer::getRealTime(), PrimitivesDrawn); updateAllHardwareBuffers(); updateAllOcclusionQueries(); return true; } //! Disable a feature of the driver. void CNullDriver::disableFeature(E_VIDEO_DRIVER_FEATURE feature, bool flag) { FeatureEnabled[feature]=!flag; } //! queries the features of the driver, returns true if feature is available bool CNullDriver::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const { return false; } //! Get attributes of the actual video driver const io::IAttributes& CNullDriver::getDriverAttributes() const { return *DriverAttributes; } //! sets transformation void CNullDriver::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) { } //! Returns the transformation set by setTransform const core::matrix4& CNullDriver::getTransform(E_TRANSFORMATION_STATE state) const { return TransformationMatrix; } //! sets a material void CNullDriver::setMaterial(const SMaterial& material) { } //! Removes a texture from the texture cache and deletes it, freeing lot of //! memory. void CNullDriver::removeTexture(ITexture* texture) { if (!texture) return; for (u32 i=0; i<Textures.size(); ++i) { if (Textures[i].Surface == texture) { texture->drop(); Textures.erase(i); } } } //! Removes all texture from the texture cache and deletes them, freeing lot of //! memory. void CNullDriver::removeAllTextures() { setMaterial ( SMaterial() ); deleteAllTextures(); } //! Returns a texture by index ITexture* CNullDriver::getTextureByIndex(u32 i) { if ( i < Textures.size() ) return Textures[i].Surface; return 0; } //! Returns amount of textures currently loaded u32 CNullDriver::getTextureCount() const { return Textures.size(); } //! Renames a texture void CNullDriver::renameTexture(ITexture* texture, const io::path& newName) { // we can do a const_cast here safely, the name of the ITexture interface // is just readonly to prevent the user changing the texture name without invoking // this method, because the textures will need resorting afterwards io::SNamedPath& name = const_cast<io::SNamedPath&>(texture->getName()); name.setPath(newName); Textures.sort(); } //! loads a Texture ITexture* CNullDriver::getTexture(const io::path& filename) { // Identify textures by their absolute filenames if possible. const io::path absolutePath = FileSystem->getAbsolutePath(filename); ITexture* texture = findTexture(absolutePath); if (texture) return texture; // Then try the raw filename, which might be in an Archive texture = findTexture(filename); if (texture) return texture; // Now try to open the file using the complete path. io::IReadFile* file = FileSystem->createAndOpenFile(absolutePath); if (!file) { // Try to open it using the raw filename. file = FileSystem->createAndOpenFile(filename); } if (file) { // Re-check name for actual archive names texture = findTexture(file->getFileName()); if (texture) { file->drop(); return texture; } texture = loadTextureFromFile(file); file->drop(); if (texture) { addTexture(texture); texture->drop(); // drop it because we created it, one grab too much } else os::Printer::log("Could not load texture", filename, ELL_ERROR); return texture; } else { os::Printer::log("Could not open file of texture", filename, ELL_WARNING); return 0; } } //! loads a Texture ITexture* CNullDriver::getTexture(io::IReadFile* file) { ITexture* texture = 0; if (file) { texture = findTexture(file->getFileName()); if (texture) return texture; texture = loadTextureFromFile(file); if (texture) { addTexture(texture); texture->drop(); // drop it because we created it, one grab too much } if (!texture) os::Printer::log("Could not load texture", file->getFileName(), ELL_WARNING); } return texture; } //! opens the file and loads it into the surface video::ITexture* CNullDriver::loadTextureFromFile(io::IReadFile* file, const io::path& hashName ) { ITexture* texture = 0; IImage* image = createImageFromFile(file); if (image) { // create texture from surface texture = createDeviceDependentTexture(image, hashName.size() ? hashName : file->getFileName() ); os::Printer::log("Loaded texture", file->getFileName()); image->drop(); } return texture; } //! adds a surface, not loaded or created by the Irrlicht Engine void CNullDriver::addTexture(video::ITexture* texture) { if (texture) { SSurface s; s.Surface = texture; texture->grab(); Textures.push_back(s); // the new texture is now at the end of the texture list. when searching for // the next new texture, the texture array will be sorted and the index of this texture // will be changed. to let the order be more consistent to the user, sort // the textures now already although this isn't necessary: Textures.sort(); } } //! looks if the image is already loaded video::ITexture* CNullDriver::findTexture(const io::path& filename) { SSurface s; SDummyTexture dummy(filename); s.Surface = &dummy; s32 index = Textures.binary_search(s); if (index != -1) return Textures[index].Surface; return 0; } //! Creates a texture from a loaded IImage. ITexture* CNullDriver::addTexture(const io::path& name, IImage* image, void* mipmapData) { if ( 0 == name.size() || !image) return 0; ITexture* t = createDeviceDependentTexture(image, name, mipmapData); if (t) { addTexture(t); t->drop(); } return t; } //! creates a Texture ITexture* CNullDriver::addTexture(const core::dimension2d<u32>& size, const io::path& name, ECOLOR_FORMAT format) { if(IImage::isRenderTargetOnlyFormat(format)) { os::Printer::log("Could not create ITexture, format only supported for render target textures.", ELL_WARNING); return 0; } if ( 0 == name.size () ) return 0; IImage* image = new CImage(format, size); ITexture* t = createDeviceDependentTexture(image, name); image->drop(); addTexture(t); if (t) t->drop(); return t; } //! returns a device dependent texture from a software surface (IImage) //! THIS METHOD HAS TO BE OVERRIDDEN BY DERIVED DRIVERS WITH OWN TEXTURES ITexture* CNullDriver::createDeviceDependentTexture(IImage* surface, const io::path& name, void* mipmapData) { return new SDummyTexture(name); } //! set or reset special render targets bool CNullDriver::setRenderTarget(video::E_RENDER_TARGET target, bool clearTarget, bool clearZBuffer, SColor color) { if (ERT_FRAME_BUFFER==target) return setRenderTarget(0,clearTarget, clearZBuffer, color); else return false; } //! sets a render target bool CNullDriver::setRenderTarget(video::ITexture* texture, bool clearBackBuffer, bool clearZBuffer, SColor color) { return false; } //! Sets multiple render targets bool CNullDriver::setRenderTarget(const core::array<video::IRenderTarget>& texture, bool clearBackBuffer, bool clearZBuffer, SColor color) { return false; } //! sets a viewport void CNullDriver::setViewPort(const core::rect<s32>& area) { } //! gets the area of the current viewport const core::rect<s32>& CNullDriver::getViewPort() const { return ViewPort; } //! draws a vertex primitive list void CNullDriver::drawVertexPrimitiveList(const void* vertices, u32 vertexCount, const void* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) { if ((iType==EIT_16BIT) && (vertexCount>65536)) os::Printer::log("Too many vertices for 16bit index type, render artifacts may occur."); PrimitivesDrawn += primitiveCount; } //! draws a vertex primitive list in 2d void CNullDriver::draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount, const void* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) { if ((iType==EIT_16BIT) && (vertexCount>65536)) os::Printer::log("Too many vertices for 16bit index type, render artifacts may occur."); PrimitivesDrawn += primitiveCount; } //! Draws a 3d line. void CNullDriver::draw3DLine(const core::vector3df& start, const core::vector3df& end, SColor color) { } //! Draws a 3d triangle. void CNullDriver::draw3DTriangle(const core::triangle3df& triangle, SColor color) { S3DVertex vertices[3]; vertices[0].Pos=triangle.pointA; vertices[0].Color=color; vertices[0].Normal=triangle.getNormal().normalize(); vertices[0].TCoords.set(0.f,0.f); vertices[1].Pos=triangle.pointB; vertices[1].Color=color; vertices[1].Normal=vertices[0].Normal; vertices[1].TCoords.set(0.5f,1.f); vertices[2].Pos=triangle.pointC; vertices[2].Color=color; vertices[2].Normal=vertices[0].Normal; vertices[2].TCoords.set(1.f,0.f); const u16 indexList[] = {0,1,2}; drawVertexPrimitiveList(vertices, 3, indexList, 1, EVT_STANDARD, scene::EPT_TRIANGLES, EIT_16BIT); } //! Draws a 3d axis aligned box. void CNullDriver::draw3DBox(const core::aabbox3d<f32>& box, SColor color) { core::vector3df edges[8]; box.getEdges(edges); // TODO: optimize into one big drawIndexPrimitive call. draw3DLine(edges[5], edges[1], color); draw3DLine(edges[1], edges[3], color); draw3DLine(edges[3], edges[7], color); draw3DLine(edges[7], edges[5], color); draw3DLine(edges[0], edges[2], color); draw3DLine(edges[2], edges[6], color); draw3DLine(edges[6], edges[4], color); draw3DLine(edges[4], edges[0], color); draw3DLine(edges[1], edges[0], color); draw3DLine(edges[3], edges[2], color); draw3DLine(edges[7], edges[6], color); draw3DLine(edges[5], edges[4], color); } //! draws an 2d image void CNullDriver::draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos) { if (!texture) return; draw2DImage(texture,destPos, core::rect<s32>(core::position2d<s32>(0,0), core::dimension2di(texture->getOriginalSize()))); } //! draws a set of 2d images, using a color and the alpha channel of the //! texture if desired. The images are drawn beginning at pos and concatenated //! in one line. All drawings are clipped against clipRect (if != 0). //! The subtextures are defined by the array of sourceRects and are chosen //! by the indices given. void CNullDriver::draw2DImageBatch(const video::ITexture* texture, const core::position2d<s32>& pos, const core::array<core::rect<s32> >& sourceRects, const core::array<s32>& indices, s32 kerningWidth, const core::rect<s32>* clipRect, SColor color, bool useAlphaChannelOfTexture) { core::position2d<s32> target(pos); for (u32 i=0; i<indices.size(); ++i) { draw2DImage(texture, target, sourceRects[indices[i]], clipRect, color, useAlphaChannelOfTexture); target.X += sourceRects[indices[i]].getWidth(); target.X += kerningWidth; } } //! draws a set of 2d images, using a color and the alpha channel of the //! texture if desired. void CNullDriver::draw2DImageBatch(const video::ITexture* texture, const core::array<core::position2d<s32> >& positions, const core::array<core::rect<s32> >& sourceRects, const core::rect<s32>* clipRect, SColor color, bool useAlphaChannelOfTexture) { const irr::u32 drawCount = core::min_<u32>(positions.size(), sourceRects.size()); for (u32 i=0; i<drawCount; ++i) { draw2DImage(texture, positions[i], sourceRects[i], clipRect, color, useAlphaChannelOfTexture); } } //! Draws a part of the texture into the rectangle. void CNullDriver::draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect, const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect, const video::SColor* const colors, bool useAlphaChannelOfTexture) { if (destRect.isValid()) draw2DImage(texture, core::position2d<s32>(destRect.UpperLeftCorner), sourceRect, clipRect, colors?colors[0]:video::SColor(0xffffffff), useAlphaChannelOfTexture); } //! Draws a 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted. void CNullDriver::draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos, const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect, SColor color, bool useAlphaChannelOfTexture) { } //! Draws the outline of a 2d rectangle void CNullDriver::draw2DRectangleOutline(const core::recti& pos, SColor color) { draw2DLine(pos.UpperLeftCorner, core::position2di(pos.LowerRightCorner.X, pos.UpperLeftCorner.Y), color); draw2DLine(core::position2di(pos.LowerRightCorner.X, pos.UpperLeftCorner.Y), pos.LowerRightCorner, color); draw2DLine(pos.LowerRightCorner, core::position2di(pos.UpperLeftCorner.X, pos.LowerRightCorner.Y), color); draw2DLine(core::position2di(pos.UpperLeftCorner.X, pos.LowerRightCorner.Y), pos.UpperLeftCorner, color); } //! Draw a 2d rectangle void CNullDriver::draw2DRectangle(SColor color, const core::rect<s32>& pos, const core::rect<s32>* clip) { draw2DRectangle(pos, color, color, color, color, clip); } //! Draws a 2d rectangle with a gradient. void CNullDriver::draw2DRectangle(const core::rect<s32>& pos, SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, const core::rect<s32>* clip) { } //! Draws a 2d line. void CNullDriver::draw2DLine(const core::position2d<s32>& start, const core::position2d<s32>& end, SColor color) { } //! Draws a pixel void CNullDriver::drawPixel(u32 x, u32 y, const SColor & color) { } //! Draws a non filled concyclic regular 2d polyon. void CNullDriver::draw2DPolygon(core::position2d<s32> center, f32 radius, video::SColor color, s32 count) { if (count < 2) return; core::position2d<s32> first; core::position2d<s32> a,b; for (s32 j=0; j<count; ++j) { b = a; f32 p = j / (f32)count * (core::PI*2); a = center + core::position2d<s32>((s32)(sin(p)*radius), (s32)(cos(p)*radius)); if (j==0) first = a; else draw2DLine(a, b, color); } draw2DLine(a, first, color); } //! returns color format ECOLOR_FORMAT CNullDriver::getColorFormat() const { return ECF_R5G6B5; } //! returns screen size const core::dimension2d<u32>& CNullDriver::getScreenSize() const { return ScreenSize; } //! returns the current render target size, //! or the screen size if render targets are not implemented const core::dimension2d<u32>& CNullDriver::getCurrentRenderTargetSize() const { return ScreenSize; } // returns current frames per second value s32 CNullDriver::getFPS() const { return FPSCounter.getFPS(); } //! returns amount of primitives (mostly triangles) were drawn in the last frame. //! very useful method for statistics. u32 CNullDriver::getPrimitiveCountDrawn( u32 param ) const { return (0 == param) ? FPSCounter.getPrimitive() : (1 == param) ? FPSCounter.getPrimitiveAverage() : FPSCounter.getPrimitiveTotal(); } //! Sets the dynamic ambient light color. The default color is //! (0,0,0,0) which means it is dark. //! \param color: New color of the ambient light. void CNullDriver::setAmbientLight(const SColorf& color) { } //! \return Returns the name of the video driver. Example: In case of the DIRECT3D8 //! driver, it would return "Direct3D8". const wchar_t* CNullDriver::getName() const { return L"Irrlicht NullDevice"; } //! Draws a shadow volume into the stencil buffer. To draw a stencil shadow, do //! this: Frist, draw all geometry. Then use this method, to draw the shadow //! volume. Then, use IVideoDriver::drawStencilShadow() to visualize the shadow. void CNullDriver::drawStencilShadowVolume(const core::array<core::vector3df>& triangles, bool zfail, u32 debugDataVisible) { } //! Fills the stencil shadow with color. After the shadow volume has been drawn //! into the stencil buffer using IVideoDriver::drawStencilShadowVolume(), use this //! to draw the color of the shadow. void CNullDriver::drawStencilShadow(bool clearStencilBuffer, video::SColor leftUpEdge, video::SColor rightUpEdge, video::SColor leftDownEdge, video::SColor rightDownEdge) { } //! deletes all dynamic lights there are void CNullDriver::deleteAllDynamicLights() { Lights.set_used(0); } //! adds a dynamic light s32 CNullDriver::addDynamicLight(const SLight& light) { Lights.push_back(light); return Lights.size() - 1; } //! Turns a dynamic light on or off //! \param lightIndex: the index returned by addDynamicLight //! \param turnOn: true to turn the light on, false to turn it off void CNullDriver::turnLightOn(s32 lightIndex, bool turnOn) { // Do nothing } //! returns the maximal amount of dynamic lights the device can handle u32 CNullDriver::getMaximalDynamicLightAmount() const { return 0; } //! Returns current amount of dynamic lights set //! \return Current amount of dynamic lights set u32 CNullDriver::getDynamicLightCount() const { return Lights.size(); } //! Returns light data which was previously set by IVideoDriver::addDynamicLight(). //! \param idx: Zero based index of the light. Must be greater than 0 and smaller //! than IVideoDriver()::getDynamicLightCount. //! \return Light data. const SLight& CNullDriver::getDynamicLight(u32 idx) const { if ( idx < Lights.size() ) return Lights[idx]; else return *((SLight*)0); } //! Creates a boolean alpha channel of the texture based of an color key. void CNullDriver::makeColorKeyTexture(video::ITexture* texture, video::SColor color, bool zeroTexels) const { if (!texture) return; if (texture->getColorFormat() != ECF_A1R5G5B5 && texture->getColorFormat() != ECF_A8R8G8B8 ) { os::Printer::log("Error: Unsupported texture color format for making color key channel.", ELL_ERROR); return; } if (texture->getColorFormat() == ECF_A1R5G5B5) { u16 *p = (u16*)texture->lock(); if (!p) { os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR); return; } const core::dimension2d<u32> dim = texture->getSize(); const u32 pitch = texture->getPitch() / 2; // color with alpha disabled (i.e. fully transparent) const u16 refZeroAlpha = (0x7fff & color.toA1R5G5B5()); const u32 pixels = pitch * dim.Height; for (u32 pixel = 0; pixel < pixels; ++ pixel) { // If the color matches the reference color, ignoring alphas, // set the alpha to zero. if(((*p) & 0x7fff) == refZeroAlpha) { if(zeroTexels) (*p) = 0; else (*p) = refZeroAlpha; } ++p; } texture->unlock(); } else { u32 *p = (u32*)texture->lock(); if (!p) { os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR); return; } core::dimension2d<u32> dim = texture->getSize(); u32 pitch = texture->getPitch() / 4; // color with alpha disabled (fully transparent) const u32 refZeroAlpha = 0x00ffffff & color.color; const u32 pixels = pitch * dim.Height; for (u32 pixel = 0; pixel < pixels; ++ pixel) { // If the color matches the reference color, ignoring alphas, // set the alpha to zero. if(((*p) & 0x00ffffff) == refZeroAlpha) { if(zeroTexels) (*p) = 0; else (*p) = refZeroAlpha; } ++p; } texture->unlock(); } texture->regenerateMipMapLevels(); } //! Creates an boolean alpha channel of the texture based of an color key position. void CNullDriver::makeColorKeyTexture(video::ITexture* texture, core::position2d<s32> colorKeyPixelPos, bool zeroTexels) const { if (!texture) return; if (texture->getColorFormat() != ECF_A1R5G5B5 && texture->getColorFormat() != ECF_A8R8G8B8 ) { os::Printer::log("Error: Unsupported texture color format for making color key channel.", ELL_ERROR); return; } SColor colorKey; if (texture->getColorFormat() == ECF_A1R5G5B5) { u16 *p = (u16*)texture->lock(ETLM_READ_ONLY); if (!p) { os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR); return; } u32 pitch = texture->getPitch() / 2; const u16 key16Bit = 0x7fff & p[colorKeyPixelPos.Y*pitch + colorKeyPixelPos.X]; colorKey = video::A1R5G5B5toA8R8G8B8(key16Bit); } else { u32 *p = (u32*)texture->lock(ETLM_READ_ONLY); if (!p) { os::Printer::log("Could not lock texture for making color key channel.", ELL_ERROR); return; } u32 pitch = texture->getPitch() / 4; colorKey = 0x00ffffff & p[colorKeyPixelPos.Y*pitch + colorKeyPixelPos.X]; } texture->unlock(); makeColorKeyTexture(texture, colorKey, zeroTexels); } //! Creates a normal map from a height map texture. //! \param amplitude: Constant value by which the height information is multiplied. void CNullDriver::makeNormalMapTexture(video::ITexture* texture, f32 amplitude) const { if (!texture) return; if (texture->getColorFormat() != ECF_A1R5G5B5 && texture->getColorFormat() != ECF_A8R8G8B8 ) { os::Printer::log("Error: Unsupported texture color format for making normal map.", ELL_ERROR); return; } core::dimension2d<u32> dim = texture->getSize(); amplitude = amplitude / 255.0f; f32 vh = dim.Height / (f32)dim.Width; f32 hh = dim.Width / (f32)dim.Height; if (texture->getColorFormat() == ECF_A8R8G8B8) { // ECF_A8R8G8B8 version s32 *p = (s32*)texture->lock(); if (!p) { os::Printer::log("Could not lock texture for making normal map.", ELL_ERROR); return; } // copy texture u32 pitch = texture->getPitch() / 4; s32* in = new s32[dim.Height * pitch]; memcpy(in, p, dim.Height * pitch * 4); for (s32 x=0; x < s32(pitch); ++x) for (s32 y=0; y < s32(dim.Height); ++y) { // TODO: this could be optimized really a lot core::vector3df h1((x-1)*hh, nml32(x-1, y, pitch, dim.Height, in)*amplitude, y*vh); core::vector3df h2((x+1)*hh, nml32(x+1, y, pitch, dim.Height, in)*amplitude, y*vh); //core::vector3df v1(x*hh, nml32(x, y-1, pitch, dim.Height, in)*amplitude, (y-1)*vh); //core::vector3df v2(x*hh, nml32(x, y+1, pitch, dim.Height, in)*amplitude, (y+1)*vh); core::vector3df v1(x*hh, nml32(x, y+1, pitch, dim.Height, in)*amplitude, (y-1)*vh); core::vector3df v2(x*hh, nml32(x, y-1, pitch, dim.Height, in)*amplitude, (y+1)*vh); core::vector3df v = v1-v2; core::vector3df h = h1-h2; core::vector3df n = v.crossProduct(h); n.normalize(); n *= 0.5f; n += core::vector3df(0.5f,0.5f,0.5f); // now between 0 and 1 n *= 255.0f; s32 height = (s32)nml32(x, y, pitch, dim.Height, in); p[y*pitch + x] = video::SColor( height, // store height in alpha (s32)n.X, (s32)n.Z, (s32)n.Y).color; } delete [] in; texture->unlock(); } else { // ECF_A1R5G5B5 version s16 *p = (s16*)texture->lock(); if (!p) { os::Printer::log("Could not lock texture for making normal map.", ELL_ERROR); return; } u32 pitch = texture->getPitch() / 2; // copy texture s16* in = new s16[dim.Height * pitch]; memcpy(in, p, dim.Height * pitch * 2); for (s32 x=0; x < s32(pitch); ++x) for (s32 y=0; y < s32(dim.Height); ++y) { // TODO: this could be optimized really a lot core::vector3df h1((x-1)*hh, nml16(x-1, y, pitch, dim.Height, in)*amplitude, y*vh); core::vector3df h2((x+1)*hh, nml16(x+1, y, pitch, dim.Height, in)*amplitude, y*vh); core::vector3df v1(x*hh, nml16(x, y-1, pitch, dim.Height, in)*amplitude, (y-1)*vh); core::vector3df v2(x*hh, nml16(x, y+1, pitch, dim.Height, in)*amplitude, (y+1)*vh); core::vector3df v = v1-v2; core::vector3df h = h1-h2; core::vector3df n = v.crossProduct(h); n.normalize(); n *= 0.5f; n += core::vector3df(0.5f,0.5f,0.5f); // now between 0 and 1 n *= 255.0f; p[y*pitch + x] = video::RGBA16((u32)n.X, (u32)n.Z, (u32)n.Y); } delete [] in; texture->unlock(); } texture->regenerateMipMapLevels(); } //! Returns the maximum amount of primitives (mostly vertices) which //! the device is able to render with one drawIndexedTriangleList //! call. u32 CNullDriver::getMaximalPrimitiveCount() const { return 0xFFFFFFFF; } //! checks triangle count and print warning if wrong bool CNullDriver::checkPrimitiveCount(u32 prmCount) const { const u32 m = getMaximalPrimitiveCount(); if (prmCount > m) { char tmp[1024]; sprintf(tmp,"Could not draw triangles, too many primitives(%u), maxium is %u.", prmCount, m); os::Printer::log(tmp, ELL_ERROR); return false; } return true; } //! Enables or disables a texture creation flag. void CNullDriver::setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled) { if (enabled && ((flag == ETCF_ALWAYS_16_BIT) || (flag == ETCF_ALWAYS_32_BIT) || (flag == ETCF_OPTIMIZED_FOR_QUALITY) || (flag == ETCF_OPTIMIZED_FOR_SPEED))) { // disable other formats setTextureCreationFlag(ETCF_ALWAYS_16_BIT, false); setTextureCreationFlag(ETCF_ALWAYS_32_BIT, false); setTextureCreationFlag(ETCF_OPTIMIZED_FOR_QUALITY, false); setTextureCreationFlag(ETCF_OPTIMIZED_FOR_SPEED, false); } // set flag TextureCreationFlags = (TextureCreationFlags & (~flag)) | ((((u32)!enabled)-1) & flag); } //! Returns if a texture creation flag is enabled or disabled. bool CNullDriver::getTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag) const { return (TextureCreationFlags & flag)!=0; } //! Creates a software image from a file. IImage* CNullDriver::createImageFromFile(const io::path& filename) { if (!filename.size()) return 0; IImage* image = 0; io::IReadFile* file = FileSystem->createAndOpenFile(filename); if (file) { image = createImageFromFile(file); file->drop(); } else os::Printer::log("Could not open file of image", filename, ELL_WARNING); return image; } //! Creates a software image from a file. IImage* CNullDriver::createImageFromFile(io::IReadFile* file) { if (!file) return 0; IImage* image = 0; s32 i; // try to load file based on file extension for (i=SurfaceLoader.size()-1; i>=0; --i) { if (SurfaceLoader[i]->isALoadableFileExtension(file->getFileName())) { // reset file position which might have changed due to previous loadImage calls file->seek(0); image = SurfaceLoader[i]->loadImage(file); if (image) return image; } } // try to load file based on what is in it for (i=SurfaceLoader.size()-1; i>=0; --i) { // dito file->seek(0); if (SurfaceLoader[i]->isALoadableFileFormat(file)) { file->seek(0); image = SurfaceLoader[i]->loadImage(file); if (image) return image; } } return 0; // failed to load } //! Writes the provided image to disk file bool CNullDriver::writeImageToFile(IImage* image, const io::path& filename,u32 param) { io::IWriteFile* file = FileSystem->createAndWriteFile(filename); if(!file) return false; bool result = writeImageToFile(image, file, param); file->drop(); return result; } //! Writes the provided image to a file. bool CNullDriver::writeImageToFile(IImage* image, io::IWriteFile * file, u32 param) { if(!file) return false; for (s32 i=SurfaceWriter.size()-1; i>=0; --i) { if (SurfaceWriter[i]->isAWriteableFileExtension(file->getFileName())) { bool written = SurfaceWriter[i]->writeImage(file, image, param); if (written) return true; } } return false; // failed to write } //! Creates a software image from a byte array. IImage* CNullDriver::createImageFromData(ECOLOR_FORMAT format, const core::dimension2d<u32>& size, void *data, bool ownForeignMemory, bool deleteMemory) { if(IImage::isRenderTargetOnlyFormat(format)) { os::Printer::log("Could not create IImage, format only supported for render target textures.", ELL_WARNING); return 0; } return new CImage(format, size, data, ownForeignMemory, deleteMemory); } //! Creates an empty software image. IImage* CNullDriver::createImage(ECOLOR_FORMAT format, const core::dimension2d<u32>& size) { if(IImage::isRenderTargetOnlyFormat(format)) { os::Printer::log("Could not create IImage, format only supported for render target textures.", ELL_WARNING); return 0; } return new CImage(format, size); } //! Creates a software image from another image. IImage* CNullDriver::createImage(ECOLOR_FORMAT format, IImage *imageToCopy) { os::Printer::log("Deprecated method, please create an empty image instead and use copyTo().", ELL_WARNING); if(IImage::isRenderTargetOnlyFormat(format)) { os::Printer::log("Could not create IImage, format only supported for render target textures.", ELL_WARNING); return 0; } CImage* tmp = new CImage(format, imageToCopy->getDimension()); imageToCopy->copyTo(tmp); return tmp; } //! Creates a software image from part of another image. IImage* CNullDriver::createImage(IImage* imageToCopy, const core::position2d<s32>& pos, const core::dimension2d<u32>& size) { os::Printer::log("Deprecated method, please create an empty image instead and use copyTo().", ELL_WARNING); CImage* tmp = new CImage(imageToCopy->getColorFormat(), imageToCopy->getDimension()); imageToCopy->copyTo(tmp, core::position2di(0,0), core::recti(pos,size)); return tmp; } //! Creates a software image from part of a texture. IImage* CNullDriver::createImage(ITexture* texture, const core::position2d<s32>& pos, const core::dimension2d<u32>& size) { if ((pos==core::position2di(0,0)) && (size == texture->getSize())) { IImage* image = new CImage(texture->getColorFormat(), size, texture->lock(ETLM_READ_ONLY), false); texture->unlock(); return image; } else { // make sure to avoid buffer overruns // make the vector a separate variable for g++ 3.x const core::vector2d<u32> leftUpper(core::clamp(static_cast<u32>(pos.X), 0u, texture->getSize().Width), core::clamp(static_cast<u32>(pos.Y), 0u, texture->getSize().Height)); const core::rect<u32> clamped(leftUpper, core::dimension2du(core::clamp(static_cast<u32>(size.Width), 0u, texture->getSize().Width), core::clamp(static_cast<u32>(size.Height), 0u, texture->getSize().Height))); if (!clamped.isValid()) return 0; u8* src = static_cast<u8*>(texture->lock(ETLM_READ_ONLY)); if (!src) return 0; IImage* image = new CImage(texture->getColorFormat(), clamped.getSize()); u8* dst = static_cast<u8*>(image->lock()); src += clamped.UpperLeftCorner.Y * texture->getPitch() + image->getBytesPerPixel() * clamped.UpperLeftCorner.X; for (u32 i=0; i<clamped.getHeight(); ++i) { video::CColorConverter::convert_viaFormat(src, texture->getColorFormat(), clamped.getWidth(), dst, image->getColorFormat()); src += texture->getPitch(); dst += image->getPitch(); } image->unlock(); texture->unlock(); return image; } } //! Sets the fog mode. void CNullDriver::setFog(SColor color, E_FOG_TYPE fogType, f32 start, f32 end, f32 density, bool pixelFog, bool rangeFog) { FogColor = color; FogType = fogType; FogStart = start; FogEnd = end; FogDensity = density; PixelFog = pixelFog; RangeFog = rangeFog; } //! Gets the fog mode. void CNullDriver::getFog(SColor& color, E_FOG_TYPE& fogType, f32& start, f32& end, f32& density, bool& pixelFog, bool& rangeFog) { color = FogColor; fogType = FogType; start = FogStart; end = FogEnd; density = FogDensity; pixelFog = PixelFog; rangeFog = RangeFog; } //! Draws a mesh buffer void CNullDriver::drawMeshBuffer(const scene::IMeshBuffer* mb) { if (!mb) return; //IVertexBuffer and IIndexBuffer later SHWBufferLink *HWBuffer=getBufferLink(mb); if (HWBuffer) drawHardwareBuffer(HWBuffer); else drawVertexPrimitiveList(mb->getVertices(), mb->getVertexCount(), mb->getIndices(), mb->getIndexCount()/3, mb->getVertexType(), scene::EPT_TRIANGLES, mb->getIndexType()); } //! Draws the normals of a mesh buffer void CNullDriver::drawMeshBufferNormals(const scene::IMeshBuffer* mb, f32 length, SColor color) { const u32 count = mb->getVertexCount(); const bool normalize = mb->getMaterial().NormalizeNormals; for (u32 i=0; i < count; ++i) { core::vector3df normalizedNormal = mb->getNormal(i); if (normalize) normalizedNormal.normalize(); const core::vector3df& pos = mb->getPosition(i); draw3DLine(pos, pos + (normalizedNormal * length), color); } } CNullDriver::SHWBufferLink *CNullDriver::getBufferLink(const scene::IMeshBuffer* mb) { if (!mb || !isHardwareBufferRecommend(mb)) return 0; //search for hardware links core::map< const scene::IMeshBuffer*,SHWBufferLink* >::Node* node = HWBufferMap.find(mb); if (node) return node->getValue(); return createHardwareBuffer(mb); //no hardware links, and mesh wants one, create it } //! Update all hardware buffers, remove unused ones void CNullDriver::updateAllHardwareBuffers() { core::map<const scene::IMeshBuffer*,SHWBufferLink*>::ParentFirstIterator Iterator=HWBufferMap.getParentFirstIterator(); for (;!Iterator.atEnd();Iterator++) { SHWBufferLink *Link=Iterator.getNode()->getValue(); Link->LastUsed++; if (Link->LastUsed>20000) { deleteHardwareBuffer(Link); // todo: needs better fix Iterator = HWBufferMap.getParentFirstIterator(); } } } void CNullDriver::deleteHardwareBuffer(SHWBufferLink *HWBuffer) { if (!HWBuffer) return; HWBufferMap.remove(HWBuffer->MeshBuffer); delete HWBuffer; } //! Remove hardware buffer void CNullDriver::removeHardwareBuffer(const scene::IMeshBuffer* mb) { core::map<const scene::IMeshBuffer*,SHWBufferLink*>::Node* node = HWBufferMap.find(mb); if (node) deleteHardwareBuffer(node->getValue()); } //! Remove all hardware buffers void CNullDriver::removeAllHardwareBuffers() { while (HWBufferMap.size()) deleteHardwareBuffer(HWBufferMap.getRoot()->getValue()); } bool CNullDriver::isHardwareBufferRecommend(const scene::IMeshBuffer* mb) { if (!mb || (mb->getHardwareMappingHint_Index()==scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex()==scene::EHM_NEVER)) return false; if (mb->getVertexCount()<MinVertexCountForVBO) return false; return true; } //! Create occlusion query. /** Use node for identification and mesh for occlusion test. */ void CNullDriver::addOcclusionQuery(scene::ISceneNode* node, const scene::IMesh* mesh) { if (!node) return; if (!mesh) { if ((node->getType() != scene::ESNT_MESH) && (node->getType() != scene::ESNT_ANIMATED_MESH)) return; else if (node->getType() == scene::ESNT_MESH) mesh = static_cast<scene::IMeshSceneNode*>(node)->getMesh(); else mesh = static_cast<scene::IAnimatedMeshSceneNode*>(node)->getMesh()->getMesh(0); if (!mesh) return; } //search for query s32 index = OcclusionQueries.linear_search(SOccQuery(node)); if (index != -1) { if (OcclusionQueries[index].Mesh != mesh) { OcclusionQueries[index].Mesh->drop(); OcclusionQueries[index].Mesh = mesh; mesh->grab(); } } else { OcclusionQueries.push_back(SOccQuery(node, mesh)); node->setAutomaticCulling(node->getAutomaticCulling() | scene::EAC_OCC_QUERY); } } //! Remove occlusion query. void CNullDriver::removeOcclusionQuery(scene::ISceneNode* node) { //search for query s32 index = OcclusionQueries.linear_search(SOccQuery(node)); if (index != -1) { node->setAutomaticCulling(node->getAutomaticCulling() & ~scene::EAC_OCC_QUERY); OcclusionQueries.erase(index); } } //! Remove all occlusion queries. void CNullDriver::removeAllOcclusionQueries() { for (s32 i=OcclusionQueries.size()-1; i>=0; --i) { removeOcclusionQuery(OcclusionQueries[i].Node); } } //! Run occlusion query. Draws mesh stored in query. /** If the mesh shall be rendered visible, use flag to enable the proper material setting. */ void CNullDriver::runOcclusionQuery(scene::ISceneNode* node, bool visible) { if(!node) return; s32 index = OcclusionQueries.linear_search(SOccQuery(node)); if (index==-1) return; OcclusionQueries[index].Run=0; if (!visible) { SMaterial mat; mat.Lighting=false; mat.AntiAliasing=0; mat.ColorMask=ECP_NONE; mat.GouraudShading=false; mat.ZWriteEnable=false; setMaterial(mat); } setTransform(video::ETS_WORLD, node->getAbsoluteTransformation()); const scene::IMesh* mesh = OcclusionQueries[index].Mesh; for (u32 i=0; i<mesh->getMeshBufferCount(); ++i) { if (visible) setMaterial(mesh->getMeshBuffer(i)->getMaterial()); drawMeshBuffer(mesh->getMeshBuffer(i)); } } //! Run all occlusion queries. Draws all meshes stored in queries. /** If the meshes shall not be rendered visible, use overrideMaterial to disable the color and depth buffer. */ void CNullDriver::runAllOcclusionQueries(bool visible) { for (u32 i=0; i<OcclusionQueries.size(); ++i) runOcclusionQuery(OcclusionQueries[i].Node, visible); } //! Update occlusion query. Retrieves results from GPU. /** If the query shall not block, set the flag to false. Update might not occur in this case, though */ void CNullDriver::updateOcclusionQuery(scene::ISceneNode* node, bool block) { } //! Update all occlusion queries. Retrieves results from GPU. /** If the query shall not block, set the flag to false. Update might not occur in this case, though */ void CNullDriver::updateAllOcclusionQueries(bool block) { for (u32 i=0; i<OcclusionQueries.size(); ++i) { if (OcclusionQueries[i].Run==u32(~0)) continue; updateOcclusionQuery(OcclusionQueries[i].Node, block); ++OcclusionQueries[i].Run; if (OcclusionQueries[i].Run>1000) removeOcclusionQuery(OcclusionQueries[i].Node); } } //! Return query result. /** Return value is the number of visible pixels/fragments. The value is a safe approximation, i.e. can be larger then the actual value of pixels. */ u32 CNullDriver::getOcclusionQueryResult(scene::ISceneNode* node) const { return ~0; } //! Only used by the internal engine. Used to notify the driver that //! the window was resized. void CNullDriver::OnResize(const core::dimension2d<u32>& size) { if (ViewPort.getWidth() == (s32)ScreenSize.Width && ViewPort.getHeight() == (s32)ScreenSize.Height) ViewPort = core::rect<s32>(core::position2d<s32>(0,0), core::dimension2di(size)); ScreenSize = size; } // adds a material renderer and drops it afterwards. To be used for internal creation s32 CNullDriver::addAndDropMaterialRenderer(IMaterialRenderer* m) { s32 i = addMaterialRenderer(m); if (m) m->drop(); return i; } //! Adds a new material renderer to the video device. s32 CNullDriver::addMaterialRenderer(IMaterialRenderer* renderer, const char* name) { if (!renderer) return -1; SMaterialRenderer r; r.Renderer = renderer; r.Name = name; if (name == 0 && (MaterialRenderers.size() < (sizeof(sBuiltInMaterialTypeNames) / sizeof(char*))-1 )) { // set name of built in renderer so that we don't have to implement name // setting in all available renderers. r.Name = sBuiltInMaterialTypeNames[MaterialRenderers.size()]; } MaterialRenderers.push_back(r); renderer->grab(); return MaterialRenderers.size()-1; } //! Sets the name of a material renderer. void CNullDriver::setMaterialRendererName(s32 idx, const char* name) { if (idx < s32(sizeof(sBuiltInMaterialTypeNames) / sizeof(char*))-1 || idx >= (s32)MaterialRenderers.size()) return; MaterialRenderers[idx].Name = name; } //! Creates material attributes list from a material, usable for serialization and more. io::IAttributes* CNullDriver::createAttributesFromMaterial(const video::SMaterial& material, io::SAttributeReadWriteOptions* options) { io::CAttributes* attr = new io::CAttributes(this); attr->addEnum("Type", material.MaterialType, sBuiltInMaterialTypeNames); attr->addColor("Ambient", material.AmbientColor); attr->addColor("Diffuse", material.DiffuseColor); attr->addColor("Emissive", material.EmissiveColor); attr->addColor("Specular", material.SpecularColor); attr->addFloat("Shininess", material.Shininess); attr->addFloat("Param1", material.MaterialTypeParam); attr->addFloat("Param2", material.MaterialTypeParam2); core::stringc prefix="Texture"; u32 i; for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) { if (options && (options->Flags&io::EARWF_USE_RELATIVE_PATHS) && options->Filename && material.getTexture(i)) { io::path path = FileSystem->getRelativeFilename( FileSystem->getAbsolutePath(material.getTexture(i)->getName()), options->Filename); attr->addTexture((prefix+core::stringc(i+1)).c_str(), material.getTexture(i), path); } else attr->addTexture((prefix+core::stringc(i+1)).c_str(), material.getTexture(i)); } attr->addBool("Wireframe", material.Wireframe); attr->addBool("GouraudShading", material.GouraudShading); attr->addBool("Lighting", material.Lighting); attr->addBool("ZWriteEnable", material.ZWriteEnable); attr->addInt("ZBuffer", material.ZBuffer); attr->addBool("BackfaceCulling", material.BackfaceCulling); attr->addBool("FrontfaceCulling", material.FrontfaceCulling); attr->addBool("FogEnable", material.FogEnable); attr->addBool("NormalizeNormals", material.NormalizeNormals); attr->addBool("UseMipMaps", material.UseMipMaps); attr->addInt("AntiAliasing", material.AntiAliasing); attr->addInt("ColorMask", material.ColorMask); attr->addInt("ColorMaterial", material.ColorMaterial); attr->addInt("PolygonOffsetFactor", material.PolygonOffsetFactor); attr->addEnum("PolygonOffsetDirection", material.PolygonOffsetDirection, video::PolygonOffsetDirectionNames); prefix = "BilinearFilter"; for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) attr->addBool((prefix+core::stringc(i+1)).c_str(), material.TextureLayer[i].BilinearFilter); prefix = "TrilinearFilter"; for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) attr->addBool((prefix+core::stringc(i+1)).c_str(), material.TextureLayer[i].TrilinearFilter); prefix = "AnisotropicFilter"; for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) attr->addInt((prefix+core::stringc(i+1)).c_str(), material.TextureLayer[i].AnisotropicFilter); prefix="TextureWrapU"; for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) attr->addEnum((prefix+core::stringc(i+1)).c_str(), material.TextureLayer[i].TextureWrapU, aTextureClampNames); prefix="TextureWrapV"; for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) attr->addEnum((prefix+core::stringc(i+1)).c_str(), material.TextureLayer[i].TextureWrapV, aTextureClampNames); prefix="LODBias"; for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) attr->addInt((prefix+core::stringc(i+1)).c_str(), material.TextureLayer[i].LODBias); return attr; } //! Fills an SMaterial structure from attributes. void CNullDriver::fillMaterialStructureFromAttributes(video::SMaterial& outMaterial, io::IAttributes* attr) { outMaterial.MaterialType = video::EMT_SOLID; core::stringc name = attr->getAttributeAsString("Type"); u32 i; for ( i=0; i < MaterialRenderers.size(); ++i) if ( name == MaterialRenderers[i].Name ) { outMaterial.MaterialType = (video::E_MATERIAL_TYPE)i; break; } outMaterial.AmbientColor = attr->getAttributeAsColor("Ambient"); outMaterial.DiffuseColor = attr->getAttributeAsColor("Diffuse"); outMaterial.EmissiveColor = attr->getAttributeAsColor("Emissive"); outMaterial.SpecularColor = attr->getAttributeAsColor("Specular"); outMaterial.Shininess = attr->getAttributeAsFloat("Shininess"); outMaterial.MaterialTypeParam = attr->getAttributeAsFloat("Param1"); outMaterial.MaterialTypeParam2 = attr->getAttributeAsFloat("Param2"); core::stringc prefix="Texture"; for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) outMaterial.setTexture(i, attr->getAttributeAsTexture((prefix+core::stringc(i+1)).c_str())); outMaterial.Wireframe = attr->getAttributeAsBool("Wireframe"); outMaterial.GouraudShading = attr->getAttributeAsBool("GouraudShading"); outMaterial.Lighting = attr->getAttributeAsBool("Lighting"); outMaterial.ZWriteEnable = attr->getAttributeAsBool("ZWriteEnable"); outMaterial.ZBuffer = (u8)attr->getAttributeAsInt("ZBuffer"); outMaterial.BackfaceCulling = attr->getAttributeAsBool("BackfaceCulling"); outMaterial.FrontfaceCulling = attr->getAttributeAsBool("FrontfaceCulling"); outMaterial.FogEnable = attr->getAttributeAsBool("FogEnable"); outMaterial.NormalizeNormals = attr->getAttributeAsBool("NormalizeNormals"); if (attr->existsAttribute("UseMipMaps")) // legacy outMaterial.UseMipMaps = attr->getAttributeAsBool("UseMipMaps"); else outMaterial.UseMipMaps = true; // default 0 is ok outMaterial.AntiAliasing = attr->getAttributeAsInt("AntiAliasing"); if (attr->existsAttribute("ColorMask")) outMaterial.ColorMask = attr->getAttributeAsInt("ColorMask"); if (attr->existsAttribute("ColorMaterial")) outMaterial.ColorMaterial = attr->getAttributeAsInt("ColorMaterial"); if (attr->existsAttribute("PolygonOffsetFactor")) outMaterial.PolygonOffsetFactor = attr->getAttributeAsInt("PolygonOffsetFactor"); if (attr->existsAttribute("PolygonOffsetDirection")) outMaterial.PolygonOffsetDirection = (video::E_POLYGON_OFFSET)attr->getAttributeAsEnumeration("PolygonOffsetDirection", video::PolygonOffsetDirectionNames); prefix = "BilinearFilter"; if (attr->existsAttribute(prefix.c_str())) // legacy outMaterial.setFlag(EMF_BILINEAR_FILTER, attr->getAttributeAsBool(prefix.c_str())); else for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) outMaterial.TextureLayer[i].BilinearFilter = attr->getAttributeAsBool((prefix+core::stringc(i+1)).c_str()); prefix = "TrilinearFilter"; if (attr->existsAttribute(prefix.c_str())) // legacy outMaterial.setFlag(EMF_TRILINEAR_FILTER, attr->getAttributeAsBool(prefix.c_str())); else for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) outMaterial.TextureLayer[i].TrilinearFilter = attr->getAttributeAsBool((prefix+core::stringc(i+1)).c_str()); prefix = "AnisotropicFilter"; if (attr->existsAttribute(prefix.c_str())) // legacy outMaterial.setFlag(EMF_ANISOTROPIC_FILTER, attr->getAttributeAsBool(prefix.c_str())); else for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) outMaterial.TextureLayer[i].AnisotropicFilter = attr->getAttributeAsInt((prefix+core::stringc(i+1)).c_str()); prefix = "TextureWrap"; if (attr->existsAttribute(prefix.c_str())) // legacy { for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) { outMaterial.TextureLayer[i].TextureWrapU = (E_TEXTURE_CLAMP)attr->getAttributeAsEnumeration((prefix+core::stringc(i+1)).c_str(), aTextureClampNames); outMaterial.TextureLayer[i].TextureWrapV = outMaterial.TextureLayer[i].TextureWrapU; } } else { for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) { outMaterial.TextureLayer[i].TextureWrapU = (E_TEXTURE_CLAMP)attr->getAttributeAsEnumeration((prefix+"U"+core::stringc(i+1)).c_str(), aTextureClampNames); outMaterial.TextureLayer[i].TextureWrapV = (E_TEXTURE_CLAMP)attr->getAttributeAsEnumeration((prefix+"V"+core::stringc(i+1)).c_str(), aTextureClampNames); } } // default 0 is ok prefix="LODBias"; for (i=0; i<MATERIAL_MAX_TEXTURES; ++i) outMaterial.TextureLayer[i].LODBias = attr->getAttributeAsInt((prefix+core::stringc(i+1)).c_str()); } //! Returns driver and operating system specific data about the IVideoDriver. const SExposedVideoData& CNullDriver::getExposedVideoData() { return ExposedData; } //! Returns type of video driver E_DRIVER_TYPE CNullDriver::getDriverType() const { return EDT_NULL; } //! deletes all material renderers void CNullDriver::deleteMaterialRenders() { // delete material renderers for (u32 i=0; i<MaterialRenderers.size(); ++i) if (MaterialRenderers[i].Renderer) MaterialRenderers[i].Renderer->drop(); MaterialRenderers.clear(); } //! Returns pointer to material renderer or null IMaterialRenderer* CNullDriver::getMaterialRenderer(u32 idx) { if ( idx < MaterialRenderers.size() ) return MaterialRenderers[idx].Renderer; else return 0; } //! Returns amount of currently available material renderers. u32 CNullDriver::getMaterialRendererCount() const { return MaterialRenderers.size(); } //! Returns name of the material renderer const char* CNullDriver::getMaterialRendererName(u32 idx) const { if ( idx < MaterialRenderers.size() ) return MaterialRenderers[idx].Name.c_str(); return 0; } //! Returns pointer to the IGPUProgrammingServices interface. IGPUProgrammingServices* CNullDriver::getGPUProgrammingServices() { return this; } //! Adds a new material renderer to the VideoDriver, based on a high level shading language. s32 CNullDriver::addHighLevelShaderMaterial( const c8* vertexShaderProgram, const c8* vertexShaderEntryPointName, E_VERTEX_SHADER_TYPE vsCompileTarget, const c8* pixelShaderProgram, const c8* pixelShaderEntryPointName, E_PIXEL_SHADER_TYPE psCompileTarget, const c8* geometryShaderProgram, const c8* geometryShaderEntryPointName, E_GEOMETRY_SHADER_TYPE gsCompileTarget, scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, u32 verticesOut, IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData, E_GPU_SHADING_LANGUAGE shadingLang) { os::Printer::log("High level shader materials not available (yet) in this driver, sorry"); return -1; } //! Like IGPUProgrammingServices::addShaderMaterial() (look there for a detailed description), //! but tries to load the programs from files. s32 CNullDriver::addHighLevelShaderMaterialFromFiles( const io::path& vertexShaderProgramFileName, const c8* vertexShaderEntryPointName, E_VERTEX_SHADER_TYPE vsCompileTarget, const io::path& pixelShaderProgramFileName, const c8* pixelShaderEntryPointName, E_PIXEL_SHADER_TYPE psCompileTarget, const io::path& geometryShaderProgramFileName, const c8* geometryShaderEntryPointName, E_GEOMETRY_SHADER_TYPE gsCompileTarget, scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, u32 verticesOut, IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData, E_GPU_SHADING_LANGUAGE shadingLang) { io::IReadFile* vsfile = 0; io::IReadFile* psfile = 0; io::IReadFile* gsfile = 0; if (vertexShaderProgramFileName.size() ) { vsfile = FileSystem->createAndOpenFile(vertexShaderProgramFileName); if (!vsfile) { os::Printer::log("Could not open vertex shader program file", vertexShaderProgramFileName, ELL_WARNING); } } if (pixelShaderProgramFileName.size() ) { psfile = FileSystem->createAndOpenFile(pixelShaderProgramFileName); if (!psfile) { os::Printer::log("Could not open pixel shader program file", pixelShaderProgramFileName, ELL_WARNING); } } if (geometryShaderProgramFileName.size() ) { gsfile = FileSystem->createAndOpenFile(geometryShaderProgramFileName); if (!gsfile) { os::Printer::log("Could not open geometry shader program file", geometryShaderProgramFileName, ELL_WARNING); } } s32 result = addHighLevelShaderMaterialFromFiles( vsfile, vertexShaderEntryPointName, vsCompileTarget, psfile, pixelShaderEntryPointName, psCompileTarget, gsfile, geometryShaderEntryPointName, gsCompileTarget, inType, outType, verticesOut, callback, baseMaterial, userData, shadingLang); if (psfile) psfile->drop(); if (vsfile) vsfile->drop(); if (gsfile) gsfile->drop(); return result; } //! Like IGPUProgrammingServices::addShaderMaterial() (look there for a detailed description), //! but tries to load the programs from files. s32 CNullDriver::addHighLevelShaderMaterialFromFiles( io::IReadFile* vertexShaderProgram, const c8* vertexShaderEntryPointName, E_VERTEX_SHADER_TYPE vsCompileTarget, io::IReadFile* pixelShaderProgram, const c8* pixelShaderEntryPointName, E_PIXEL_SHADER_TYPE psCompileTarget, io::IReadFile* geometryShaderProgram, const c8* geometryShaderEntryPointName, E_GEOMETRY_SHADER_TYPE gsCompileTarget, scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, u32 verticesOut, IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData, E_GPU_SHADING_LANGUAGE shadingLang) { c8* vs = 0; c8* ps = 0; c8* gs = 0; if (vertexShaderProgram) { const long size = vertexShaderProgram->getSize(); if (size) { vs = new c8[size+1]; vertexShaderProgram->read(vs, size); vs[size] = 0; } } if (pixelShaderProgram) { const long size = pixelShaderProgram->getSize(); if (size) { // if both handles are the same we must reset the file if (pixelShaderProgram==vertexShaderProgram) pixelShaderProgram->seek(0); ps = new c8[size+1]; pixelShaderProgram->read(ps, size); ps[size] = 0; } } if (geometryShaderProgram) { const long size = geometryShaderProgram->getSize(); if (size) { // if both handles are the same we must reset the file if ((geometryShaderProgram==vertexShaderProgram) || (geometryShaderProgram==pixelShaderProgram)) geometryShaderProgram->seek(0); gs = new c8[size+1]; geometryShaderProgram->read(gs, size); gs[size] = 0; } } s32 result = this->addHighLevelShaderMaterial( vs, vertexShaderEntryPointName, vsCompileTarget, ps, pixelShaderEntryPointName, psCompileTarget, gs, geometryShaderEntryPointName, gsCompileTarget, inType, outType, verticesOut, callback, baseMaterial, userData, shadingLang); delete [] vs; delete [] ps; delete [] gs; return result; } //! Adds a new material renderer to the VideoDriver, using pixel and/or //! vertex shaders to render geometry. s32 CNullDriver::addShaderMaterial(const c8* vertexShaderProgram, const c8* pixelShaderProgram, IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData) { os::Printer::log("Shader materials not implemented yet in this driver, sorry."); return -1; } //! Like IGPUProgrammingServices::addShaderMaterial(), but tries to load the //! programs from files. s32 CNullDriver::addShaderMaterialFromFiles(io::IReadFile* vertexShaderProgram, io::IReadFile* pixelShaderProgram, IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData) { c8* vs = 0; c8* ps = 0; if (vertexShaderProgram) { const long size = vertexShaderProgram->getSize(); if (size) { vs = new c8[size+1]; vertexShaderProgram->read(vs, size); vs[size] = 0; } } if (pixelShaderProgram) { const long size = pixelShaderProgram->getSize(); if (size) { ps = new c8[size+1]; pixelShaderProgram->read(ps, size); ps[size] = 0; } } s32 result = addShaderMaterial(vs, ps, callback, baseMaterial, userData); delete [] vs; delete [] ps; return result; } //! Like IGPUProgrammingServices::addShaderMaterial(), but tries to load the //! programs from files. s32 CNullDriver::addShaderMaterialFromFiles(const io::path& vertexShaderProgramFileName, const io::path& pixelShaderProgramFileName, IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData) { io::IReadFile* vsfile = 0; io::IReadFile* psfile = 0; if (vertexShaderProgramFileName.size()) { vsfile = FileSystem->createAndOpenFile(vertexShaderProgramFileName); if (!vsfile) { os::Printer::log("Could not open vertex shader program file", vertexShaderProgramFileName, ELL_WARNING); return -1; } } if (pixelShaderProgramFileName.size()) { psfile = FileSystem->createAndOpenFile(pixelShaderProgramFileName); if (!psfile) { os::Printer::log("Could not open pixel shader program file", pixelShaderProgramFileName, ELL_WARNING); if (vsfile) vsfile->drop(); return -1; } } s32 result = addShaderMaterialFromFiles(vsfile, psfile, callback, baseMaterial, userData); if (psfile) psfile->drop(); if (vsfile) vsfile->drop(); return result; } //! Creates a render target texture. ITexture* CNullDriver::addRenderTargetTexture(const core::dimension2d<u32>& size, const io::path&name, const ECOLOR_FORMAT format) { return 0; } //! Clears the ZBuffer. void CNullDriver::clearZBuffer() { } //! Returns a pointer to the mesh manipulator. scene::IMeshManipulator* CNullDriver::getMeshManipulator() { return MeshManipulator; } //! Returns an image created from the last rendered frame. IImage* CNullDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) { return 0; } // prints renderer version void CNullDriver::printVersion() { core::stringw namePrint = L"Using renderer: "; namePrint += getName(); os::Printer::log(namePrint.c_str(), ELL_INFORMATION); } //! creates a video driver IVideoDriver* createNullDriver(io::IFileSystem* io, const core::dimension2d<u32>& screenSize) { CNullDriver* nullDriver = new CNullDriver(io, screenSize); // create empty material renderers for(u32 i=0; sBuiltInMaterialTypeNames[i]; ++i) { IMaterialRenderer* imr = new IMaterialRenderer(); nullDriver->addMaterialRenderer(imr); imr->drop(); } return nullDriver; } //! Set/unset a clipping plane. //! There are at least 6 clipping planes available for the user to set at will. //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. //! \param plane: The plane itself. //! \param enable: If true, enable the clipping plane else disable it. bool CNullDriver::setClipPlane(u32 index, const core::plane3df& plane, bool enable) { return false; } //! Enable/disable a clipping plane. void CNullDriver::enableClipPlane(u32 index, bool enable) { // not necessary } ITexture* CNullDriver::createRenderTargetTexture(const core::dimension2d<u32>& size, const c8* name) { os::Printer::log("createRenderTargetTexture is deprecated, use addRenderTargetTexture instead"); ITexture* tex = addRenderTargetTexture(size, name); tex->grab(); return tex; } void CNullDriver::setMinHardwareBufferVertexCount(u32 count) { MinVertexCountForVBO = count; } SOverrideMaterial& CNullDriver::getOverrideMaterial() { return OverrideMaterial; } //! Get the 2d override material for altering its values SMaterial& CNullDriver::getMaterial2D() { return OverrideMaterial2D; } //! Enable the 2d override material void CNullDriver::enableMaterial2D(bool enable) { OverrideMaterial2DEnabled=enable; } core::dimension2du CNullDriver::getMaxTextureSize() const { return core::dimension2du(0x10000,0x10000); // maybe large enough } //! Color conversion convenience function /** Convert an image (as array of pixels) from source to destination array, thereby converting the color format. The pixel size is determined by the color formats. \param sP Pointer to source \param sF Color format of source \param sN Number of pixels to convert, both array must be large enough \param dP Pointer to destination \param dF Color format of destination */ void CNullDriver::convertColor(const void* sP, ECOLOR_FORMAT sF, s32 sN, void* dP, ECOLOR_FORMAT dF) const { video::CColorConverter::convert_viaFormat(sP, sF, sN, dP, dF); } } // end namespace } // end namespace
{ "content_hash": "4a3d18755bdbfb9441a016b75e669058", "timestamp": "", "source": "github", "line_count": 2448, "max_line_length": 197, "avg_line_length": 27.27532679738562, "alnum_prop": 0.7233787629174779, "repo_name": "PauT/Surface3d", "id": "15f32f96b4a5eb418323673bc56cf8b7b81f6f3f", "size": "66770", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "lib/irrlicht/CNullDriver.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "8314" }, { "name": "Awk", "bytes": "31768" }, { "name": "C", "bytes": "4924318" }, { "name": "C++", "bytes": "5996601" }, { "name": "CMake", "bytes": "19058" }, { "name": "CSS", "bytes": "1746" }, { "name": "GLSL", "bytes": "771" }, { "name": "Groff", "bytes": "305972" }, { "name": "HTML", "bytes": "7532" }, { "name": "Java", "bytes": "201154" }, { "name": "Logos", "bytes": "1019781" }, { "name": "Makefile", "bytes": "53971" }, { "name": "Objective-C", "bytes": "31104" }, { "name": "Objective-C++", "bytes": "59117" }, { "name": "Perl", "bytes": "5584" }, { "name": "Python", "bytes": "8374" }, { "name": "SAS", "bytes": "14198" }, { "name": "Shell", "bytes": "352826" }, { "name": "Smalltalk", "bytes": "2560" }, { "name": "XSLT", "bytes": "12288" } ], "symlink_target": "" }
import unittest from pypika import ( Case, Field, Table, functions as fn, ) from pypika.terms import ( Negative, ValueWrapper, ) class IsAggregateTests(unittest.TestCase): def test__field_is_not_aggregate(self): v = Field("foo") self.assertFalse(v.is_aggregate) def test__constant_is_aggregate_none(self): v = ValueWrapper(100) self.assertIsNone(v.is_aggregate) def test__constant_arithmetic_is_aggregate_none(self): v = ValueWrapper(100) + ValueWrapper(100) self.assertIsNone(v.is_aggregate) def test__field_arithmetic_is_not_aggregate(self): v = Field("foo") + Field("bar") self.assertFalse(v.is_aggregate) def test__field_arithmetic_constant_is_not_aggregate(self): v = Field("foo") + 1 self.assertFalse(v.is_aggregate) def test__agg_func_is_aggregate(self): v = fn.Sum(Field("foo")) self.assertTrue(v.is_aggregate) def test__negative_agg_func_is_aggregate(self): v = Negative(fn.Sum(Field("foo"))) self.assertTrue(v.is_aggregate) def test__agg_func_arithmetic_is_aggregate(self): v = fn.Sum(Field("foo")) / fn.Sum(Field("foo")) self.assertTrue(v.is_aggregate) def test__mixed_func_arithmetic_is_not_aggregate(self): v = Field("foo") / fn.Sum(Field("foo")) self.assertFalse(v.is_aggregate) def test__func_arithmetic_constant_is_not_aggregate(self): v = 1 / fn.Sum(Field("foo")) self.assertTrue(v.is_aggregate) def test__agg_case_criterion_is_aggregate(self): v = Case().when(fn.Sum(Field("foo")) > 666, 'More than 666').else_('Less than 666') self.assertTrue(v.is_aggregate) def test__agg_case_is_aggregate(self): v = ( Case() .when(Field("foo") == 1, fn.Sum(Field("bar"))) .when(Field("foo") == 2, fn.Sum(Field("fiz"))) .else_(fn.Sum(Field("fiz"))) ) self.assertTrue(v.is_aggregate) def test__mixed_case_is_not_aggregate(self): v = Case().when(Field("foo") == 1, fn.Sum(Field("bar"))).when(Field("foo") == 2, Field("fiz")) self.assertFalse(v.is_aggregate) def test__case_mixed_else_is_not_aggregate(self): v = ( Case() .when(Field("foo") == 1, fn.Sum(Field("bar"))) .when(Field("foo") == 2, fn.Sum(Field("fiz"))) .else_(Field("fiz")) ) self.assertFalse(v.is_aggregate) def test__case_mixed_constant_is_not_aggregate(self): v = Case().when(Field("foo") == 1, fn.Sum(Field("bar"))).when(Field("foo") == 2, fn.Sum(Field("fiz"))).else_(1) self.assertTrue(v.is_aggregate) def test__case_with_field_is_not_aggregate(self): v = Case().when(Field("foo") == 1, 1).when(Field("foo") == 2, 2).else_(3) self.assertFalse(v.is_aggregate) def test__case_with_single_aggregate_field_in_one_criterion_is_aggregate(self): v = Case().when(Field("foo") == 1, 1).when(fn.Sum(Field("foo")) == 2, 2).else_(3) self.assertTrue(v.is_aggregate) def test__non_aggregate_function_with_aggregated_arg(self): t = Table("abc") expr = fn.Sqrt(fn.Sum(t.a)) self.assertTrue(expr.is_aggregate) def test_complicated(self): t = Table("abc") is_placebo = t.campaign_extra_info == "placebo" pixel_mobile_search = Case().when(is_placebo, t.action_fb_pixel_search + t.action_fb_mobile_search) unique_impressions = Case().when(is_placebo, t.unique_impressions) v = fn.Sum(pixel_mobile_search) / fn.Sum(unique_impressions) - 1.96 * fn.Sqrt( 1 / fn.Sum(unique_impressions) * fn.Sum(pixel_mobile_search) / fn.Sum(unique_impressions) * (1 - fn.Sum(pixel_mobile_search) / fn.Sum(unique_impressions)) ) self.assertTrue(v.is_aggregate)
{ "content_hash": "51c219f13fed0502b16eaa79151ee166", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 119, "avg_line_length": 32.34426229508197, "alnum_prop": 0.5884439939178915, "repo_name": "kayak/pypika", "id": "1c627d8e9c2d65410c67cf2c39974949b0720a0e", "size": "3946", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pypika/tests/test_aggregate.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "394110" } ], "symlink_target": "" }
import 'core-js/es6/symbol'; import 'core-js/es6/object'; import 'core-js/es6/function'; import 'core-js/es6/parse-int'; import 'core-js/es6/parse-float'; import 'core-js/es6/number'; import 'core-js/es6/math'; import 'core-js/es6/string'; import 'core-js/es6/date'; import 'core-js/es6/array'; import 'core-js/es6/regexp'; import 'core-js/es6/map'; import 'core-js/es6/set'; import 'core-js/es6/reflect'; import 'core-js/es7/reflect'; import 'zone.js/dist/zone';
{ "content_hash": "92aff9ceccee714b2e4e04ec65735718", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 33, "avg_line_length": 27.294117647058822, "alnum_prop": 0.7198275862068966, "repo_name": "kunl/ng2-blog", "id": "c9bdebe9da07cfd98a298748fa0849571e618856", "size": "516", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "client/polyfills.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15962" }, { "name": "HTML", "bytes": "14082" }, { "name": "JavaScript", "bytes": "3647103" }, { "name": "TypeScript", "bytes": "30171" } ], "symlink_target": "" }
#ifndef _NT_ATOMIC_OSX_H_ #define _NT_ATOMIC_OSX_H_ #include <libkern/OSAtomic.h> /* ---- ptr ---- */ // void *nt_atomic_compare_and_swapptr(void * volatile *ptr, void *oldval, void *newval) #define nt_atomic_compare_and_swapptr(ptr, oldval, newval) \ (OSAtomicCompareAndSwapPtrBarrier(oldval, newval, ptr) ? (oldval) : NULL) #define nt_atomic_bool_compare_and_swapptr(ptr, oldval, newval) \ OSAtomicCompareAndSwapPtrBarrier(oldval, newval, ptr) #if __LP64__ #define nt_atomic_readptr(ptr) \ (void *)OSAtomicAdd64Barrier((int64_t)0LL, (volatile int64_t *)(ptr)) #else #define nt_atomic_readptr(ptr) \ (void *)OSAtomicAdd32Barrier(0, (volatile int32_t *)(ptr)) #endif #define nt_atomic_setptr(ptr, newval) \ while(!nt_atomic_bool_compare_and_swapptr(ptr, nt_atomic_readptr(ptr), newval)) /* ---- 32 ---- */ #define nt_atomic_compare_and_swap32(ptr, oldval, newval) \ (OSAtomicCompareAndSwap32Barrier(oldval, newval, ptr) ? (oldval) : NULL) #define nt_atomic_bool_compare_and_swap32(ptr, oldval, newval) \ OSAtomicCompareAndSwap32Barrier(oldval, newval, ptr) #define nt_atomic_read32(ptr) OSAtomicAdd32Barrier(0, ptr) #define nt_atomic_set32(ptr, newval) \ while(!nt_atomic_bool_compare_and_swap32(ptr, nt_atomic_read32(ptr), newval)) #define nt_atomic_add32(ptr, n) OSAtomicAdd32Barrier(n, ptr) #define nt_atomic_sub32(ptr, n) OSAtomicAdd32Barrier(-(n), ptr) #define nt_atomic_add_and_fetch32(ptr, n) nt_atomic_add32(ptr, n) #define nt_atomic_sub_and_fetch32(ptr, n) nt_atomic_sub32(ptr, n) NT_STATIC_INLINE int32_t nt_atomic_fetch_and_add32(volatile int32_t *ptr, int32_t n) { int32_t oldval; do { oldval = nt_atomic_read32(ptr); } while(!nt_atomic_bool_compare_and_swap32(ptr, oldval, oldval+n)); return oldval; } #define nt_atomic_fetch_and_sub32(ptr, n) nt_atomic_fetch_and_add32(ptr, -(n)) #endif
{ "content_hash": "58ad6a8e1631af37fa696bc18c60afce", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 88, "avg_line_length": 30.475409836065573, "alnum_prop": 0.708445400753093, "repo_name": "rsms/libnt", "id": "511a9da8d6528d0fdf799257e62611a3bd3313d0", "size": "3033", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/atomic_osx.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "116827" } ], "symlink_target": "" }
module Thredded module IconHelper def shared_inline_svg(filename, **args) svg = content_tag :svg, **args do content_tag :use, '', 'xlink:href' => "##{thredded_icon_id(filename)}" end if (definition = define_svg_icons(filename)) definition + svg else svg end end def define_svg_icons(*filenames) return if filenames.blank? sb = filenames.map do |filename| inline_svg_once(filename, id: thredded_icon_id(filename)) end return if sb.compact.blank? content_tag :div, safe_join(sb), class: 'thredded--svg-definitions' end def inline_svg_once(filename, id:, **transform_params) return if @already_inlined_svg_ids&.include?(id) record_already_inlined_svg(filename, id) inline_svg_tag(filename, id: id, **transform_params) end private def record_already_inlined_svg(filename, id) if filename.is_a?(String) # in case it's an IO or other fail "Please use id: #{thredded_icon_id(filename)}" unless id == thredded_icon_id(filename) end @already_inlined_svg_ids ||= [] @already_inlined_svg_ids << id end def thredded_icon_id(svg_filename) "thredded-#{File.basename(svg_filename, '.svg').dasherize}-icon" end end end
{ "content_hash": "c71bcf423862f67dd677ccd830c52543", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 99, "avg_line_length": 30.325581395348838, "alnum_prop": 0.6273006134969326, "repo_name": "thredded/thredded", "id": "1e690bbfa30c613bbb42067b8ac723acf9632c40", "size": "1335", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "app/helpers/thredded/icon_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "972" }, { "name": "HTML", "bytes": "113484" }, { "name": "JavaScript", "bytes": "35532" }, { "name": "Procfile", "bytes": "60" }, { "name": "Ruby", "bytes": "559911" }, { "name": "SCSS", "bytes": "79530" }, { "name": "Shell", "bytes": "3610" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>demos: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.4.6~camlp4 / demos - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> demos <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-06 19:57:14 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-06 19:57:14 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp4 4.02+7 Camlp4 is a system for writing extensible parsers for programming languages conf-findutils 1 Virtual package relying on findutils conf-which 1 Virtual package relying on which coq 8.4.6~camlp4 Formal proof management system. num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlbuild 0 Build system distributed with the OCaml compiler since OCaml 3.10.0 # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/demos&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Demos&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: sorting&quot; &quot;keyword: Cases&quot; &quot;keyword: Tauto&quot; &quot;keyword: AutoRewrite&quot; &quot;keyword: Prolog&quot; &quot;category: Miscellaneous/Coq Use Examples&quot; ] authors: [ &quot;Coq group&quot; ] bug-reports: &quot;https://github.com/coq-contribs/demos/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/demos.git&quot; synopsis: &quot;Demos of some Coq tools appeared in version V6.0&quot; description: &quot;&quot;&quot; Example of sorting algorithms defined using the Cases (pattern-matching) construction. Demo of the decision tactic Tauto for intuitionistic propositional calculus. Demo of the AutoRewrite tactic. Demo of the Prolog tactic applied to the compilation of miniML programs.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/demos/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=15b2dee01a890057ed54693694515f87&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-demos.8.8.0 coq.8.4.6~camlp4</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.4.6~camlp4). The following dependencies couldn&#39;t be met: - coq-demos -&gt; coq &gt;= 8.8 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-demos.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "767c46b1d78bd72c5444647645d3f3f4", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 206, "avg_line_length": 43.48235294117647, "alnum_prop": 0.5550595238095238, "repo_name": "coq-bench/coq-bench.github.io", "id": "26581d8d820c676d2bf665002fe18efac79be0a7", "size": "7417", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.4.6~camlp4/demos/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }