answer
stringlengths
15
1.25M
//css_dir ..\..\..\; //css_ref Wix_bin\SDK\Microsoft.Deployment.WindowsInstaller.dll; //css_ref System.Core.dll; using System; using System.Windows.Forms; using Microsoft.Deployment.WindowsInstaller; using WixSharp; using Microsoft.Win32; using System.Diagnostics; class Script { static public void Main(string[] args) { var project = new Project("Setup", new <API key>(CustonActions.RegisterFileType, Return.ignore, When.After, Step.InstallInitialize, Condition.NOT_BeingRemoved), new <API key>(CustonActions.UnRegisterFileType, Return.ignore, When.After, Step.InstallInitialize, Condition.Installed)); Compiler.BuildMsi(project); } } public class CustonActions { static RegistryKey OpenOrCreateKey(string path) { var key = Registry.ClassesRoot.OpenSubKey(path, true); if (key == null) { Registry.ClassesRoot.CreateSubKey(path); key = Registry.ClassesRoot.OpenSubKey(path, true); } return key; } [CustomAction] public static ActionResult RegisterFileType(Session session) { try { using (RegistryKey key = OpenOrCreateKey(@".my")) key.SetValue("", "myfile"); using (RegistryKey key = OpenOrCreateKey(@"myfile\shell\open\command")) key.SetValue("", Environment.<API key>(@"%SystemRoot%\system32\NOTEPAD.EXE %1")); } catch { } return ActionResult.Success; } [CustomAction] public static ActionResult UnRegisterFileType(Session session) { try { Registry.ClassesRoot.DeleteSubKeyTree(".my"); Registry.ClassesRoot.DeleteSubKeyTree(".myfile"); } catch { } return ActionResult.Success; } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <title>Uses of Class org.myrobotlab.java.<API key></title> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.myrobotlab.java.<API key>"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/myrobotlab/java/<API key>.html" title="class in org.myrobotlab.java">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/myrobotlab/java/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class org.myrobotlab.java.<API key>" class="title">Uses of Class<br>org.myrobotlab.java.<API key></h2> </div> <div class="classUseContainer">No usage of org.myrobotlab.java.<API key></div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </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><a href="../../../../org/myrobotlab/java/<API key>.html" title="class in org.myrobotlab.java">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/myrobotlab/java/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
rm -rf www && eleventy --input=src --output=www --config=.eleventy.js --serve
/** * Autogenerated by Thrift Compiler (0.14.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.hadoop.hive.metastore.api; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.14.1)") @org.apache.hadoop.classification.InterfaceAudience.Public @org.apache.hadoop.classification.InterfaceStability.Stable public class WMDropPoolResponse implements org.apache.thrift.TBase<WMDropPoolResponse, WMDropPoolResponse._Fields>, java.io.Serializable, Cloneable, Comparable<WMDropPoolResponse> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("WMDropPoolResponse"); private static final org.apache.thrift.scheme.SchemeFactory <API key> = new <API key>(); private static final org.apache.thrift.scheme.SchemeFactory <API key> = new <API key>(); /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ; private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByThriftId(int fieldId) { switch(fieldId) { default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields <API key>(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.<API key>("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.<API key>(WMDropPoolResponse.class, metaDataMap); } public WMDropPoolResponse() { } /** * Performs a deep copy on <i>other</i>. */ public WMDropPoolResponse(WMDropPoolResponse other) { } public WMDropPoolResponse deepCopy() { return new WMDropPoolResponse(this); } @Override public void clear() { } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { } } @org.apache.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { } throw new java.lang.<API key>(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.<API key>(); } switch (field) { } throw new java.lang.<API key>(); } @Override public boolean equals(java.lang.Object that) { if (that instanceof WMDropPoolResponse) return this.equals((WMDropPoolResponse)that); return false; } public boolean equals(WMDropPoolResponse that) { if (that == null) return false; if (this == that) return true; return true; } @Override public int hashCode() { int hashCode = 1; return hashCode; } @Override public int compareTo(WMDropPoolResponse other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; return 0; } @org.apache.thrift.annotation.Nullable public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("WMDropPoolResponse("); boolean first = true; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.<API key> { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class <API key> implements org.apache.thrift.scheme.SchemeFactory { public <API key> getScheme() { return new <API key>(); } } private static class <API key> extends org.apache.thrift.scheme.StandardScheme<WMDropPoolResponse> { public void read(org.apache.thrift.protocol.TProtocol iprot, WMDropPoolResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, WMDropPoolResponse struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class <API key> implements org.apache.thrift.scheme.SchemeFactory { public <API key> getScheme() { return new <API key>(); } } private static class <API key> extends org.apache.thrift.scheme.TupleScheme<WMDropPoolResponse> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, WMDropPoolResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; } @Override public void read(org.apache.thrift.protocol.TProtocol prot, WMDropPoolResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? <API key> : <API key>).getScheme(); } }
package org.scaladebugger.tool.backend.functions import com.sun.jdi.ThreadReference import org.scaladebugger.api.lowlevel.wrappers.Implicits._ import org.scaladebugger.tool.backend.StateManager import scala.collection.JavaConverters._ import scala.util.Try /** * Represents a collection of functions for managing threads. * * @param stateManager The manager whose state to share among functions * @param writeLine Used to write output to the terminal */ class <API key>( private val stateManager: StateManager, private val writeLine: String => Unit ) { /** Entrypoint for listing thread groups for connected JVMs. */ def threadsGroups(m: Map[String, Any]) = { val jvms = stateManager.state.<API key> if (jvms.isEmpty) writeLine("No VM connected!") jvms.foreach(s => { val threadGroups = s.threads.map(_.threadGroup) .groupBy(_.name).map(_._2.head) writeLine(s"<= JVM ${s.uniqueId} =>") threadGroups.foreach(tg => { val rName = tg.referenceType.name val id = "0x" + tg.uniqueIdHexString val name = tg.name writeLine(s"($rName)$id $name") }) }) } /** Entrypoint for setting the default thread group. */ def threadGroup(m: Map[String, Any]) = { val jvms = stateManager.state.<API key> if (jvms.isEmpty) writeLine("No VM connected!") val threadGroupName = m.get("threadGroup").map(_.toString) threadGroupName match { // If name provided, lookup and set as active thread group case Some(name) => val threadGroup = jvms.view.flatMap(_.threads).map(_.threadGroup) .collectFirst { case tg if tg.name == name => tg } if (threadGroup.isEmpty) writeLine(s"No thread group found named '$name'!") threadGroup.foreach(stateManager.<API key>) // No name provided, so clear existing active thread group case None => stateManager.<API key>() } } }
package com.gemstone.gemfire.internal.lang; /** * The SystemUtils class is an abstract utility class for working with, invoking methods and accessing properties * of the Java System class. * * @author John Blum * @see java.lang.System * @since 6.8 */ @SuppressWarnings("unused") public class SystemUtils { public static final String CURRENT_DIRECTORY = System.getProperty("user.dir"); // Java Virtual Machine (JVM) Names public static final String IBM_J9_JVM_NAME = "J9"; public static final String <API key> = "HotSpot"; public static final String <API key> = "JRockit"; // Java Virtual Machine (JVM) Vendor Names public static final String <API key> = "Apple"; public static final String IBM_JVM_NAME = "IBM"; public static final String <API key> = "Oracle"; // Operating System Names public static final String LINUX_OS_NAME = "Linux"; public static final String MAC_OSX_NAME = "Mac"; public static final String WINDOWS_OS_NAME = "Windows"; /** * Utility method to determine whether the installed Java Runtime Environment (JRE) is minimally at the specified, * expected version. Typically, Java versions are of the form "1.6.0_31"... * * @param expectedVersion an int value specifying the minimum expected version of the Java Runtime. * @return a boolean value indicating if the Java Runtime meets the expected version requirement. * @see java.lang.System#getProperty(String) with "java.version". */ public static boolean <API key>(final String expectedVersion) { String actualVersionDigits = StringUtils.getDigitsOnly(System.getProperty("java.version")); String <API key> = StringUtils.padEnding(StringUtils.getDigitsOnly(expectedVersion), '0', actualVersionDigits.length()); try { return (Long.parseLong(actualVersionDigits) >= Long.parseLong(<API key>)); } catch (<API key> ignore) { return false; } } /** * Utility method to determine whether the Java application process is executing on the Apple JVM. * * @return a boolean value indicating whether the Java application process is executing and running * on the Apple JVM. * @see #isJvmVendor(String) */ public static boolean isAppleJVM() { return isJvmVendor(<API key>); } /** * Utility method to determine whether the Java application process is executing on the Oracle JVM. * * @return a boolean value indicating whether the Java application process is executing and running * on the Oracle JVM. * @see #isJvmVendor(String) */ public static boolean isOracleJVM() { return isJvmVendor(<API key>); } // @see java.lang.System#getProperty(String) with 'java.vm.vendor'. private static boolean isJvmVendor(final String <API key>) { String jvmVendor = System.getProperty("java.vm.vendor"); return (jvmVendor != null && jvmVendor.contains(<API key>)); } /** * Utility method to determine whether the Java application process is executing on the Java HotSpot VM. * Client or Server VM does not matter. * * @return a boolean value indicating whether the Java application process is executing on the Java HotSpot VM. * @see #isJVM(String) */ public static boolean isHotSpotVM() { return isJVM(<API key>); } /** * Utility method to determine whether the Java application process is executing on the IBM J9 VM. * * @return a boolean value indicating whether the Java application process is executing on the IBM J9 VM. * @see #isJVM(String) */ public static boolean isJ9VM() { return isJVM(IBM_J9_JVM_NAME); } /** * Utility method to determine whether the Java application process is executing on the Oracle JRockit VM. * Client or Server VM does not matter. * * @return a boolean value indicating whether the Java application process is executing on the Oracle JRockit VM. * @see #isJVM(String) */ public static boolean isJRockitVM() { return isJVM(<API key>); } // @see java.lang.System#getProperty(String) with "java.vm.name". private static boolean isJVM(final String expectedJvmName) { String jvmName = System.getProperty("java.vm.name"); return (jvmName != null && jvmName.contains(expectedJvmName)); } /** * Utility method that determines whether the Java application process is executing in a Linux * operating system environment. * * @return a boolean value indicating whether the Java application process is executing in Linux. * @see #isOS(String) */ public static boolean isLinux() { return isOS(LINUX_OS_NAME); } /** * Utility method that determines whether the Java application process is executing in a Apple Mac OSX * operating system environment. * * @return a boolean value indicating whether the Java application process is executing in Mac OSX. * @see #isOS(String) */ public static boolean isMacOSX() { return isOS(MAC_OSX_NAME); } /** * Utility method that determines whether the Java application process is executing in a Microsoft Windows-based * operating system environment. * * @return a boolean value indicating whether the Java application process is executing in Windows. * @see #isOS(String) */ public static boolean isWindows() { return isOS(WINDOWS_OS_NAME); } // @see java.lang.System#getProperty(String) with "os.name". private static boolean isOS(final String expectedOsName) { String osName = System.getProperty("os.name"); return (osName != null && osName.contains(expectedOsName)); } }
#!/bin/bash OUTDIR="build/_config" INDIR="build/config" mkdir -p ${OUTDIR} if [ -d "$INDIR" ]; then
<?php final class <API key> extends <API key> { public function getBrowseTitle() { return pht('Browse Repositories'); } public function getPlaceholderText() { return pht('Type a repository name...'); } public function <API key>() { return '<API key>'; } public function loadResults() { $viewer = $this->getViewer(); $raw_query = $this->getRawQuery(); $query = id(new <API key>()) ->setOrder('name') ->withDatasourceQuery($raw_query); $repos = $this->executeQuery($query); $type_icon = id(new <API key>()) ->getTypeIcon(); $image_sprite = "<API key> phui-font-fa phui-icon-view {$type_icon}"; $results = array(); foreach ($repos as $repo) { $display_name = $repo->getMonogram().' '.$repo->getName(); $name = $display_name; $slug = $repo->getRepositorySlug(); if (strlen($slug)) { $name = "{$name} {$slug}"; } $results[] = id(new <API key>()) ->setName($name) ->setDisplayName($display_name) ->setURI($repo->getURI()) ->setPHID($repo->getPHID()) ->setPriorityString($repo->getMonogram()) ->setPriorityType('repo') ->setImageSprite($image_sprite) ->setDisplayType(pht('Repository')); } return $results; } }
#include <utility> #include <string> #include "util/hash.h" #include "library/private.h" #include "library/module.h" #include "library/kernel_bindings.h" #include "library/fingerprint.h" namespace lean { struct private_ext : public <API key> { unsigned m_counter; name_map<name> m_inv_map; // map: hidden-name -> user-name private_ext():m_counter(0) {} }; struct private_ext_reg { unsigned m_ext_id; private_ext_reg() { m_ext_id = environment::register_extension(std::make_shared<private_ext>()); } }; static private_ext_reg * g_ext = nullptr; static private_ext const & get_extension(environment const & env) { return static_cast<private_ext const &>(env.get_extension(g_ext->m_ext_id)); } static environment update(environment const & env, private_ext const & ext) { return env.update(g_ext->m_ext_id, std::make_shared<private_ext>(ext)); } static name * g_private = nullptr; static std::string * g_prv_key = nullptr; // Make sure the mapping "hidden-name r ==> user-name n" is preserved when we close sections and // export .olean files. static environment <API key>(environment const & env, name const & r, name const & n) { return module::add(env, *g_prv_key, [=](environment const &, serializer & s) { s << n << r; }); } pair<environment, name> add_private_name(environment const & env, name const & n, optional<unsigned> const & extra_hash) { private_ext ext = get_extension(env); unsigned h = hash(n.hash(), ext.m_counter); uint64 f = get_fingerprint(env); h = hash(h, static_cast<unsigned>(f >> 32)); h = hash(h, static_cast<unsigned>(f)); if (extra_hash) h = hash(h, *extra_hash); name r = name(*g_private, h) + n; ext.m_inv_map.insert(r, n); ext.m_counter++; environment new_env = update(env, ext); new_env = <API key>(new_env, r, n); return mk_pair(new_env, r); } static void private_reader(deserializer & d, shared_environment & senv, std::function<void(asynch_update_fn const &)> &, std::function<void(delayed_update_fn const &)> &) { name n, h; d >> n >> h; senv.update([=](environment const & env) -> environment { private_ext ext = get_extension(env); // we restore only the mapping hidden-name -> user-name (for pretty printing purposes) ext.m_inv_map.insert(h, n); ext.m_counter++; return update(env, ext); }); } optional<name> hidden_to_user_name(environment const & env, name const & n) { auto it = get_extension(env).m_inv_map.find(n); return it ? optional<name>(*it) : optional<name>(); } static int add_private_name(lua_State * L) { int nargs = lua_gettop(L); optional<unsigned> h; if (nargs > 2) h = lua_tonumber(L, 3); auto p = add_private_name(to_environment(L, 1), to_name_ext(L, 2), h); push_environment(L, p.first); push_name(L, p.second); return 2; } static int hidden_to_user_name(lua_State * L) { return push_optional_name(L, hidden_to_user_name(to_environment(L, 1), to_name_ext(L, 2))); } void open_private(lua_State * L) { SET_GLOBAL_FUN(add_private_name, "add_private_name"); SET_GLOBAL_FUN(hidden_to_user_name, "hidden_to_user_name"); } void initialize_private() { g_ext = new private_ext_reg(); g_private = new name("private"); g_prv_key = new std::string("prv"); <API key>(*g_prv_key, private_reader); } void finalize_private() { delete g_prv_key; delete g_private; delete g_ext; } }
package egovframework.com.ext.jfile.org.json; import java.util.Iterator; /** * Convert a web browser cookie list string to a JSONObject and back. * @author JSON.org * @version 2008-09-18 */ public class CookieList { /** * Convert a cookie list into a JSONObject. A cookie list is a sequence * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The names and the values * will be unescaped, possibly converting '+' and '%' sequences. * * To add a cookie to a cooklist, * <API key>.put(cookieJSONObject.getString("name"), * cookieJSONObject.getString("value")); * @param string A cookie list string * @return A JSONObject * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject o = new JSONObject(); JSONTokener x = new JSONTokener(string); while (x.more()) { String name = Cookie.unescape(x.nextTo('=')); x.next('='); o.put(name, Cookie.unescape(x.nextTo(';'))); x.next(); } return o; } /** * Convert a JSONObject into a cookie list. A cookie list is a sequence * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The characters '%', '+', '=', and ';' * in the names and values are replaced by "%hh". * @param o A JSONObject * @return A cookie list string * @throws JSONException */ public static String toString(JSONObject o) throws JSONException { boolean b = false; Iterator<?> keys = o.keys(); String s; StringBuffer sb = new StringBuffer(); while (keys.hasNext()) { s = keys.next().toString(); if (!o.isNull(s)) { if (b) { sb.append(';'); } sb.append(Cookie.escape(s)); sb.append("="); sb.append(Cookie.escape(o.getString(s))); b = true; } } return sb.toString(); } }
## mounts Mounts has three different usage options: `path`, `persistent` and `sync`. They're used to configure which folders will be internalized to the container or persisted internally by `azk`. # path js 'INTERNAL_FOLDER': path('LOCAL_PATH'), Mount the folder located in the current system machine `LOCAL_PATH`, relative to the Azkfile.js, to the path `INTERNAL_FOLDER` inside the system container. If any of the files are changed, from the user machine or from inside the container, the information is also updated on the other end. # persistent js 'INTERNAL_FOLDER': persistent('LOCAL_PATH'), Persists the files that are inside the container on the path `INTERNAL_FOLDER`, to an `azk` persistent data folder in the user machine. The location the data will be saved will vary between Mac and Linux: ### Mac The folder is stored in a virtual disk (`~/.azk/data/vm/azk-agent.vmdk`) in the path `/azk/persistent_folders`. This disk is mounted in the path `/mnt/sda1` of the VM. ### Linux `~/.azk/data/persistent_folders/#{manifest.id}/LOCAL_PATH`. Note that using the same 'LOCAL_PATH' in the same Azkfile.js, but in different systems, means that these systems will share the persisted data. # sync js 'INTERNAL_FOLDER': sync('LOCAL_PATH' [, OPTS]), Syncs the files in `LOCAL_PATH` with a remote destination, which is mounted in the `INTERNAL_FOLDER`. Differently from `path` option, `sync` uses [rsync](https://rsync.samba.org/) instead of VirtualBox [shared folders](https://www.virtualbox.org/manual/ch04.html#sharedfolders). As result, the overall performance is significantly increased, mainly for applications which demand a great number of files (e.g. a Ruby on Rails application with a lot of assets). ## OPTS (optional) * `except`: an `Array` of files and/or folders to be ignored in the sync process. It uses [glob patterns](http://teaching.idallen.com/dat2330/06w/notes/glob_patterns.txt). Useful hints: * **Exclude a file**: `{except: ["./path/to/the/file.png"]}` * **Exclude a folder**: `{except: ["./path/to/the/folder/"]}` // *Mind the tailing slash!* * **Exclude all CSS files**: `{except: ["*.css"]}` > By default, `azk` ignores the following elements when syncing: `.syncignore`, `.gitignore`, `Azkfile.js`, `.azk/` and `.git/`. * `daemon`: a `boolean` value that indicates if, when running `azk` in daemon mode (e.g. `azk start`), `azk` should either use or not use the `sync` scheme (in the negative case, the `path` scheme is used) (default: `true`); * `shell`: similarly to `daemon` option, it's a `boolean` value that indicates if, when running `azk` in shell mode (e.g. `azk shell`), `azk` should either use or not use the `sync` scheme (in the negative case, the `path` scheme is used) (default: `false`). Setting as `false` is particularly useful to keep a two-way sync, allowing created files in the shell (e.g. via `$ rails generate scaffold User name:string`) to be persisted back in the original project folder; ## Data persistency When using `sync`, we need to ensure that the all data generated by [`provision`](/en/reference/azkfilejs/provision.html) will be persisted. To do this, we have to add to `mounts` a `persistent` entry with correspondent folder. Those folder may vary between languages and frameworks, but follow some examples: * __Ruby/Rails__: js mounts: { '/azk/#{manifest.dir}' : sync("."), '/azk/bundler' : persistent("bundler"), '/azk/#{manifest.dir}/tmp' : persistent("tmp"), '/azk/#{manifest.dir}/.bundle' : path(".bundle"), '/azk/#{manifest.dir}/log' : path("log"), }, * __Node.js__: js mounts: { '/azk/#{manifest.dir}' : sync('.'), '/azk/node_modules' : persistent('node_modules'), }, ## Excluded folders Since you use `sync` in a folder, `azk` starts to watch its files for any new change in order to re-sync the modified ones as soon as the change happens. As long as that folder has too many files, the CPU consumption can increase severally. The best way to avoid this is by telling `sync` to skip any folder which isn't absolutely required to make the system run. You can make this by any of the following ways: * Using the `except` option for the `sync`, as listed above; * Creating, inside the folder to be sync, a file named `.syncignore` which contains a list of files and folders to be skipped during the sync process (e.g. if you are using `sync(./MyProject)`, `azk` will look for the file `./MyProject/.syncignore`); * If you don't have a `.syncignore` file, by default `azk` will ignore all the files and folders listed in the file `.gitignore` (inside the folder to be synced) during the sync process (e.g. analogously, if you are using `sync(./MyProject)`, `azk` will look for the file `./MyProject/.gitignore`). ## Destination synced data The destination path of the data that will be synced will vary between Mac and Linux: ### Mac The folder is stored in a virtual disk (`~/.azk/data/vm/azk-agent.vmdk`) in the path `/azk/sync_folders`. This disk is mounted in the path `/mnt/sda1` of the VM. ### Linux `~/.azk/data/sync_folders/#{manifest.id}/LOCAL_PATH`. Note that using the same 'LOCAL_PATH' in the same Azkfile.js, but in different containers, will mean that they'll share the data. > **IMPORTANT NOTE:** If you are facing performance issues using `azk` with your application, you should use this option when mounting your source code. Note it's a one-way sync, so you still have to add entries in `mounts` indicating which folders need to use the `share` option (using `path` or `persistent`). Examples * __path__: Mount the current project folder (`'.'`) in the container on the path `/azk/azkdemo` (considering `azkdemo` is the name of the folder where the `Azkfile.js` is located). js mounts: { '/azk/#{manifest.dir}' : path('.'), }, * __persistent__: Persists the files within the container that are on the path `/azk/bundler`. The files, in this case, will be stored in the _guest machine_ inside the folder `~/.azk/data/persistent_folders/#{manifest.id}/`. js mounts: { '/azk/bundler' : persistent('bundler'), }, * __sync__: Syncs the project files within the container on the path `/azk/azkdemo` (considering `azkdemo` is the name of the folder where the `Azkfile.js` is located), excluding CSS files and `config` folder. Plus, use shared folders to `tmp` and `log`. js mounts: { '/azk/#{manifest.dir}' : sync('.', except: ['*.css', 'config/']), '/azk/#{manifest.dir}/tmp' : persistent('tmp/'), '/azk/#{manifest.dir}/log' : persistent('log/'), },
#include "commonmarker.h" #include "cmark.h" #include "houdini.h" #include "node.h" #include "registry.h" #include "parser.h" #include "syntax_extension.h" #include "core-extensions.h" static VALUE rb_mNodeError; static VALUE rb_mNode; static VALUE sym_document; static VALUE sym_blockquote; static VALUE sym_list; static VALUE sym_list_item; static VALUE sym_code_block; static VALUE sym_html; static VALUE sym_paragraph; static VALUE sym_header; static VALUE sym_hrule; static VALUE sym_text; static VALUE sym_softbreak; static VALUE sym_linebreak; static VALUE sym_code; static VALUE sym_inline_html; static VALUE sym_emph; static VALUE sym_strong; static VALUE sym_link; static VALUE sym_image; static VALUE <API key>; static VALUE <API key>; static VALUE sym_bullet_list; static VALUE sym_ordered_list; static VALUE sym_left; static VALUE sym_right; static VALUE sym_center; static VALUE encode_utf8_string(const char *c_string) { VALUE string = rb_str_new2(c_string); int enc = rb_enc_find_index("UTF-8"); <API key>(string, enc); return string; } static void rb_mark_c_struct(void *data) { cmark_node *node = data; cmark_node *child; /* Mark the parent to make sure that the tree won't be freed as long as a child node is referenced. */ cmark_node *parent = cmark_node_parent(node); if (parent) { void *user_data = <API key>(parent); if (!user_data) { /* This should never happen. Child can nodes can only be returned from parents that already are associated with a Ruby object. */ fprintf(stderr, "parent without user_data\n"); abort(); } rb_gc_mark((VALUE)user_data); } /* Mark all children to make sure their cached Ruby objects won't be freed. */ for (child = <API key>(node); child != NULL; child = cmark_node_next(child)) { void *user_data = <API key>(child); if (user_data) rb_gc_mark((VALUE)user_data); } } static void rb_free_c_struct(void *data) { /* It's important that the `free` function does not inspect the node data, as it may be part of a tree that was already freed. */ cmark_node_free(data); } static VALUE rb_node_to_value(cmark_node *node) { void *user_data; RUBY_DATA_FUNC free_func; VALUE val; if (node == NULL) return Qnil; user_data = <API key>(node); if (user_data) return (VALUE)user_data; /* Only free tree roots. */ free_func = cmark_node_parent(node) ? NULL : rb_free_c_struct; val = Data_Wrap_Struct(rb_mNode, rb_mark_c_struct, free_func, node); <API key>(node, (void *)val); return val; } /* If the node structure is changed, the finalizers must be updated. */ static void rb_parent_added(VALUE val) { RDATA(val)->dfree = NULL; } static void rb_parent_removed(VALUE val) { RDATA(val)->dfree = rb_free_c_struct; } static cmark_parser *prepare_parser(VALUE rb_options, VALUE rb_extensions, cmark_mem *mem) { int options; int extensions_len; VALUE rb_ext_name; int i; Check_Type(rb_options, T_FIXNUM); Check_Type(rb_extensions, T_ARRAY); options = FIX2INT(rb_options); extensions_len = RARRAY_LEN(rb_extensions); cmark_parser *parser = <API key>(options, mem); for (i = 0; i < extensions_len; ++i) { rb_ext_name = RARRAY_PTR(rb_extensions)[i]; if (!SYMBOL_P(rb_ext_name)) { cmark_parser_free(parser); cmark_arena_reset(); rb_raise(rb_eTypeError, "extension names should be Symbols; got a %"PRIsVALUE"", rb_obj_class(rb_ext_name)); } <API key> *syntax_extension = <API key>(rb_id2name(SYM2ID(rb_ext_name))); if (!syntax_extension) { cmark_parser_free(parser); cmark_arena_reset(); rb_raise(rb_eArgError, "extension %s not found", rb_id2name(SYM2ID(rb_ext_name))); } <API key>(parser, syntax_extension); } return parser; } /* * Internal: Parses a Markdown string into an HTML string. * */ static VALUE rb_markdown_to_html(VALUE self, VALUE rb_text, VALUE rb_options, VALUE rb_extensions) { char *str, *html; int len; cmark_parser *parser; cmark_node *doc; Check_Type(rb_text, T_STRING); Check_Type(rb_options, T_FIXNUM); parser = prepare_parser(rb_options, rb_extensions, <API key>()); str = (char *)RSTRING_PTR(rb_text); len = RSTRING_LEN(rb_text); cmark_parser_feed(parser, str, len); doc = cmark_parser_finish(parser); if (doc == NULL) { cmark_arena_reset(); rb_raise(rb_mNodeError, "error parsing document"); } cmark_mem *default_mem = <API key>(); html = <API key>(doc, FIX2INT(rb_options), parser->syntax_extensions, default_mem); cmark_arena_reset(); VALUE ruby_html = rb_str_new2(html); default_mem->free(html); return ruby_html; } /* * Internal: Creates a node based on a node type. * * type - A {Symbol} representing the node to be created. Must be one of the * following: * - `:document` * - `:blockquote` * - `:list` * - `:list_item` * - `:code_block` * - `:html` * - `:paragraph` * - `:header` * - `:hrule` * - `:text` * - `:softbreak` * - `:linebreak` * - `:code` * - `:inline_html` * - `:emph` * - `:strong` * - `:link` * - `:image` */ static VALUE rb_node_new(VALUE self, VALUE type) { cmark_node_type node_type = 0; cmark_node *node; Check_Type(type, T_SYMBOL); if (type == sym_document) node_type = CMARK_NODE_DOCUMENT; else if (type == sym_blockquote) node_type = <API key>; else if (type == sym_list) node_type = CMARK_NODE_LIST; else if (type == sym_list_item) node_type = CMARK_NODE_ITEM; else if (type == sym_code_block) node_type = <API key>; else if (type == sym_html) node_type = CMARK_NODE_HTML; else if (type == sym_paragraph) node_type = <API key>; else if (type == sym_header) node_type = CMARK_NODE_HEADER; else if (type == sym_hrule) node_type = CMARK_NODE_HRULE; else if (type == sym_text) node_type = CMARK_NODE_TEXT; else if (type == sym_softbreak) node_type = <API key>; else if (type == sym_linebreak) node_type = <API key>; else if (type == sym_code) node_type = CMARK_NODE_CODE; else if (type == sym_inline_html) node_type = <API key>; else if (type == sym_emph) node_type = CMARK_NODE_EMPH; else if (type == sym_strong) node_type = CMARK_NODE_STRONG; else if (type == sym_link) node_type = CMARK_NODE_LINK; else if (type == sym_image) node_type = CMARK_NODE_IMAGE; else if (type == <API key>) node_type = <API key>; else if (type == <API key>) node_type = <API key>; else rb_raise(rb_mNodeError, "invalid node of type %d", node_type); node = cmark_node_new(node_type); if (node == NULL) { rb_raise(rb_mNodeError, "could not create node of type %d", node_type); } return rb_node_to_value(node); } /* * Internal: Parses a Markdown string into a document. * */ static VALUE rb_parse_document(VALUE self, VALUE rb_text, VALUE rb_len, VALUE rb_options, VALUE rb_extensions) { char *text; int len, options; cmark_parser *parser; cmark_node *doc; Check_Type(rb_text, T_STRING); Check_Type(rb_len, T_FIXNUM); Check_Type(rb_options, T_FIXNUM); parser = prepare_parser(rb_options, rb_extensions, <API key>()); text = (char *)RSTRING_PTR(rb_text); len = FIX2INT(rb_len); options = FIX2INT(rb_options); cmark_parser_feed(parser, text, len); doc = cmark_parser_finish(parser); if (doc == NULL) { rb_raise(rb_mNodeError, "error parsing document"); } cmark_parser_free(parser); return rb_node_to_value(doc); } /* * Public: Fetch the string contents of the node. * * Returns a {String}. */ static VALUE <API key>(VALUE self) { const char *text; cmark_node *node; Data_Get_Struct(self, cmark_node, node); text = <API key>(node); if (text == NULL) { rb_raise(rb_mNodeError, "could not get string content"); } return encode_utf8_string(text); } /* * Public: Sets the string content of the node. * * string - A {String} containing new content. * * Raises NodeError if the string content can't be set. */ static VALUE <API key>(VALUE self, VALUE s) { char *text; cmark_node *node; Check_Type(s, T_STRING); Data_Get_Struct(self, cmark_node, node); text = StringValueCStr(s); if (!<API key>(node, text)) { rb_raise(rb_mNodeError, "could not set string content"); } return Qnil; } /* * Public: Fetches the list type of the node. * * Returns a {Symbol} representing the node's type. */ static VALUE rb_node_get_type(VALUE self) { int node_type; cmark_node *node; VALUE symbol; const char *s; Data_Get_Struct(self, cmark_node, node); node_type = cmark_node_get_type(node); symbol = Qnil; switch (node_type) { case CMARK_NODE_DOCUMENT: symbol = sym_document; break; case <API key>: symbol = sym_blockquote; break; case CMARK_NODE_LIST: symbol = sym_list; break; case CMARK_NODE_ITEM: symbol = sym_list_item; break; case <API key>: symbol = sym_code_block; break; case CMARK_NODE_HTML: symbol = sym_html; break; case <API key>: symbol = sym_paragraph; break; case CMARK_NODE_HEADER: symbol = sym_header; break; case CMARK_NODE_HRULE: symbol = sym_hrule; break; case CMARK_NODE_TEXT: symbol = sym_text; break; case <API key>: symbol = sym_softbreak; break; case <API key>: symbol = sym_linebreak; break; case CMARK_NODE_CODE: symbol = sym_code; break; case <API key>: symbol = sym_inline_html; break; case CMARK_NODE_EMPH: symbol = sym_emph; break; case CMARK_NODE_STRONG: symbol = sym_strong; break; case CMARK_NODE_LINK: symbol = sym_link; break; case CMARK_NODE_IMAGE: symbol = sym_image; break; case <API key>: symbol = <API key>; break; case <API key>: symbol = <API key>; break; default: if (node->extension) { s = node->extension-><API key>(node->extension, node); return ID2SYM(rb_intern(s)); } rb_raise(rb_mNodeError, "invalid node type %d", node_type); } return symbol; } /* * Public: Fetches the sourcepos of the node. * * Returns a {Hash} containing {Symbol} keys of the positions. */ static VALUE <API key>(VALUE self) { int start_line, start_column, end_line, end_column; VALUE result; cmark_node *node; Data_Get_Struct(self, cmark_node, node); start_line = <API key>(node); start_column = <API key>(node); end_line = <API key>(node); end_column = <API key>(node); result = rb_hash_new(); rb_hash_aset(result, CSTR2SYM("start_line"), INT2NUM(start_line)); rb_hash_aset(result, CSTR2SYM("start_column"), INT2NUM(start_column)); rb_hash_aset(result, CSTR2SYM("end_line"), INT2NUM(end_line)); rb_hash_aset(result, CSTR2SYM("end_column"), INT2NUM(end_column)); return result; } /* * Public: Returns the type of the current pointer as a string. * * Returns a {String}. */ static VALUE <API key>(VALUE self) { cmark_node *node; Data_Get_Struct(self, cmark_node, node); return rb_str_new2(<API key>(node)); } /* * Internal: Unlinks the node from the tree (fixing pointers in * parents and siblings appropriately). */ static VALUE rb_node_unlink(VALUE self) { cmark_node *node; Data_Get_Struct(self, cmark_node, node); cmark_node_unlink(node); rb_parent_removed(self); return Qnil; } /* Public: Fetches the first child of the node. * * Returns a {Node} if a child exists, `nil` otherise. */ static VALUE rb_node_first_child(VALUE self) { cmark_node *node, *child; Data_Get_Struct(self, cmark_node, node); child = <API key>(node); return rb_node_to_value(child); } /* Public: Fetches the next sibling of the node. * * Returns a {Node} if a sibling exists, `nil` otherwise. */ static VALUE rb_node_next(VALUE self) { cmark_node *node, *next; Data_Get_Struct(self, cmark_node, node); next = cmark_node_next(node); return rb_node_to_value(next); } /* * Public: Inserts a node as a sibling before the current node. * * sibling - A sibling {Node} to insert. * * Returns `true` if successful. * Raises NodeError if the node can't be inserted. */ static VALUE <API key>(VALUE self, VALUE sibling) { cmark_node *node1, *node2; Data_Get_Struct(self, cmark_node, node1); Data_Get_Struct(sibling, cmark_node, node2); if (!<API key>(node1, node2)) { rb_raise(rb_mNodeError, "could not insert before"); } rb_parent_added(sibling); return Qtrue; } /* Internal: Convert the node to an HTML string. * * Returns a {String}. */ static VALUE rb_render_html(VALUE self, VALUE rb_options, VALUE rb_extensions) { int options, extensions_len; VALUE rb_ext_name; int i; cmark_node *node; cmark_llist *extensions = NULL; cmark_mem *mem = <API key>(); Check_Type(rb_options, T_FIXNUM); Check_Type(rb_extensions, T_ARRAY); options = FIX2INT(rb_options); extensions_len = RARRAY_LEN(rb_extensions); Data_Get_Struct(self, cmark_node, node); for (i = 0; i < extensions_len; ++i) { rb_ext_name = RARRAY_PTR(rb_extensions)[i]; if (!SYMBOL_P(rb_ext_name)) { cmark_llist_free(mem, extensions); rb_raise(rb_eTypeError, "extension names should be Symbols; got a %"PRIsVALUE"", rb_obj_class(rb_ext_name)); } <API key> *syntax_extension = <API key>(rb_id2name(SYM2ID(rb_ext_name))); if (!syntax_extension) { cmark_llist_free(mem, extensions); rb_raise(rb_eArgError, "extension %s not found\n", rb_id2name(SYM2ID(rb_ext_name))); } extensions = cmark_llist_append(mem, extensions, syntax_extension); } char *html = cmark_render_html(node, options, extensions); VALUE ruby_html = rb_str_new2(html); cmark_llist_free(mem, extensions); free(html); return ruby_html; } /* Internal: Convert the node to a CommonMark string. * * Returns a {String}. */ static VALUE <API key>(int argc, VALUE *argv, VALUE self) { VALUE rb_options, rb_width; rb_scan_args(argc, argv, "11", &rb_options, &rb_width); int width = 120; if (!NIL_P(rb_width)) { Check_Type(rb_width, T_FIXNUM); width = FIX2INT(rb_width); } int options; cmark_node *node; Check_Type(rb_options, T_FIXNUM); options = FIX2INT(rb_options); Data_Get_Struct(self, cmark_node, node); char *cmark = <API key>(node, options, width); VALUE ruby_cmark = rb_str_new2(cmark); free(cmark); return ruby_cmark; } /* Internal: Convert the node to a plain textstring. * * Returns a {String}. */ static VALUE rb_render_plaintext(int argc, VALUE *argv, VALUE self) { VALUE rb_options, rb_width; rb_scan_args(argc, argv, "11", &rb_options, &rb_width); int width = 120; if (!NIL_P(rb_width)) { Check_Type(rb_width, T_FIXNUM); width = FIX2INT(rb_width); } int options; cmark_node *node; Check_Type(rb_options, T_FIXNUM); options = FIX2INT(rb_options); Data_Get_Struct(self, cmark_node, node); char *text = <API key>(node, options, width); VALUE ruby_text = rb_str_new2(text); free(text); return ruby_text; } /* * Public: Inserts a node as a sibling after the current node. * * sibling - A sibling {Node} to insert. * * Returns `true` if successful. * Raises NodeError if the node can't be inserted. */ static VALUE <API key>(VALUE self, VALUE sibling) { cmark_node *node1, *node2; Data_Get_Struct(self, cmark_node, node1); Data_Get_Struct(sibling, cmark_node, node2); if (!<API key>(node1, node2)) { rb_raise(rb_mNodeError, "could not insert after"); } rb_parent_added(sibling); return Qtrue; } /* * Public: Inserts a node as the first child of the current node. * * child - A child {Node} to insert. * * Returns `true` if successful. * Raises NodeError if the node can't be inserted. */ static VALUE <API key>(VALUE self, VALUE child) { cmark_node *node1, *node2; Data_Get_Struct(self, cmark_node, node1); Data_Get_Struct(child, cmark_node, node2); if (!<API key>(node1, node2)) { rb_raise(rb_mNodeError, "could not prepend child"); } rb_parent_added(child); return Qtrue; } /* * Public: Inserts a node as the last child of the current node. * * child - A child {Node} to insert. * * Returns `true` if successful. * Raises NodeError if the node can't be inserted. */ static VALUE <API key>(VALUE self, VALUE child) { cmark_node *node1, *node2; Data_Get_Struct(self, cmark_node, node1); Data_Get_Struct(child, cmark_node, node2); if (!<API key>(node1, node2)) { rb_raise(rb_mNodeError, "could not append child"); } rb_parent_added(child); return Qtrue; } /* Public: Fetches the first child of the current node. * * Returns a {Node} if a child exists, `nil` otherise. */ static VALUE rb_node_last_child(VALUE self) { cmark_node *node, *child; Data_Get_Struct(self, cmark_node, node); child = <API key>(node); return rb_node_to_value(child); } /* Public: Fetches the parent of the current node. * * Returns a {Node} if a parent exists, `nil` otherise. */ static VALUE rb_node_parent(VALUE self) { cmark_node *node, *parent; Data_Get_Struct(self, cmark_node, node); parent = cmark_node_parent(node); return rb_node_to_value(parent); } /* Public: Fetches the previous sibling of the current node. * * Returns a {Node} if a parent exists, `nil` otherise. */ static VALUE rb_node_previous(VALUE self) { cmark_node *node, *previous; Data_Get_Struct(self, cmark_node, node); previous = cmark_node_previous(node); return rb_node_to_value(previous); } /* * Public: Gets the URL of the current node (must be a `:link` or `:image`). * * Returns a {String}. * Raises a NodeError if the URL can't be retrieved. */ static VALUE rb_node_get_url(VALUE self) { const char *text; cmark_node *node; Data_Get_Struct(self, cmark_node, node); text = cmark_node_get_url(node); if (text == NULL) { rb_raise(rb_mNodeError, "could not get url"); } return rb_str_new2(text); } /* * Public: Sets the URL of the current node (must be a `:link` or `:image`). * * url - A {String} representing the new URL * * Raises a NodeError if the URL can't be set. */ static VALUE rb_node_set_url(VALUE self, VALUE url) { cmark_node *node; char *text; Check_Type(url, T_STRING); Data_Get_Struct(self, cmark_node, node); text = StringValueCStr(url); if (!cmark_node_set_url(node, text)) { rb_raise(rb_mNodeError, "could not set url"); } return Qnil; } /* * Public: Gets the title of the current node (must be a `:link` or `:image`). * * Returns a {String}. * Raises a NodeError if the title can't be retrieved. */ static VALUE rb_node_get_title(VALUE self) { const char *text; cmark_node *node; Data_Get_Struct(self, cmark_node, node); text = <API key>(node); if (text == NULL) { rb_raise(rb_mNodeError, "could not get title"); } return rb_str_new2(text); } /* * Public: Sets the title of the current node (must be a `:link` or `:image`). * * title - A {String} representing the new title * * Raises a NodeError if the title can't be set. */ static VALUE rb_node_set_title(VALUE self, VALUE title) { char *text; cmark_node *node; Check_Type(title, T_STRING); Data_Get_Struct(self, cmark_node, node); text = StringValueCStr(title); if (!<API key>(node, text)) { rb_raise(rb_mNodeError, "could not set title"); } return Qnil; } /* * Public: Gets the header level of the current node (must be a `:header`). * * Returns a {Number} representing the header level. * Raises a NodeError if the header level can't be retrieved. */ static VALUE <API key>(VALUE self) { int header_level; cmark_node *node; Data_Get_Struct(self, cmark_node, node); header_level = <API key>(node); if (header_level == 0) { rb_raise(rb_mNodeError, "could not get header_level"); } return INT2NUM(header_level); } /* * Public: Sets the header level of the current node (must be a `:header`). * * level - A {Number} representing the new header level * * Raises a NodeError if the header level can't be set. */ static VALUE <API key>(VALUE self, VALUE level) { int l; cmark_node *node; Check_Type(level, T_FIXNUM); Data_Get_Struct(self, cmark_node, node); l = FIX2INT(level); if (!<API key>(node, l)) { rb_raise(rb_mNodeError, "could not set header_level"); } return Qnil; } /* * Public: Gets the list type of the current node (must be a `:list`). * * Returns a {Symbol}. * Raises a NodeError if the title can't be retrieved. */ static VALUE <API key>(VALUE self) { int list_type; cmark_node *node; VALUE symbol; Data_Get_Struct(self, cmark_node, node); list_type = <API key>(node); if (list_type == CMARK_BULLET_LIST) { symbol = sym_bullet_list; } else if (list_type == CMARK_ORDERED_LIST) { symbol = sym_ordered_list; } else { rb_raise(rb_mNodeError, "could not get list_type"); } return symbol; } /* * Public: Sets the list type of the current node (must be a `:list`). * * level - A {Symbol} representing the new list type * * Raises a NodeError if the list type can't be set. */ static VALUE <API key>(VALUE self, VALUE list_type) { int type = 0; cmark_node *node; Check_Type(list_type, T_SYMBOL); Data_Get_Struct(self, cmark_node, node); if (list_type == sym_bullet_list) { type = CMARK_BULLET_LIST; } else if (list_type == sym_ordered_list) { type = CMARK_ORDERED_LIST; } else { rb_raise(rb_mNodeError, "invalid list_type"); } if (!<API key>(node, type)) { rb_raise(rb_mNodeError, "could not set list_type"); } return Qnil; } /* * Public: Gets the starting number the current node (must be an * `:ordered_list`). * * Returns a {Number} representing the starting number. * Raises a NodeError if the starting number can't be retrieved. */ static VALUE <API key>(VALUE self) { cmark_node *node; Data_Get_Struct(self, cmark_node, node); if (cmark_node_get_type(node) != CMARK_NODE_LIST || <API key>(node) != CMARK_ORDERED_LIST) { rb_raise(rb_mNodeError, "can't get list_start for non-ordered list %d", <API key>(node)); } return INT2NUM(<API key>(node)); } /* * Public: Sets the starting number of the current node (must be an * `:ordered_list`). * * level - A {Number} representing the new starting number * * Raises a NodeError if the starting number can't be set. */ static VALUE <API key>(VALUE self, VALUE start) { int s; cmark_node *node; Check_Type(start, T_FIXNUM); Data_Get_Struct(self, cmark_node, node); s = FIX2INT(start); if (!<API key>(node, s)) { rb_raise(rb_mNodeError, "could not set list_start"); } return Qnil; } /* * Public: Gets the tight status the current node (must be a `:list`). * * Returns a `true` if the list is tight, `false` otherwise. * Raises a NodeError if the starting number can't be retrieved. */ static VALUE <API key>(VALUE self) { int flag; cmark_node *node; Data_Get_Struct(self, cmark_node, node); if (cmark_node_get_type(node) != CMARK_NODE_LIST) { rb_raise(rb_mNodeError, "can't get list_tight for non-list"); } flag = <API key>(node); return flag ? Qtrue : Qfalse; } /* * Public: Sets the tight status of the current node (must be a `:list`). * * tight - A {Boolean} representing the new tightness * * Raises a NodeError if the tightness can't be set. */ static VALUE <API key>(VALUE self, VALUE tight) { int t; cmark_node *node; Data_Get_Struct(self, cmark_node, node); t = RTEST(tight); if (!<API key>(node, t)) { rb_raise(rb_mNodeError, "could not set list_tight"); } return Qnil; } /* * Public: Gets the fence info of the current node (must be a `:code_block`). * * Returns a {String} representing the fence info. * Raises a NodeError if the fence info can't be retrieved. */ static VALUE <API key>(VALUE self) { const char *fence_info; cmark_node *node; Data_Get_Struct(self, cmark_node, node); fence_info = <API key>(node); if (fence_info == NULL) { rb_raise(rb_mNodeError, "could not get fence_info"); } return rb_str_new2(fence_info); } /* * Public: Sets the fence info of the current node (must be a `:code_block`). * * info - A {String} representing the new fence info * * Raises a NodeError if the fence info can't be set. */ static VALUE <API key>(VALUE self, VALUE info) { char *text; cmark_node *node; Check_Type(info, T_STRING); Data_Get_Struct(self, cmark_node, node); text = StringValueCStr(info); if (!<API key>(node, text)) { rb_raise(rb_mNodeError, "could not set fence_info"); } return Qnil; } static VALUE <API key>(VALUE self) { uint16_t column_count, i; uint8_t *alignments; cmark_node *node; VALUE ary; Data_Get_Struct(self, cmark_node, node); column_count = <API key>(node); alignments = <API key>(node); if (!column_count || !alignments) { rb_raise(rb_mNodeError, "could not get column_count or alignments"); } ary = rb_ary_new(); for (i = 0; i < column_count; ++i) { if (alignments[i] == 'l') rb_ary_push(ary, sym_left); else if (alignments[i] == 'c') rb_ary_push(ary, sym_center); else if (alignments[i] == 'r') rb_ary_push(ary, sym_right); else rb_ary_push(ary, Qnil); } return ary; } /* Internal: Escapes href URLs safely. */ static VALUE rb_html_escape_href(VALUE self, VALUE rb_text) { char *result; cmark_node *node; Check_Type(rb_text, T_STRING); Data_Get_Struct(self, cmark_node, node); cmark_mem *mem = cmark_node_mem(node); cmark_strbuf buf = CMARK_BUF_INIT(mem); if (houdini_escape_href(&buf, (const uint8_t *)RSTRING_PTR(rb_text), RSTRING_LEN(rb_text))) { result = (char *)cmark_strbuf_detach(&buf); return rb_str_new2(result); } return rb_text; } /* Internal: Escapes HTML content safely. */ static VALUE rb_html_escape_html(VALUE self, VALUE rb_text) { char *result; cmark_node *node; Check_Type(rb_text, T_STRING); Data_Get_Struct(self, cmark_node, node); cmark_mem *mem = cmark_node_mem(node); cmark_strbuf buf = CMARK_BUF_INIT(mem); if (<API key>(&buf, (const uint8_t *)RSTRING_PTR(rb_text), RSTRING_LEN(rb_text), 0)) { result = (char *)cmark_strbuf_detach(&buf); return rb_str_new2(result); } return rb_text; } VALUE rb_extensions(VALUE self) { cmark_llist *exts, *it; <API key> *ext; VALUE ary = rb_ary_new(); cmark_mem *mem = <API key>(); exts = <API key>(mem); for (it = exts; it; it = it->next) { ext = it->data; rb_ary_push(ary, rb_str_new2(ext->name)); } cmark_llist_free(mem, exts); return ary; } __attribute__((visibility("default"))) void Init_commonmarker() { VALUE module; sym_document = ID2SYM(rb_intern("document")); sym_blockquote = ID2SYM(rb_intern("blockquote")); sym_list = ID2SYM(rb_intern("list")); sym_list_item = ID2SYM(rb_intern("list_item")); sym_code_block = ID2SYM(rb_intern("code_block")); sym_html = ID2SYM(rb_intern("html")); sym_paragraph = ID2SYM(rb_intern("paragraph")); sym_header = ID2SYM(rb_intern("header")); sym_hrule = ID2SYM(rb_intern("hrule")); sym_text = ID2SYM(rb_intern("text")); sym_softbreak = ID2SYM(rb_intern("softbreak")); sym_linebreak = ID2SYM(rb_intern("linebreak")); sym_code = ID2SYM(rb_intern("code")); sym_inline_html = ID2SYM(rb_intern("inline_html")); sym_emph = ID2SYM(rb_intern("emph")); sym_strong = ID2SYM(rb_intern("strong")); sym_link = ID2SYM(rb_intern("link")); sym_image = ID2SYM(rb_intern("image")); <API key> = ID2SYM(rb_intern("footnote_reference")); <API key> = ID2SYM(rb_intern("footnote_definition")); sym_bullet_list = ID2SYM(rb_intern("bullet_list")); sym_ordered_list = ID2SYM(rb_intern("ordered_list")); sym_left = ID2SYM(rb_intern("left")); sym_right = ID2SYM(rb_intern("right")); sym_center = ID2SYM(rb_intern("center")); module = rb_define_module("CommonMarker"); <API key>(module, "extensions", rb_extensions, 0); rb_mNodeError = <API key>(module, "NodeError", rb_eStandardError); rb_mNode = <API key>(module, "Node", rb_cObject); <API key>(rb_mNode, "markdown_to_html", rb_markdown_to_html, 3); <API key>(rb_mNode, "new", rb_node_new, 1); <API key>(rb_mNode, "parse_document", rb_parse_document, 4); rb_define_method(rb_mNode, "string_content", <API key>, 0); rb_define_method(rb_mNode, "string_content=", <API key>, 1); rb_define_method(rb_mNode, "type", rb_node_get_type, 0); rb_define_method(rb_mNode, "type_string", <API key>, 0); rb_define_method(rb_mNode, "sourcepos", <API key>, 0); rb_define_method(rb_mNode, "delete", rb_node_unlink, 0); rb_define_method(rb_mNode, "first_child", rb_node_first_child, 0); rb_define_method(rb_mNode, "next", rb_node_next, 0); rb_define_method(rb_mNode, "insert_before", <API key>, 1); rb_define_method(rb_mNode, "_render_html", rb_render_html, 2); rb_define_method(rb_mNode, "_render_commonmark", <API key>, -1); rb_define_method(rb_mNode, "_render_plaintext", rb_render_plaintext, -1); rb_define_method(rb_mNode, "insert_after", <API key>, 1); rb_define_method(rb_mNode, "prepend_child", <API key>, 1); rb_define_method(rb_mNode, "append_child", <API key>, 1); rb_define_method(rb_mNode, "last_child", rb_node_last_child, 0); rb_define_method(rb_mNode, "parent", rb_node_parent, 0); rb_define_method(rb_mNode, "previous", rb_node_previous, 0); rb_define_method(rb_mNode, "url", rb_node_get_url, 0); rb_define_method(rb_mNode, "url=", rb_node_set_url, 1); rb_define_method(rb_mNode, "title", rb_node_get_title, 0); rb_define_method(rb_mNode, "title=", rb_node_set_title, 1); rb_define_method(rb_mNode, "header_level", <API key>, 0); rb_define_method(rb_mNode, "header_level=", <API key>, 1); rb_define_method(rb_mNode, "list_type", <API key>, 0); rb_define_method(rb_mNode, "list_type=", <API key>, 1); rb_define_method(rb_mNode, "list_start", <API key>, 0); rb_define_method(rb_mNode, "list_start=", <API key>, 1); rb_define_method(rb_mNode, "list_tight", <API key>, 0); rb_define_method(rb_mNode, "list_tight=", <API key>, 1); rb_define_method(rb_mNode, "fence_info", <API key>, 0); rb_define_method(rb_mNode, "fence_info=", <API key>, 1); rb_define_method(rb_mNode, "table_alignments", <API key>, 0); rb_define_method(rb_mNode, "html_escape_href", rb_html_escape_href, 1); rb_define_method(rb_mNode, "html_escape_html", rb_html_escape_html, 1); <API key>(); }
from collections import deque import weakref import py4j.protocol as proto from py4j.clientserver import ( <API key>, ClientServer, JavaClient, PythonServer) from py4j.java_gateway import ( CallbackServer, JavaGateway, GatewayClient, GatewayProperty, PythonProxyPool, GatewayConnection, CallbackConnection) from py4j.tests.<API key> import PythonPing # Use deque to be thread-safe MEMORY_HOOKS = deque() CREATED = deque() FINALIZED = deque() def register_creation(obj): obj_str = str(obj) CREATED.append(obj_str) MEMORY_HOOKS.append(weakref.ref( obj, lambda wr: FINALIZED.append(obj_str) )) class <API key>(PythonPing): def __init__(self, fail=False): super(<API key>, self).__init__(fail) register_creation(self) class InstrJavaGateway(JavaGateway): def __init__(self, *args, **kwargs): super(InstrJavaGateway, self). __init__(*args, **kwargs) register_creation(self) def <API key>(self): gateway_client = InstrGatewayClient( gateway_parameters=self.gateway_parameters) return gateway_client def <API key>(self, <API key>): callback_server = InstrCallbackServer( self.gateway_property.pool, self._gateway_client, <API key>=<API key>) return callback_server def <API key>(self): gateway_property = <API key>( self.gateway_parameters.auto_field, PythonProxyPool(), self.gateway_parameters.<API key>) if self.<API key>: gateway_property.pool.put( self.<API key>, proto.<API key>) return gateway_property class InstrGatewayClient(GatewayClient): def __init__(self, *args, **kwargs): super(InstrGatewayClient, self).__init__(*args, **kwargs) register_creation(self) def _create_connection(self): connection = <API key>( self.gateway_parameters, self.gateway_property) connection.start() return connection class <API key>(GatewayProperty): """Object shared by callbackserver, gateway, and connections. """ def __init__(self, *args, **kwargs): super(<API key>, self).__init__(*args, **kwargs) register_creation(self) class <API key>(GatewayConnection): def __init__(self, *args, **kwargs): super(<API key>, self).__init__(*args, **kwargs) register_creation(self) class InstrCallbackServer(CallbackServer): def __init__(self, *args, **kwargs): super(InstrCallbackServer, self).__init__(*args, **kwargs) register_creation(self) def _create_connection(self, socket_instance, stream): connection = <API key>( self.pool, stream, socket_instance, self.gateway_client, self.<API key>, self) return connection class <API key>(CallbackConnection): def __init__(self, *args, **kwargs): super(<API key>, self).__init__(*args, **kwargs) register_creation(self) class <API key>(<API key>): def __init__(self, *args, **kwargs): super(<API key>, self).__init__(*args, **kwargs) register_creation(self) class InstrPythonServer(PythonServer): def __init__(self, *args, **kwargs): super(InstrPythonServer, self).__init__(*args, **kwargs) register_creation(self) def _create_connection(self, socket, stream): connection = <API key>( self.java_parameters, self.python_parameters, self.gateway_property, self.gateway_client, self) connection.<API key>(socket, stream) return connection class InstrJavaClient(JavaClient): def __init__(self, *args, **kwargs): super(InstrJavaClient, self).__init__(*args, **kwargs) register_creation(self) def <API key>(self): connection = <API key>( self.java_parameters, self.python_parameters, self.gateway_property, self) connection.<API key>() self.<API key>(connection) self.deque.append(connection) return connection class InstrClientServer(ClientServer): def __init__(self, *args, **kwargs): super(InstrClientServer, self).__init__(*args, **kwargs) register_creation(self) def <API key>(self): java_client = InstrJavaClient( self.java_parameters, self.python_parameters) return java_client def <API key>(self, <API key>): callback_server = InstrPythonServer( self._gateway_client, self.java_parameters, self.python_parameters, self.gateway_property) return callback_server def <API key>(self): gateway_property = <API key>( self.java_parameters.auto_field, PythonProxyPool(), self.java_parameters.<API key>) if self.<API key>: gateway_property.pool.put( self.<API key>, proto.<API key>) return gateway_property
// Peloton // notifiable_task.cpp // Identification: src/common/notifiable_task.cpp #include "common/notifiable_task.h" #include "common/logger.h" #include "common/event_util.h" #include <cstring> namespace peloton { NotifiableTask::NotifiableTask(int task_id) : task_id_(task_id) { base_ = EventUtil::EventBaseNew(); // For exiting a loop terminate_ = RegisterManualEvent([](int, short, void *arg) { EventUtil::EventBaseLoopExit((struct event_base *) arg, nullptr); }, base_); }; NotifiableTask::~NotifiableTask() { for (struct event *event : events_) { EventUtil::EventDel(event); event_free(event); } event_base_free(base_); } struct event *NotifiableTask::RegisterEvent(int fd, short flags, event_callback_fn callback, void *arg, const struct timeval *timeout) { struct event *event = event_new(base_, fd, flags, callback, arg); events_.insert(event); EventUtil::EventAdd(event, timeout); return event; } void NotifiableTask::UnregisterEvent(struct event *event) { auto it = events_.find(event); if (it == events_.end()) return; if (event_del(event) == -1) { LOG_ERROR("Failed to delete event"); return; } event_free(event); events_.erase(event); } } // namespace peloton
// Code generated by protoc-gen-validate. DO NOT EDIT. // source: envoy/type/matcher/v3/metadata.proto package <API key> import ( "bytes" "errors" "fmt" "net" "net/mail" "net/url" "regexp" "strings" "time" "unicode/utf8" "github.com/golang/protobuf/ptypes" ) // ensure the imports are used var ( _ = bytes.MinRead _ = errors.New("") _ = fmt.Print _ = utf8.UTFMax _ = (*regexp.Regexp)(nil) _ = (*strings.Reader)(nil) _ = net.IPv4len _ = time.Duration(0) _ = (*url.URL)(nil) _ = (*mail.Address)(nil) _ = ptypes.DynamicAny{} ) // Validate checks the field values on MetadataMatcher with the rules defined // in the proto definition for this message. If any rules are violated, an // error is returned. func (m *MetadataMatcher) Validate() error { if m == nil { return nil } if utf8.RuneCountInString(m.GetFilter()) < 1 { return <API key>{ field: "Filter", reason: "value length must be at least 1 runes", } } if len(m.GetPath()) < 1 { return <API key>{ field: "Path", reason: "value must contain at least 1 item(s)", } } for idx, item := range m.GetPath() { _, _ = idx, item if v, ok := interface{}(item).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return <API key>{ field: fmt.Sprintf("Path[%v]", idx), reason: "embedded message failed validation", cause: err, } } } } if m.GetValue() == nil { return <API key>{ field: "Value", reason: "value is required", } } if v, ok := interface{}(m.GetValue()).(interface{ Validate() error }); ok { if err := v.Validate(); err != nil { return <API key>{ field: "Value", reason: "embedded message failed validation", cause: err, } } } return nil } // <API key> is the validation error returned by // MetadataMatcher.Validate if the designated constraints aren't met. type <API key> struct { field string reason string cause error key bool } // Field function returns field value. func (e <API key>) Field() string { return e.field } // Reason function returns reason value. func (e <API key>) Reason() string { return e.reason } // Cause function returns cause value. func (e <API key>) Cause() error { return e.cause } // Key function returns key value. func (e <API key>) Key() bool { return e.key } // ErrorName returns error name. func (e <API key>) ErrorName() string { return "<API key>" } // Error satisfies the builtin error interface func (e <API key>) Error() string { cause := "" if e.cause != nil { cause = fmt.Sprintf(" | caused by: %v", e.cause) } key := "" if e.key { key = "key for " } return fmt.Sprintf( "invalid %sMetadataMatcher.%s: %s%s", key, e.field, e.reason, cause) } var _ error = <API key>{} var _ interface { Field() string Reason() string Key() bool Cause() error ErrorName() string } = <API key>{} // Validate checks the field values on <API key> with the // rules defined in the proto definition for this message. If any rules are // violated, an error is returned. func (m *<API key>) Validate() error { if m == nil { return nil } switch m.Segment.(type) { case *<API key>: if utf8.RuneCountInString(m.GetKey()) < 1 { return <API key>{ field: "Key", reason: "value length must be at least 1 runes", } } default: return <API key>{ field: "Segment", reason: "value is required", } } return nil } // <API key> is the validation error returned // by <API key>.Validate if the designated constraints // aren't met. type <API key> struct { field string reason string cause error key bool } // Field function returns field value. func (e <API key>) Field() string { return e.field } // Reason function returns reason value. func (e <API key>) Reason() string { return e.reason } // Cause function returns cause value. func (e <API key>) Cause() error { return e.cause } // Key function returns key value. func (e <API key>) Key() bool { return e.key } // ErrorName returns error name. func (e <API key>) ErrorName() string { return "<API key>" } // Error satisfies the builtin error interface func (e <API key>) Error() string { cause := "" if e.cause != nil { cause = fmt.Sprintf(" | caused by: %v", e.cause) } key := "" if e.key { key = "key for " } return fmt.Sprintf( "invalid %<API key>.%s: %s%s", key, e.field, e.reason, cause) } var _ error = <API key>{} var _ interface { Field() string Reason() string Key() bool Cause() error ErrorName() string } = <API key>{}
// file at the top-level directory of this distribution and at // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around any Reader to treat it as an RNG. use io::Reader; use rand::Rng; use result::{Ok, Err}; use slice::SlicePrelude; An RNG that reads random bytes straight from a `Reader`. This will work best with an infinite reader, but this is not required. # Panics It will panic if it there is insufficient data to fulfill a request. # Example ```rust use std::rand::{reader, Rng}; use std::io::MemReader; let mut rng = reader::ReaderRng::new(MemReader::new(vec!(1,2,3,4,5,6,7,8))); println!("{:x}", rng.gen::<uint>()); ``` pub struct ReaderRng<R> { reader: R } impl<R: Reader> ReaderRng<R> { Create a new `ReaderRng` from a `Reader`. pub fn new(r: R) -> ReaderRng<R> { ReaderRng { reader: r } } } impl<R: Reader> Rng for ReaderRng<R> { fn next_u32(&mut self) -> u32 { // This is designed for speed: reading a LE integer on a LE // platform just involves blitting the bytes into the memory // of the u32, similarly for BE on BE; avoiding byteswapping. if cfg!(target_endian="little") { self.reader.read_le_u32().unwrap() } else { self.reader.read_be_u32().unwrap() } } fn next_u64(&mut self) -> u64 { // see above for explanation. if cfg!(target_endian="little") { self.reader.read_le_u64().unwrap() } else { self.reader.read_be_u64().unwrap() } } fn fill_bytes(&mut self, v: &mut [u8]) { if v.len() == 0 { return } match self.reader.read_at_least(v.len(), v) { Ok(_) => {} Err(e) => panic!("ReaderRng.fill_bytes error: {}", e) } } } #[cfg(test)] mod test { use prelude::*; use super::ReaderRng; use io::MemReader; use num::Int; use rand::Rng; #[test] fn test_reader_rng_u64() { // transmute from the target to avoid endianness concerns. let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1, 0 , 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3]; let mut rng = ReaderRng::new(MemReader::new(v)); assert_eq!(rng.next_u64(), 1_u64.to_be()); assert_eq!(rng.next_u64(), 2_u64.to_be()); assert_eq!(rng.next_u64(), 3_u64.to_be()); } #[test] fn test_reader_rng_u32() { let v = vec![0u8, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3]; let mut rng = ReaderRng::new(MemReader::new(v)); assert_eq!(rng.next_u32(), 1_u32.to_be()); assert_eq!(rng.next_u32(), 2_u32.to_be()); assert_eq!(rng.next_u32(), 3_u32.to_be()); } #[test] fn <API key>() { let v = [1u8, 2, 3, 4, 5, 6, 7, 8]; let mut w = [0u8, .. 8]; let mut rng = ReaderRng::new(MemReader::new(v.as_slice().to_vec())); rng.fill_bytes(&mut w); assert!(v == w); } #[test] #[should_fail] fn <API key>() { let mut rng = ReaderRng::new(MemReader::new(vec!())); let mut v = [0u8, .. 3]; rng.fill_bytes(&mut v); } }
'use strict'; describe('specs for directives', function() { beforeEach(module('myApp.directives')); var $scope; beforeEach(inject(function($rootScope) { $scope = $rootScope.$new(); $scope.name = {first: "Jane", last: "Doe"}; })); describe('hello-world', function() { it('should contain the provided name', function() { inject(function($compile) { var element = $compile('<div hello-world name="name"></div>')($scope); $scope.$digest(); expect(element.html()).toContain('Jane'); }); }); }); });
#ifndef MEM_HPP #define MEM_HPP #include <cuda.h> #include "bindings.hpp" #include "function.hpp" namespace NodeCuda { class Mem : public ObjectWrap { public: static void Initialize(Handle<Object> target); static Handle<Value> GetDevicePtr(Local<String> property, const AccessorInfo &info); protected: static Persistent<FunctionTemplate> <API key>; static Handle<Value> Alloc(const Arguments& args); static Handle<Value> AllocPitch(const Arguments& args); static Handle<Value> Free(const Arguments& args); static Handle<Value> CopyHtoD(const Arguments& args); static Handle<Value> CopyDtoH(const Arguments& args); static Handle<Value> mem_Set(const Arguments& args); Mem() : ObjectWrap(), m_devicePtr(0) {} ~Mem() {} private: static Handle<Value> New(const Arguments& args); CUdeviceptr m_devicePtr; friend class NodeCuda::Function; }; } #endif
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function <API key>(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // This class is a reference implementation. If you desire additional // functionality, you can work with the config options here, or copy this code // into your project and customize the ApiClient to your needs. // You can pass in config using `action.payload.fetchConfig`, or using passedConfig // when you first initialize your ApiClient. Some keys will be used internally, and // all other config keys will be passed on to the fetch `init` parameter. See // See below for how the three config objects are merged: fetchConfig takes precedence // over passedConfig, which takes precedence over baseConfig. The headers key of // the three objects is merged, to allow more fine-grained header setup. // `methods` will be ignored if passed to fetchConfig. Pass an array to passedConfig // to allow more HTTP methods to be used via the fetch API. // `basePath` is the basePath of your API. It must be passed to passedConfig, and can // be overwritten in fetchConfig. // `format` is the format to be requested from the Response. It can be any of arrayBuffer, // blob, formData, json (the default), or text. // `bodyEncoder` is the function that encodes the data parameter before passing to fetch // All other keys are passed directly to the fetch `init` parameter. var ApiClient = function () { function ApiClient(passedConfig) { var _this = this; _classCallCheck(this, ApiClient); var baseConfig = { bodyEncoder: JSON.stringify, credentials: 'same-origin', format: 'json', headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, methods: ['get', 'post', 'put', 'patch', 'delete'] }; if (!passedConfig.basePath) { throw new Error('You must pass a base path to the ApiClient'); } var methods = passedConfig.methods || baseConfig.methods; methods.forEach(function (method) { _this[method] = function (path) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, params = _ref.params, data = _ref.data, fetchConfig = _ref.fetchConfig; var config = _extends({}, baseConfig, passedConfig, fetchConfig, { headers: _extends({}, baseConfig.headers, passedConfig ? passedConfig.headers : {}, fetchConfig ? fetchConfig.headers : {}) }); var _methods = config.methods, basePath = config.basePath, headers = config.headers, format = config.format, bodyEncoder = config.bodyEncoder, otherConfig = <API key>(config, ['methods', 'basePath', 'headers', 'format', 'bodyEncoder']); var requestPath = basePath + path + _this.queryString(params); var body = data ? bodyEncoder(data) : undefined; return fetch(requestPath, _extends({}, otherConfig, { method: method, headers: headers, body: body })).then(function (response) { return { response: response, format: format }; }).then(_this.handleErrors).then(function (response) { return response[format](); }); }; }); } _createClass(ApiClient, [{ key: 'queryString', value: function queryString(params) { var s = Object.keys(params).map(function (key) { return [key, params[key]].map(encodeURIComponent).join('='); }).join('&'); return s ? '?' + s : ''; } }, { key: 'handleErrors', value: function handleErrors(_ref2) { var response = _ref2.response, format = _ref2.format; if (!response.ok) { return response[format]() // if response parsing failed send back the entire response object .catch(function () { throw response; }) // else send back the parsed error .then(function (parsedErr) { throw parsedErr; }); } return response; } }]); return ApiClient; }(); exports.default = ApiClient;
namespace StructureMap.Diagnostics.TreeView { public class Astericks : Section { private readonly string _buffer; public Astericks() : this(5) { } public Astericks(int tabWidth) { _buffer = "* ".PadLeft(tabWidth); } public override int TabWidth { get { return _buffer.Length; } } protected override void applyBuffer(Line line, int index) { line.Prepend(_buffer); } } }
<div id="screen"> <h1>Hi. I'm default.</h1> <p>Don't be sad, I don't mind being nobody. It's okay, really.</p> </div>
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="pl"> <head> <!-- Generated by javadoc (1.8.0) on Mon Jul 28 12:08:59 CEST 2014 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ParamConverter (JUnitParams 1.0.3-SNAPSHOT API)</title> <meta name="date" content="2014-07-28"> <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="ParamConverter (JUnitParams 1.0.3-SNAPSHOT API)"; } } catch(err) { } var methods = {"i0":6}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <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="class-use/ParamConverter.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../junitparams/converters/ConvertParam.html" title="annotation in junitparams.converters"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../index.html?junitparams/converters/ParamConverter.html" target="_top">Frames</a></li> <li><a href="ParamConverter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <div class="subTitle">junitparams.converters</div> <h2 title="Interface ParamConverter" class="title">Interface ParamConverter&lt;T&gt;</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public interface <span class="typeNameLabel">ParamConverter&lt;T&gt;</span></pre> <div class="block">Implement this interface if you want to convert params from some representation to the type expected by your test method's parameter. &lt;T&gt; is the expected parameter type.</div> <dl> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>Pawel Lipinski</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="method.summary"> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code><a href="../../junitparams/converters/ParamConverter.html" title="type parameter in ParamConverter">T</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../junitparams/converters/ParamConverter.html <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;options)</code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="method.detail"> </a> <h3>Method Detail</h3> <a name="convert-java.lang.Object-java.lang.String-"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>convert</h4> <pre><a href="../../junitparams/converters/ParamConverter.html" title="type parameter in ParamConverter">T</a>&nbsp;convert(<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;param, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;options) throws <a href="../../junitparams/converters/<API key>.html" title="class in junitparams.converters"><API key></a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="../../junitparams/converters/<API key>.html" title="class in junitparams.converters"><API key></a></code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <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="class-use/ParamConverter.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../junitparams/converters/ConvertParam.html" title="annotation in junitparams.converters"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../index.html?junitparams/converters/ParamConverter.html" target="_top">Frames</a></li> <li><a href="ParamConverter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> </a></div> <p class="legalCopy"><small>Copyright & </body> </html>
import { BoundingSphere } from "../../Source/Cesium.js"; import { Cartesian3 } from "../../Source/Cesium.js"; import { Ellipsoid } from "../../Source/Cesium.js"; import { JulianDate } from "../../Source/Cesium.js"; import { <API key> } from "../../Source/Cesium.js"; import { Entity } from "../../Source/Cesium.js"; import { EntityView } from "../../Source/Cesium.js"; import createScene from "../createScene.js"; describe( "DataSources/EntityView", function () { var scene; var defaultOffset = EntityView.defaultOffset3D; beforeAll(function () { scene = createScene(); }); beforeEach(function () { EntityView.defaultOffset3D = defaultOffset.clone(); }); afterAll(function () { scene.destroyForSpecs(); }); it("throws when constructed without required values", function () { var entity = new Entity(); var view; expect(function () { view = new EntityView(undefined, scene); }).<API key>(); expect(function () { view = new EntityView(entity, undefined); }).<API key>(); view = new EntityView(entity, scene); expect(view.ellipsoid).toBe(Ellipsoid.WGS84); }); it("constructor sets expected values", function () { var entity = new Entity(); var ellipsoid = Ellipsoid.UNIT_SPHERE; var view = new EntityView(entity, scene, ellipsoid); expect(view.entity).toBe(entity); expect(view.scene).toBe(scene); expect(view.ellipsoid).toBe(Ellipsoid.UNIT_SPHERE); }); it("can set and get defaultOffset3D", function () { var sampleOffset = new Cartesian3(1, 2, 3); EntityView.defaultOffset3D = sampleOffset; var entity = new Entity(); entity.position = new <API key>( Cartesian3.fromDegrees(0.0, 0.0) ); var view = new EntityView(entity, scene); view.update(JulianDate.now()); expect(EntityView.defaultOffset3D).toEqualEpsilon(sampleOffset, 1e-10); expect(view.scene.camera.position).toEqualEpsilon(sampleOffset, 1e-10); }); it("uses entity viewFrom", function () { var sampleOffset = new Cartesian3(1, 2, 3); var entity = new Entity(); entity.position = new <API key>( Cartesian3.fromDegrees(0.0, 0.0) ); entity.viewFrom = sampleOffset; var view = new EntityView(entity, scene); view.update(JulianDate.now()); expect(view.scene.camera.position).toEqualEpsilon(sampleOffset, 1e-10); }); it("uses entity bounding sphere", function () { var sampleOffset = new Cartesian3( -1.<API key>, -7.348469228349534, 7.3484692283495345 ); var entity = new Entity(); entity.position = new <API key>( Cartesian3.fromDegrees(0.0, 0.0) ); var view = new EntityView(entity, scene, undefined); view.update( JulianDate.now(), new BoundingSphere(new Cartesian3(3, 4, 5), 6) ); expect(view.scene.camera.position).toEqualEpsilon(sampleOffset, 1e-10); }); it("uses entity viewFrom if available and boundingsphere is supplied", function () { var sampleOffset = new Cartesian3(1, 2, 3); var entity = new Entity(); entity.position = new <API key>( Cartesian3.fromDegrees(0.0, 0.0) ); entity.viewFrom = sampleOffset; var view = new EntityView( entity, scene, undefined, new BoundingSphere(new Cartesian3(3, 4, 5), 6) ); view.update(JulianDate.now()); expect(view.scene.camera.position).toEqualEpsilon(sampleOffset, 1e-10); }); it("update throws without time parameter", function () { var entity = new Entity(); entity.position = new <API key>(Cartesian3.ZERO); var view = new EntityView(entity, scene); expect(function () { view.update(undefined); }).<API key>(); }); it("update returns without entity.position property.", function () { var entity = new Entity(); var view = new EntityView(entity, scene); view.update(JulianDate.now()); }); }, "WebGL" );
""" The Accounts module contains the base definition for a Qubole account object """ from qds_sdk.resource import SingletonResource from qds_sdk.qubole import Qubole import argparse class AccountCmdLine: @staticmethod def parsers(): argparser = argparse.ArgumentParser( prog="qds.py account", description="Account Creation for Qubole Data Service.") subparsers = argparser.add_subparsers(title="account operations") # Create create = subparsers.add_parser( "create", help="Create a new account") create.add_argument( "--name", dest="name", required=True, help="Account name") create.add_argument( "--location", dest="defloc", required=True, help="Default S3 location for storing logs, result and cached data") create.add_argument( "--storage-access-key", dest="acc_key", required=True, help="AWS Access Key ID for storage") create.add_argument( "--storage-secret-key", dest="secret", required=True, help="AWS Secret Access Key for storage") create.add_argument( "--compute-access-key", dest="compute_access_key", required=True, help="AWS Access Key ID for compute") create.add_argument( "--compute-secret-key", dest="compute_secret_key", required=True, help="AWS Secret Access Key for compute") create.add_argument( "--aws-region", dest="aws_region", required=True, help="AWS Region", choices=["us-east-1", "us-west-2", "ap-northeast-1", "sa-east-1", "eu-west-1", "ap-southeast-1", "us-west-1"]) create.add_argument( "--<API key>", dest="<API key>", choices=["true", "false"], default="false", help="Use previous account plan, default: false") create.set_defaults(func=AccountCmdLine.create) return argparser @staticmethod def run(args): parser = AccountCmdLine.parsers() parsed = parser.parse_args(args) return parsed.func(parsed) @staticmethod def create(args): args.level = "free" args.compute_type = "CUSTOMER_MANAGED" args.storage_type = "CUSTOMER_MANAGED" args.CacheQuotaSizeInGB = "25" v = {} args = vars(args) args.pop("func") v['account'] = args result = Account.create(**v) return result class Account(SingletonResource): <API key> = "accounts/get_creds" rest_entity_path = "account" @classmethod def create(cls, **kwargs): conn = Qubole.agent() return cls(conn.post(cls.rest_entity_path, data=kwargs))
# $NetBSD: Makefile,v 1.4 1997/10/18 16:48:29 mrg Exp $ # from: @(#)Makefile 8.1 (Berkeley) 6/6/93 PROG= wc .include <bsd.prog.mk>
#ifndef _Vocab_h_ #define _Vocab_h_ #ifdef PRE_ISO_CXX # include <iostream.h> #else # include <iostream> using namespace std; #endif #include "Boolean.h" #include "File.h" #include "LHash.h" #include "SArray.h" #include "Array.h" #include "MemStats.h" #ifdef USE_SHORT_VOCAB typedef unsigned short VocabIndex; #else typedef unsigned int VocabIndex; #endif typedef const char *VocabString; const unsigned int maxWordLength = 1024; const VocabIndex Vocab_None = (VocabIndex)-1; const VocabString Vocab_Unknown = "<unk>"; const VocabString Vocab_SentStart = "<s>"; const VocabString Vocab_SentEnd = "</s>"; const VocabString Vocab_Pause = "-pau-"; typedef int (*<API key>)(VocabIndex, VocabIndex); typedef int (*<API key>)(const VocabIndex *, const VocabIndex *); class Vocab { friend class VocabIter; public: Vocab(VocabIndex start = 0, VocabIndex end = (Vocab_None-1)); virtual ~Vocab() {}; virtual VocabIndex addWord(VocabString name); virtual VocabIndex addWordAlias(VocabIndex word, VocabString name); virtual VocabString getWord(VocabIndex index); virtual VocabIndex getIndex(VocabString name, VocabIndex unkIndex = Vocab_None); virtual void remove(VocabString name); virtual void remove(VocabIndex index); virtual unsigned int numWords() const { return byName.numEntries(); }; virtual VocabIndex highIndex() const; /* * Special (pseudo-) vocabulary tokens */ virtual VocabIndex &unkIndex() { return _unkIndex; }; /* <unk> index */ virtual VocabIndex &ssIndex() { return _ssIndex; }; /* <s> index */ virtual VocabIndex &seIndex() { return _seIndex; }; /* </s> index */ virtual VocabIndex &pauseIndex() { return _pauseIndex; }; /* -pau- index */ virtual Boolean &unkIsWord() { return _unkIsWord; }; /* consider <unk> a regular word */ virtual Boolean &toLower() { return _toLower; }; /* map word strings to lowercase */ /* * Some Vocab tokens/indices are "pseudo words", i.e., they don't * get probabilities since they can only occur in contexts. */ virtual Boolean isNonEvent(VocabString word) /* pseudo-word? */ { return isNonEvent(getIndex(word)); }; virtual Boolean isNonEvent(VocabIndex word) const /* non-event? */ { return (!_unkIsWord && (word == _unkIndex)) || nonEventMap.find(word) != 0; }; virtual VocabIndex addNonEvent(VocabIndex word); virtual VocabIndex addNonEvent(VocabString name) { return addNonEvent(addWord(name)); }; virtual Boolean addNonEvents(Vocab &nonevents); virtual Boolean removeNonEvent(VocabIndex word); /* * Handling of meta-count tags: these are tags that represent a token * count total, or a type frequency count (count-of-count). * If metaTag == "__META__", the following tags acquire special meaning: * * __META__ a word count total * __META__1 count of singleton word types * __META__2 count of word types occurring twice * ... ... * __META__N count of word types occurring N times */ virtual VocabString &metaTag() { return _metaTag; }; /* meta-count tag */ Boolean isMetaTag(VocabIndex word) { return metaTagMap.find(word) != 0; }; unsigned typeOfMetaTag(VocabIndex word) { unsigned *type = metaTagMap.find(word); return type != 0 ? *type : (unsigned)-1; }; VocabIndex metaTagOfType(unsigned); /* * Utilities for handling Vocab sequences */ virtual unsigned int getWords(const VocabIndex *wids, VocabString *words, unsigned int max); virtual unsigned int addWords(const VocabString *words, VocabIndex *wids, unsigned int max); virtual unsigned int getIndices(const VocabString *words, VocabIndex *wids, unsigned int max, VocabIndex unkIndex = Vocab_None); virtual Boolean checkWords(const VocabString *words, VocabIndex *wids, unsigned int max); static unsigned int parseWords(char *line, VocabString *words, unsigned int max); static unsigned int length(const VocabIndex *words); static unsigned int length(const VocabString *words); static VocabIndex *copy(VocabIndex *to, const VocabIndex *from); static VocabString *copy(VocabString *to, const VocabString *from); static VocabIndex *reverse(VocabIndex *words); static Boolean contains(const VocabIndex *words, VocabIndex word); static VocabString *reverse(VocabString *words); static void write(File &file, const VocabString *words); /* * Comparison of Vocabs and their sequences */ static int compare(VocabIndex word1, VocabIndex word2); /* order on word indices induced by Vocab */ static int compare(VocabString word1, VocabString word2) { return strcmp(word1, word2); }; static int compare(const VocabIndex *word1, const VocabIndex *word2); /* order on word index sequences */ static int compare(const VocabString *word1, const VocabString *word2); <API key> compareIndex() const; <API key> compareIndices() const; Boolean ngramsInRange(VocabString *startRange, VocabString *endRange); /* * Miscellaneous */ virtual unsigned int read(File &file); virtual unsigned int readAliases(File &file); virtual void write(File &file, Boolean sorted = true) const; virtual void use() const { outputVocab = (Vocab *)this; }; // discard const virtual Boolean readIndexMap(File &file, Array<VocabIndex> &map, Boolean limitVocab = false); virtual void writeIndexMap(File &file); virtual void memStats(MemStats &stats) const; static Vocab *outputVocab; /* implicit parameter to operator<< */ static Vocab *compareVocab; /* implicit parameter to compare() */ protected: LHash<VocabString,VocabIndex> byName; Array<VocabString> byIndex; VocabIndex nextIndex; VocabIndex maxIndex; LHash<VocabIndex, unsigned> nonEventMap; /* set of non-event words */ LHash<VocabIndex, unsigned> metaTagMap; /* maps metatags to their type: 0 count total 1 single counts N count of count N */ // hidden data members (accessed through virtual functions VocabIndex _unkIndex; /* <unk> index */ VocabIndex _ssIndex; /* <s> index */ VocabIndex _seIndex; /* </s> index */ VocabIndex _pauseIndex; /* -pau- index */ Boolean _unkIsWord; /* consider <unk> a regular word */ Boolean _toLower; /* map word strings to lowercase */ VocabString _metaTag; /* meta-count tag */ }; ostream &operator<< (ostream &, const VocabString *words); ostream &operator<< (ostream &, const VocabIndex *words); class VocabIter { public: VocabIter(const Vocab &vocab, Boolean sorted = false); void init(); VocabString next() { VocabIndex index; return next(index); }; VocabString next(VocabIndex &index); private: LHashIter<VocabString,VocabIndex> myIter; }; /* * We sometimes use strings over VocabIndex as keys into maps. * Define the necessary support functions (see Map.h, LHash.cc, SArray.cc). */ static inline unsigned LHash_hashKey(const VocabIndex *key, unsigned maxBits) { unsigned i = 0; /* * The rationale here is similar to LHash_hashKey(unsigned), * except that we shift more to preserve more of the typical number of * bits in a VocabIndex. The value was optimized to encoding 3 words * at a time (trigrams). */ for (; *key != Vocab_None; key ++) { i += (i << 12) + *key; } return LHash_hashKey(i, maxBits); } static inline const VocabIndex * Map_copyKey(const VocabIndex *key) { VocabIndex *copy = new VocabIndex[Vocab::length(key) + 1]; assert(copy != 0); unsigned i; for (i = 0; key[i] != Vocab_None; i ++) { copy[i] = key[i]; } copy[i] = Vocab_None; return copy; } static inline void Map_freeKey(const VocabIndex *key) { delete [] (VocabIndex *)key; } static inline Boolean LHash_equalKey(const VocabIndex *key1, const VocabIndex *key2) { unsigned i; for (i = 0; key1[i] != Vocab_None && key2[i] != Vocab_None; i ++) { if (key1[i] != key2[i]) { return false; } } if (key1[i] == Vocab_None && key2[i] == Vocab_None) { return true; } else { return false; } } static inline int SArray_compareKey(const VocabIndex *key1, const VocabIndex *key2) { unsigned int i = 0; for (i = 0; ; i++) { if (key1[i] == Vocab_None) { if (key2[i] == Vocab_None) { return 0; } else { return -1; /* key1 is shorter */ } } else { if (key2[i] == Vocab_None) { return 1; /* key2 is shorted */ } else { int comp = SArray_compareKey(key1[i], key2[i]); if (comp != 0) { return comp; /* they differ at pos i */ } } } } /*NOTREACHED*/ } #endif /* _Vocab_h_ */
#!/bin/bash echo "Running Spark KMeans Low Dimension" . ./configDefaults.sh HOST=`hostname` ARGS="spark://$HOST:7077 $<API key> $<API key> $<API key> $ITERATIONS" echo "running KMeans with args $ARGS" $SPARK_HOME/bin/spark-submit --master spark://$HOST:7077 \ --class com.github.projectflink.spark.<API key> \ `ls "$TESTJOB_HOME"/spark-jobs/target/spark-jobs-*-All.jar` $ARGS
"use strict"; // Dependencies var protocols = require("protocols"); /** * isSsh * Checks if an input value is a ssh url or not. * * @name isSsh * @function * @param {String|Array} input The input url or an array of protocols. * @return {Boolean} `true` if the input is a ssh url, `false` otherwise. */ function isSsh(input) { if (Array.isArray(input)) { return input.indexOf("ssh") !== -1 || input.indexOf("rsync") !== -1; } if (typeof input !== "string") { return false; } var prots = protocols(input); input = input.substring(input.indexOf(": if (isSsh(prots)) { return true; } // TODO This probably could be improved :) return input.indexOf("@") < input.indexOf(":"); } module.exports = isSsh;
/* Universal Module Definition (UMD) */ (function (root, name, factory) { /* global define: false */ /* global module: false */ if (typeof define === "function" && typeof define.amd !== "undefined") /* AMD environment */ define(function () { return factory(root); }); else if (typeof module === "object" && typeof module.exports === "object") { /* CommonJS environment */ module.exports = factory(root); module.exports["default"] = module.exports; } else /* Browser environment */ root[name] = factory(root); }(this, "UUID", function (/* root */) { /* array to hex-string conversion */ var a2hs = function (bytes, begin, end, uppercase, str, pos) { var mkNum = function (num, uppercase) { var base16 = num.toString(16); if (base16.length < 2) base16 = "0" + base16; if (uppercase) base16 = base16.toUpperCase(); return base16; }; for (var i = begin; i <= end; i++) str[pos++] = mkNum(bytes[i], uppercase); return str; }; /* hex-string to array conversion */ var hs2a = function (str, begin, end, bytes, pos) { for (var i = begin; i <= end; i += 2) bytes[pos++] = parseInt(str.substr(i, 2), 16); }; var z85_encoder = ( "0123456789" + "<API key>" + "<API key>" + /* This library provides conversions between 8/16/32-bit character strings and 8/16/32-bit big/little-endian word arrays. */ /* string to array conversion */ var s2a = function (s, _options) { /* determine options */ var options = { ibits: 8, obits: 8, obigendian: true }; for (var opt in _options) if (typeof options[opt] !== "undefined") options[opt] = _options[opt]; /* convert string to array */ var a = []; var i = 0; var c, C; var ck = 0; var w; var wk = 0; var sl = s.length; for (;;) { /* fetch next octet from string */ if (ck === 0) C = s.charCodeAt(i++); c = (C >> (options.ibits - (ck + 8))) & 0xFF; ck = (ck + 8) % options.ibits; /* place next word into array */ if (options.obigendian) { if (wk === 0) w = (c << (options.obits - 8)); else w |= (c << ((options.obits - 8) - wk)); } else { if (wk === 0) w = c; else w |= (c << wk); } wk = (wk + 8) % options.obits; if (wk === 0) { a.push(w); if (i >= sl) break; } } return a; }; /* array to string conversion */ var a2s = function (a, _options) { /* determine options */ var options = { ibits: 32, ibigendian: true }; for (var opt in _options) if (typeof options[opt] !== "undefined") options[opt] = _options[opt]; /* convert array to string */ var s = ""; var imask = 0xFFFFFFFF; if (options.ibits < 32) imask = (1 << options.ibits) - 1; var al = a.length; for (var i = 0; i < al; i++) { /* fetch next word from array */ var w = a[i] & imask; /* place next octet into string */ for (var j = 0; j < options.ibits; j += 8) { if (options.ibigendian) s += String.fromCharCode((w >> ((options.ibits - 8) - j)) & 0xFF); else s += String.fromCharCode((w >> j) & 0xFF); } } return s; }; /* this is just a really minimal UI64 functionality, just sufficient enough for the UUID v1 generator and PCG PRNG! */ /* UI64 constants */ var UI64_DIGITS = 8; /* number of digits */ var UI64_DIGIT_BITS = 8; /* number of bits in a digit */ var UI64_DIGIT_BASE = 256; /* the numerical base of a digit */ /* convert between individual digits and the UI64 representation */ var ui64_d2i = function (d7, d6, d5, d4, d3, d2, d1, d0) { return [ d0, d1, d2, d3, d4, d5, d6, d7 ]; }; /* the zero represented as an UI64 */ var ui64_zero = function () { return ui64_d2i(0, 0, 0, 0, 0, 0, 0, 0); }; /* clone the UI64 */ var ui64_clone = function (x) { return x.slice(0); }; /* convert between number and UI64 representation */ var ui64_n2i = function (n) { var ui64 = ui64_zero(); for (var i = 0; i < UI64_DIGITS; i++) { ui64[i] = Math.floor(n % UI64_DIGIT_BASE); n /= UI64_DIGIT_BASE; } return ui64; }; /* convert between UI64 representation and number */ var ui64_i2n = function (x) { var n = 0; for (var i = UI64_DIGITS - 1; i >= 0; i n *= UI64_DIGIT_BASE; n += x[i]; } return Math.floor(n); }; /* add UI64 (y) to UI64 (x) and return overflow/carry as number */ var ui64_add = function (x, y) { var carry = 0; for (var i = 0; i < UI64_DIGITS; i++) { carry += x[i] + y[i]; x[i] = Math.floor(carry % UI64_DIGIT_BASE); carry = Math.floor(carry / UI64_DIGIT_BASE); } return carry; }; /* multiply number (n) to UI64 (x) and return overflow/carry as number */ var ui64_muln = function (x, n) { var carry = 0; for (var i = 0; i < UI64_DIGITS; i++) { carry += x[i] * n; x[i] = Math.floor(carry % UI64_DIGIT_BASE); carry = Math.floor(carry / UI64_DIGIT_BASE); } return carry; }; /* multiply UI64 (y) to UI64 (x) and return overflow/carry as UI64 */ var ui64_mul = function (x, y) { var i, j; /* clear temporary result buffer zx */ var zx = new Array(UI64_DIGITS + UI64_DIGITS); for (i = 0; i < (UI64_DIGITS + UI64_DIGITS); i++) zx[i] = 0; /* perform multiplication operation */ var carry; for (i = 0; i < UI64_DIGITS; i++) { /* calculate partial product and immediately add to zx */ carry = 0; for (j = 0; j < UI64_DIGITS; j++) { carry += (x[i] * y[j]) + zx[i + j]; zx[i + j] = (carry % UI64_DIGIT_BASE); carry /= UI64_DIGIT_BASE; } /* add carry to remaining digits in zx */ for ( ; j < UI64_DIGITS + UI64_DIGITS - i; j++) { carry += zx[i + j]; zx[i + j] = (carry % UI64_DIGIT_BASE); carry /= UI64_DIGIT_BASE; } } /* provide result by splitting zx into x and ov */ for (i = 0; i < UI64_DIGITS; i++) x[i] = zx[i]; return zx.slice(UI64_DIGITS, UI64_DIGITS); }; /* AND operation: UI64 (x) &= UI64 (y) */ var ui64_and = function (x, y) { for (var i = 0; i < UI64_DIGITS; i++) x[i] &= y[i]; return x; }; /* OR operation: UI64 (x) |= UI64 (y) */ var ui64_or = function (x, y) { for (var i = 0; i < UI64_DIGITS; i++) x[i] |= y[i]; return x; }; /* rotate right UI64 (x) by a "s" bits and return overflow/carry as number */ var ui64_rorn = function (x, s) { var ov = ui64_zero(); if ((s % UI64_DIGIT_BITS) !== 0) throw new Error("ui64_rorn: only bit rotations supported with a multiple of digit bits"); var k = Math.floor(s / UI64_DIGIT_BITS); for (var i = 0; i < k; i++) { for (var j = UI64_DIGITS - 1 - 1; j >= 0; j ov[j + 1] = ov[j]; ov[0] = x[0]; for (j = 0; j < UI64_DIGITS - 1; j++) x[j] = x[j + 1]; x[j] = 0; } return ui64_i2n(ov); }; /* rotate right UI64 (x) by a "s" bits and return overflow/carry as number */ var ui64_ror = function (x, s) { /* sanity check shifting */ if (s > (UI64_DIGITS * UI64_DIGIT_BITS)) throw new Error("ui64_ror: invalid number of bits to shift"); /* prepare temporary buffer zx */ var zx = new Array(UI64_DIGITS + UI64_DIGITS); var i; for (i = 0; i < UI64_DIGITS; i++) { zx[i + UI64_DIGITS] = x[i]; zx[i] = 0; } /* shift bits inside zx */ var k1 = Math.floor(s / UI64_DIGIT_BITS); var k2 = s % UI64_DIGIT_BITS; for (i = k1; i < UI64_DIGITS + UI64_DIGITS - 1; i++) { zx[i - k1] = ((zx[i] >>> k2) | (zx[i + 1] << (UI64_DIGIT_BITS - k2))) & ((1 << UI64_DIGIT_BITS) - 1); } zx[UI64_DIGITS + UI64_DIGITS - 1 - k1] = (zx[UI64_DIGITS + UI64_DIGITS - 1] >>> k2) & ((1 << UI64_DIGIT_BITS) - 1); for (i = UI64_DIGITS + UI64_DIGITS - 1 - k1 + 1; i < UI64_DIGITS + UI64_DIGITS; i++) zx[i] = 0; /* provide result by splitting zx into x and ov */ for (i = 0; i < UI64_DIGITS; i++) x[i] = zx[i + UI64_DIGITS]; return zx.slice(0, UI64_DIGITS); }; /* rotate left UI64 (x) by a "s" bits and return overflow/carry as UI64 */ var ui64_rol = function (x, s) { /* sanity check shifting */ if (s > (UI64_DIGITS * UI64_DIGIT_BITS)) throw new Error("ui64_rol: invalid number of bits to shift"); /* prepare temporary buffer zx */ var zx = new Array(UI64_DIGITS + UI64_DIGITS); var i; for (i = 0; i < UI64_DIGITS; i++) { zx[i + UI64_DIGITS] = 0; zx[i] = x[i]; } /* shift bits inside zx */ var k1 = Math.floor(s / UI64_DIGIT_BITS); var k2 = s % UI64_DIGIT_BITS; for (i = UI64_DIGITS - 1 - k1; i > 0; i zx[i + k1] = ((zx[i] << k2) | (zx[i - 1] >>> (UI64_DIGIT_BITS - k2))) & ((1 << UI64_DIGIT_BITS) - 1); } zx[0 + k1] = (zx[0] << k2) & ((1 << UI64_DIGIT_BITS) - 1); for (i = 0 + k1 - 1; i >= 0; i zx[i] = 0; /* provide result by splitting zx into x and ov */ for (i = 0; i < UI64_DIGITS; i++) x[i] = zx[i]; return zx.slice(UI64_DIGITS, UI64_DIGITS); }; /* XOR UI64 (y) onto UI64 (x) and return x */ var ui64_xor = function (x, y) { for (var i = 0; i < UI64_DIGITS; i++) x[i] ^= y[i]; return; }; /* this is just a really minimal UI32 functionality, just sufficient enough for the MD5 and SHA1 digests! */ /* safely add two integers (with wrapping at 2^32) */ var ui32_add = function (x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }; /* bitwise rotate 32-bit number to the left */ var ui32_rol = function (num, cnt) { return ( ((num << cnt ) & 0xFFFFFFFF) | ((num >>> (32 - cnt)) & 0xFFFFFFFF) ); }; /* calculate the SHA-1 of an array of big-endian words, and a bit length */ var sha1_core = function (x, len) { /* perform the appropriate triplet combination function for the current iteration */ function sha1_ft (t, b, c, d) { if (t < 20) return (b & c) | ((~b) & d); if (t < 40) return b ^ c ^ d; if (t < 60) return (b & c) | (b & d) | (c & d); return b ^ c ^ d; } /* determine the appropriate additive constant for the current iteration */ function sha1_kt (t) { return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514; } /* append padding */ x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; for (var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; var olde = e; for (var j = 0; j < 80; j++) { if (j < 16) w[j] = x[i + j]; else w[j] = ui32_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); var t = ui32_add( ui32_add(ui32_rol(a, 5), sha1_ft(j, b, c, d)), ui32_add(ui32_add(e, w[j]), sha1_kt(j)) ); e = d; d = c; c = ui32_rol(b, 30); b = a; a = t; } a = ui32_add(a, olda); b = ui32_add(b, oldb); c = ui32_add(c, oldc); d = ui32_add(d, oldd); e = ui32_add(e, olde); } return [ a, b, c, d, e ]; }; /* calculate the SHA-1 of an octet string */ var sha1 = function (s) { return a2s( sha1_core( s2a(s, { ibits: 8, obits: 32, obigendian: true }), s.length * 8), { ibits: 32, ibigendian: true }); }; /* calculate the MD5 of an array of little-endian words, and a bit length */ var md5_core = function (x, len) { /* basic operations the algorithm uses */ function md5_cmn (q, a, b, x, s, t) { return ui32_add(ui32_rol(ui32_add(ui32_add(a, q), ui32_add(x, t)), s), b); } function md5_ff (a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg (a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh (a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii (a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7, -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i+10], 9, 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i+14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4, -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4, 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6, -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = ui32_add(a, olda); b = ui32_add(b, oldb); c = ui32_add(c, oldc); d = ui32_add(d, oldd); } return [ a, b, c, d ]; }; /* calculate the MD5 of an octet string */ var md5 = function (s) { return a2s( md5_core( s2a(s, { ibits: 8, obits: 32, obigendian: false }), s.length * 8), { ibits: 32, ibigendian: false }); }; var PCG = function (seed) { /* pre-load some "magic" constants */ this.mul = ui64_d2i(0x58, 0x51, 0xf4, 0x2d, 0x4c, 0x95, 0x7f, 0x2d); this.inc = ui64_d2i(0x14, 0x05, 0x7b, 0x7e, 0xf7, 0x67, 0x81, 0x4f); this.mask = ui64_d2i(0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff); /* generate an initial internal state */ this.state = ui64_clone(this.inc); this.next(); ui64_and(this.state, this.mask); seed = ui64_n2i(seed !== undefined ? (seed >>> 0) : ((Math.random() * 0xffffffff) >>> 0)); ui64_or(this.state, seed); this.next(); }; PCG.prototype.next = function () { /* save current state */ var state = ui64_clone(this.state); /* advance internal state */ ui64_mul(this.state, this.mul); ui64_add(this.state, this.inc); /* calculate: (state ^ (state >> 18)) >> 27 */ var output = ui64_clone(state); ui64_ror(output, 18); ui64_xor(output, state); ui64_ror(output, 27); /* calculate: state >> 59 */ var rot = ui64_clone(state); ui64_ror(rot, 59); /* calculate: rotate32(xorshifted, rot) */ ui64_and(output, this.mask); var k = ui64_i2n(rot); var output2 = ui64_clone(output); ui64_rol(output2, 32 - k); ui64_ror(output, k); ui64_xor(output, output2); /* return pseudo-random number */ return ui64_i2n(output); }; var pcg = new PCG(); /* utility function: simple Pseudo Random Number Generator (PRNG) */ var prng = function (len, radix) { var bytes = []; for (var i = 0; i < len; i++) bytes[i] = (pcg.next() % radix); return bytes; }; /* internal state */ var time_last = 0; var time_seq = 0; /* the API constructor */ var UUID = function () { if (arguments.length === 1 && typeof arguments[0] === "string") this.parse.apply(this, arguments); else if (arguments.length >= 1 && typeof arguments[0] === "number") this.make.apply(this, arguments); else if (arguments.length >= 1) throw new Error("UUID: constructor: invalid arguments"); else for (var i = 0; i < 16; i++) this[i] = 0x00; }; /* inherit from a standard class which provides the best UUID representation in the particular environment */ /* global Uint8Array: false */ /* global Buffer: false */ if (typeof Uint8Array !== "undefined") UUID.prototype = new Uint8Array(16); else if (typeof Buffer !== "undefined") /* Node Buffer (server environments: Node.js, IO.js) */ UUID.prototype = new Buffer(16); else /* JavaScript (any environment) */ UUID.prototype = new Array(16); UUID.prototype.constructor = UUID; /* API method: generate a particular UUID */ UUID.prototype.make = function (version) { var i; var uuid = this; if (version === 1) { /* generate UUID version 1 (time and node based) */ /* determine current time and time sequence counter */ var date = new Date(); var time_now = date.getTime(); if (time_now !== time_last) time_seq = 0; else time_seq++; time_last = time_now; /* convert time to 100*nsec */ var t = ui64_n2i(time_now); ui64_muln(t, 1000 * 10); /* adjust for offset between UUID and Unix Epoch time */ ui64_add(t, ui64_d2i(0x01, 0xB2, 0x1D, 0xD2, 0x13, 0x81, 0x40, 0x00)); /* compensate for low resolution system clock by adding the time/tick sequence counter */ if (time_seq > 0) ui64_add(t, ui64_n2i(time_seq)); /* store the 60 LSB of the time in the UUID */ var ov; ov = ui64_rorn(t, 8); uuid[3] = (ov & 0xFF); ov = ui64_rorn(t, 8); uuid[2] = (ov & 0xFF); ov = ui64_rorn(t, 8); uuid[1] = (ov & 0xFF); ov = ui64_rorn(t, 8); uuid[0] = (ov & 0xFF); ov = ui64_rorn(t, 8); uuid[5] = (ov & 0xFF); ov = ui64_rorn(t, 8); uuid[4] = (ov & 0xFF); ov = ui64_rorn(t, 8); uuid[7] = (ov & 0xFF); ov = ui64_rorn(t, 8); uuid[6] = (ov & 0x0F); /* generate a random clock sequence */ var clock = prng(2, 255); uuid[8] = clock[0]; uuid[9] = clock[1]; /* generate a random local multicast node address */ var node = prng(6, 255); node[0] |= 0x01; node[0] |= 0x02; for (i = 0; i < 6; i++) uuid[10 + i] = node[i]; } else if (version === 4) { /* generate UUID version 4 (random data based) */ var data = prng(16, 255); for (i = 0; i < 16; i++) this[i] = data[i]; } else if (version === 3 || version === 5) { /* generate UUID version 3/5 (MD5/SHA-1 based) */ var input = ""; var nsUUID = ( typeof arguments[1] === "object" && arguments[1] instanceof UUID ? arguments[1] : new UUID().parse(arguments[1]) ); for (i = 0; i < 16; i++) input += String.fromCharCode(nsUUID[i]); input += arguments[2]; var s = version === 3 ? md5(input) : sha1(input); for (i = 0; i < 16; i++) uuid[i] = s.charCodeAt(i); } else throw new Error("UUID: make: invalid version"); /* brand with particular UUID version */ uuid[6] &= 0x0F; uuid[6] |= (version << 4); /* brand as UUID variant 2 (DCE 1.1) */ uuid[8] &= 0x3F; uuid[8] |= (0x02 << 6); return uuid; }; /* API method: format UUID into usual textual representation */ UUID.prototype.format = function (type) { var str, arr; if (type === "z85") str = z85_encode(this, 16); else if (type === "b16") { arr = Array(32); a2hs(this, 0, 15, true, arr, 0); str = arr.join(""); } else if (type === undefined || type === "std") { arr = new Array(36); a2hs(this, 0, 3, false, arr, 0); arr[ 8] = "-"; a2hs(this, 4, 5, false, arr, 9); arr[13] = "-"; a2hs(this, 6, 7, false, arr, 14); arr[18] = "-"; a2hs(this, 8, 9, false, arr, 19); arr[23] = "-"; a2hs(this, 10, 15, false, arr, 24); str = arr.join(""); } return str; }; /* API method: format UUID into usual textual representation */ UUID.prototype.toString = function (type) { return this.format(type); }; /* API method: parse UUID from usual textual representation */ UUID.prototype.parse = function (str, type) { if (typeof str !== "string") throw new Error("UUID: parse: invalid argument (type string expected)"); if (type === "z85") z85_decode(str, this); else if (type === "b16") hs2a(str, 0, 35, this, 0); else if (type === undefined || type === "std") { var map = { "nil": "<API key>", "ns:DNS": "<API key>", "ns:URL": "<API key>", "ns:OID": "<API key>", "ns:X500": "<API key>" }; if (map[str] !== undefined) str = map[str]; else if (!str.match(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/)) throw new Error("UUID: parse: invalid string representation " + "(expected \"<API key>\")"); hs2a(str, 0, 7, this, 0); hs2a(str, 9, 12, this, 4); hs2a(str, 14, 17, this, 6); hs2a(str, 19, 22, this, 8); hs2a(str, 24, 35, this, 10); } return this; }; /* API method: export UUID into standard array of numbers */ UUID.prototype.export = function () { var arr = Array(16); for (var i = 0; i < 16; i++) arr[i] = this[i]; return arr; }; /* API method: import UUID from standard array of numbers */ UUID.prototype.import = function (arr) { if (!(typeof arr === "object" && arr instanceof Array)) throw new Error("UUID: import: invalid argument (type Array expected)"); if (arr.length !== 16) throw new Error("UUID: import: invalid argument (Array of length 16 expected)"); for (var i = 0; i < 16; i++) { if (typeof arr[i] !== "number") throw new Error("UUID: import: invalid array element " (type Number expected)"); if (!(isFinite(arr[i]) && Math.floor(arr[i]) === arr[i])) throw new Error("UUID: import: invalid array element " (Number with integer value expected)"); if (!(arr[i] >= 0 && arr[i] <= 255)) throw new Error("UUID: import: invalid array element " (Number with integer value in range 0...255 expected)"); this[i] = arr[i]; } return this; }; /* API method: compare UUID against another one */ UUID.prototype.compare = function (other) { if (typeof other !== "object") throw new Error("UUID: compare: invalid argument (type UUID expected)"); if (!(other instanceof UUID)) throw new Error("UUID: compare: invalid argument (type UUID expected)"); for (var i = 0; i < 16; i++) { if (this[i] < other[i]) return -1; else if (this[i] > other[i]) return +1; } return 0; }; /* API method: hash UUID by XOR-folding it k times */ UUID.prototype.fold = function (k) { if (typeof k === "undefined") throw new Error("UUID: fold: invalid argument (number of fold operations expected)"); if (k < 1 || k > 4) throw new Error("UUID: fold: invalid argument (1-4 fold operations expected)"); var n = 16 / Math.pow(2, k); var hash = new Array(n); for (var i = 0; i < n; i++) { var h = 0; for (var j = 0; i + j < 16; j += n) h ^= this[i + j]; hash[i] = h; } return hash; }; UUID.PCG = PCG; /* export API */ return UUID; }));
<li id="listItemHeader" class="dropdown-header"> <span id="caption">Zoom</span> </li>
package helpers import ( "errors" "fmt" "strings" ginkgoconfig "github.com/onsi/ginkgo/config" ) // UserDefinedScope in case that the test scope is defined by the user instead // of the focus string. var UserDefinedScope string // GetScope returns the scope for the currently running test. func GetScope() (string, error) { if UserDefinedScope != "" { return UserDefinedScope, nil } focusString := strings.TrimSpace(strings.ToLower(ginkgoconfig.GinkgoConfig.FocusString)) switch { case strings.HasPrefix(focusString, "run"): return Runtime, nil case strings.HasPrefix(focusString, K8s): return K8s, nil case strings.Contains(focusString, "nightly"): // Nightly tests run in a Kubernetes environment. return K8s, nil default: return "", errors.New("Scope cannot be set") } } // GetScopeWithVersion returns the scope of the running test. If the scope is // k8s, then it returns k8s scope along with the version of k8s that is running. func GetScopeWithVersion() string { // No errors check here, test never reach here because test should fail // before. result, _ := GetScope() if result != K8s { return result } return fmt.Sprintf("%s-%s", result, GetCurrentK8SEnv()) }
#include "Base.h" #include "<API key>.h" #include "Node.h" namespace gameplay { void <API key>::setLimits(float minAngle, float maxAngle, float bounciness) { // Use the defaults for softness (0.9) and biasFactor (0.3). GP_ASSERT(_constraint); ((btHingeConstraint*)_constraint)->setLimit(minAngle, maxAngle, 0.9f, 0.3f, bounciness); } <API key>::<API key>(PhysicsRigidBody* a, const Quaternion& rotationOffsetA, const Vector3& translationOffsetA, PhysicsRigidBody* b, const Quaternion& rotationOffsetB, const Vector3& translationOffsetB) : PhysicsConstraint(a, b) { GP_ASSERT(a && a->_body && a->getNode()); // Take scale into account for the first node's translation offset. Vector3 sA; a->getNode()->getWorldMatrix().getScale(&sA); Vector3 tA(translationOffsetA.x * sA.x, translationOffsetA.y * sA.y, translationOffsetA.z * sA.z); if (b) { GP_ASSERT(b->_body && b->getNode()); // Take scale into account for the second node's translation offset. Vector3 sB; b->getNode()->getWorldMatrix().getScale(&sB); Vector3 tB(translationOffsetB.x * sB.x, translationOffsetB.y * sB.y, translationOffsetB.z * sB.z); btTransform frameInA(BQ(rotationOffsetA), BV(tA)); btTransform frameInB(BQ(rotationOffsetB), BV(tB)); _constraint = bullet_new<btHingeConstraint>(*a->_body, *b->_body, frameInA, frameInB); } else { btTransform frameInA(BQ(rotationOffsetA), BV(tA)); _constraint = bullet_new<btHingeConstraint>(*a->_body, frameInA); } } <API key>::~<API key>() { // Unused } }
ESLint-plugin-React ================ [![Maintenance Status][status-image]][status-url] [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][deps-image]][deps-url] [![Coverage Status][coverage-image]][coverage-url] [![Code Climate][climate-image]][climate-url] [![Tidelift][tidelift-image]][tidelift-url] React specific linting rules for ESLint # Installation Install [ESLint](https: sh $ npm install eslint --save-dev If you installed `ESLint` globally, you have to install React plugin globally too. Otherwise, install it locally. sh $ npm install eslint-plugin-react --save-dev # Configuration Use [our preset](#recommended) to get reasonable defaults: json "extends": [ "eslint:recommended", "plugin:react/recommended" ] You should also specify settings that will be shared across all the plugin rules. ([More about eslint shared settings](https://eslint.org/docs/user-guide/configuring#<API key>)) json5 { "settings": { "react": { "createClass": "createReactClass", // Regex for Component Factory to use, // default to "createReactClass" "pragma": "React", // Pragma to use, default to "React" "version": "detect", // React version. "detect" automatically picks the version you have installed. // You can also use `16.0`, `16.3`, etc, if you want to override the detected value. // default to latest and warns if missing // It will default to "detect" in the future "flowVersion": "0.53" // Flow version }, "<API key>": [ // The names of any function used to wrap propTypes, e.g. `forbidExtraProps`. If this isn't set, any propTypes wrapped in a function will be skipped. "forbidExtraProps", {"property": "freeze", "object": "Object"}, {"property": "myFavoriteWrapper"} ], "linkComponents": [ // Components used as alternatives to <a> for linking, eg. <Link to={ url } /> "Hyperlink", {"name": "Link", "linkAttribute": "to"} ] } } If you do not use a preset you will need to specify individual rules and add extra configuration. Add "react" to the plugins section. json { "plugins": [ "react" ] } Enable JSX support. With ESLint 2+ json { "parserOptions": { "ecmaFeatures": { "jsx": true } } } Enable the rules that you would like to use. json "rules": { "react/jsx-uses-react": "error", "react/jsx-uses-vars": "error", } # List of supported rules <!-- <API key>:START (BASIC_RULES) --> * [react/boolean-prop-naming](docs/rules/boolean-prop-naming.md): Enforces consistent naming for boolean props * [react/button-has-type](docs/rules/button-has-type.md): Forbid "button" element without an explicit "type" attribute * [react/<API key>](docs/rules/<API key>.md): Enforce all defaultProps are defined and not "required" in propTypes. * [react/<API key>](docs/rules/<API key>.md): Enforce consistent usage of destructuring assignment of props, state, and context * [react/display-name](docs/rules/display-name.md): Prevent missing displayName in a React component definition * [react/<API key>](docs/rules/<API key>.md): Forbid certain props on components * [react/forbid-dom-props](docs/rules/forbid-dom-props.md): Forbid certain props on DOM Nodes * [react/forbid-elements](docs/rules/forbid-elements.md): Forbid certain elements * [react/<API key>](docs/rules/<API key>.md): Forbid using another component's propTypes * [react/forbid-prop-types](docs/rules/forbid-prop-types.md): Forbid certain propTypes * [react/<API key>](docs/rules/<API key>.md): Standardize the way function component get defined (fixable) * [react/<API key>](docs/rules/<API key>.md): Reports when this.state is accessed within setState * [react/<API key>](docs/rules/<API key>.md): Prevent adjacent inline elements not separated by whitespace. * [react/no-array-index-key](docs/rules/no-array-index-key.md): Prevent usage of Array index in keys * [react/no-children-prop](docs/rules/no-children-prop.md): Prevent passing of children as props. * [react/no-danger](docs/rules/no-danger.md): Prevent usage of dangerous JSX props * [react/<API key>](docs/rules/<API key>.md): Report when a DOM element is using both children and <API key> * [react/no-deprecated](docs/rules/no-deprecated.md): Prevent usage of deprecated methods * [react/<API key>](docs/rules/<API key>.md): Prevent usage of setState in componentDidMount * [react/<API key>](docs/rules/<API key>.md): Prevent usage of setState in componentDidUpdate * [react/<API key>](docs/rules/<API key>.md): Prevent direct mutation of this.state * [react/no-find-dom-node](docs/rules/no-find-dom-node.md): Prevent usage of findDOMNode * [react/no-is-mounted](docs/rules/no-is-mounted.md): Prevent usage of isMounted * [react/no-multi-comp](docs/rules/no-multi-comp.md): Prevent multiple component definition per file * [react/<API key>](docs/rules/<API key>.md): Flag <API key> when extending PureComponent * [react/<API key>](docs/rules/<API key>.md): Prevent usage of the return value of React.render * [react/no-set-state](docs/rules/no-set-state.md): Prevent usage of setState * [react/no-string-refs](docs/rules/no-string-refs.md): Prevent string definitions for references and prevent referencing this.refs * [react/no-this-in-sfc](docs/rules/no-this-in-sfc.md): Report "this" being used in stateless components * [react/no-typos](docs/rules/no-typos.md): Prevent common typos * [react/<API key>](docs/rules/<API key>.md): Detect unescaped HTML entities, which might represent malformed tags * [react/no-unknown-property](docs/rules/no-unknown-property.md): Prevent usage of unknown DOM property (fixable) * [react/no-unsafe](docs/rules/no-unsafe.md): Prevent usage of unsafe lifecycle methods * [react/<API key>](docs/rules/<API key>.md): Prevent definitions of unused prop types * [react/no-unused-state](docs/rules/no-unused-state.md): Prevent definition of unused state fields * [react/<API key>](docs/rules/<API key>.md): Prevent usage of setState in componentWillUpdate * [react/prefer-es6-class](docs/rules/prefer-es6-class.md): Enforce ES5 or ES6 class for React Components * [react/<API key>](docs/rules/<API key>.md): Require read-only props. (fixable) * [react/<API key>](docs/rules/<API key>.md): Enforce stateless components to be written as a pure function * [react/prop-types](docs/rules/prop-types.md): Prevent missing props validation in a React component definition * [react/react-in-jsx-scope](docs/rules/react-in-jsx-scope.md): Prevent missing React when using JSX * [react/<API key>](docs/rules/<API key>.md): Enforce a defaultProps definition for every prop that is not a required prop. * [react/<API key>](docs/rules/<API key>.md): Enforce React components to have a <API key> method * [react/<API key>](docs/rules/<API key>.md): Enforce ES5 or ES6 class for returning value in render function * [react/self-closing-comp](docs/rules/self-closing-comp.md): Prevent extra closing tags for components without children (fixable) * [react/sort-comp](docs/rules/sort-comp.md): Enforce component methods order * [react/sort-prop-types](docs/rules/sort-prop-types.md): Enforce propTypes declarations alphabetical sorting * [react/<API key>](docs/rules/<API key>.md): State initialization in an ES6 class component should be in a constructor * [react/<API key>](docs/rules/<API key>.md): Defines where React component static properties should be positioned. * [react/style-prop-object](docs/rules/style-prop-object.md): Enforce style prop value is an object * [react/<API key>](docs/rules/<API key>.md): Prevent passing of children to void DOM elements (e.g. `<br />`). <!-- <API key>:END --> ## JSX-specific rules <!-- <API key>:START (JSX_RULES) --> * [react/jsx-boolean-value](docs/rules/jsx-boolean-value.md): Enforce boolean attributes notation in JSX (fixable) * [react/<API key>](docs/rules/<API key>.md): Ensures inline tags are not rendered without spaces between them * [react/<API key>](docs/rules/<API key>.md): Validate closing bracket location in JSX (fixable) * [react/<API key>](docs/rules/<API key>.md): Validate closing tag location for multiline JSX (fixable) * [react/<API key>](docs/rules/<API key>.md): Disallow unnecessary JSX expressions when literals alone are sufficient or enfore JSX expressions on literals in JSX children or attributes (fixable) * [react/jsx-curly-newline](docs/rules/jsx-curly-newline.md): Enforce consistent line breaks inside jsx curly (fixable) * [react/jsx-curly-spacing](docs/rules/jsx-curly-spacing.md): Enforce or disallow spaces inside of curly braces in JSX attributes (fixable) * [react/jsx-equals-spacing](docs/rules/jsx-equals-spacing.md): Disallow or enforce spaces around equal signs in JSX attributes (fixable) * [react/<API key>](docs/rules/<API key>.md): Restrict file extensions that may contain JSX * [react/<API key>](docs/rules/<API key>.md): Ensure proper position of the first property in JSX (fixable) * [react/jsx-fragments](docs/rules/jsx-fragments.md): Enforce shorthand or standard form for React fragments (fixable) * [react/jsx-handler-names](docs/rules/jsx-handler-names.md): Enforce event handler naming conventions in JSX * [react/jsx-indent](docs/rules/jsx-indent.md): Validate JSX indentation (fixable) * [react/jsx-indent-props](docs/rules/jsx-indent-props.md): Validate props indentation in JSX (fixable) * [react/jsx-key](docs/rules/jsx-key.md): Report missing `key` props in iterators/collection literals * [react/jsx-max-depth](docs/rules/jsx-max-depth.md): Validate JSX maximum depth * [react/<API key>](docs/rules/<API key>.md): Limit maximum of props on a single line in JSX (fixable) * [react/jsx-no-bind](docs/rules/jsx-no-bind.md): Prevents usage of Function.prototype.bind and arrow functions in React component props * [react/<API key>](docs/rules/<API key>.md): Comments inside children section of tag should be placed inside braces * [react/<API key>](docs/rules/<API key>.md): Enforce no duplicate props * [react/jsx-no-literals](docs/rules/jsx-no-literals.md): Prevent using string literals in React component definition * [react/jsx-no-script-url](docs/rules/jsx-no-script-url.md): Forbid `javascript:` URLs * [react/jsx-no-target-blank](docs/rules/jsx-no-target-blank.md): Forbid target="_blank" attribute without rel="noopener noreferrer" * [react/jsx-no-undef](docs/rules/jsx-no-undef.md): Disallow undeclared variables in JSX * [react/<API key>](docs/rules/<API key>.md): Disallow unnecessary fragments (fixable) * [react/<API key>](docs/rules/<API key>.md): Limit to one expression per line in JSX (fixable) * [react/jsx-pascal-case](docs/rules/jsx-pascal-case.md): Enforce PascalCase for user-defined JSX components * [react/<API key>](docs/rules/<API key>.md): Disallow multiple spaces between inline JSX props (fixable) * [react/<API key>](docs/rules/<API key>.md): Prevent JSX prop spreading * [react/<API key>](docs/rules/<API key>.md): Enforce default props alphabetical sorting * [react/jsx-sort-props](docs/rules/jsx-sort-props.md): Enforce props alphabetical sorting (fixable) * [react/<API key>](docs/rules/<API key>.md): Validate spacing before closing bracket in JSX (fixable) * [react/jsx-tag-spacing](docs/rules/jsx-tag-spacing.md): Validate whitespace in and around the JSX opening and closing brackets (fixable) * [react/jsx-uses-react](docs/rules/jsx-uses-react.md): Prevent React to be marked as unused * [react/jsx-uses-vars](docs/rules/jsx-uses-vars.md): Prevent variables used in JSX to be marked as unused * [react/jsx-wrap-multilines](docs/rules/jsx-wrap-multilines.md): Prevent missing parentheses around multilines JSX (fixable) <!-- <API key>:END --> ## Other useful plugins - JSX accessibility: [<API key>](https://github.com/evcohen/<API key>) - React Native: [<API key>](https://github.com/Intellicode/<API key>) # Shareable configurations ## Recommended This plugin exports a `recommended` configuration that enforces React good practices. To enable this configuration use the `extends` property in your `.eslintrc` config file: json { "extends": ["eslint:recommended", "plugin:react/recommended"] } See [ESLint documentation](http://eslint.org/docs/user-guide/configuring#<API key>) for more information about extending configuration files. The rules enabled in this configuration are: * [react/display-name](docs/rules/display-name.md) * [react/jsx-key](docs/rules/jsx-key.md) * [react/<API key>](docs/rules/<API key>.md) * [react/<API key>](docs/rules/<API key>.md) * [react/jsx-no-target-blank](docs/rules/jsx-no-target-blank.md) * [react/jsx-no-undef](docs/rules/jsx-no-undef.md) * [react/jsx-uses-react](docs/rules/jsx-uses-react.md) * [react/jsx-uses-vars](docs/rules/jsx-uses-vars.md) * [react/no-children-prop](docs/rules/no-children-prop.md) * [react/<API key>](docs/rules/<API key>.md) * [react/no-deprecated](docs/rules/no-deprecated.md) * [react/<API key>](docs/rules/<API key>.md) * [react/no-find-dom-node](docs/rules/no-find-dom-node.md) * [react/no-is-mounted](docs/rules/no-is-mounted.md) * [react/<API key>](docs/rules/<API key>.md) * [react/no-string-refs](docs/rules/no-string-refs.md) * [react/<API key>](docs/rules/<API key>.md) * [react/no-unknown-property](docs/rules/no-unknown-property.md) * [react/prop-types](docs/rules/prop-types.md) * [react/react-in-jsx-scope](docs/rules/react-in-jsx-scope.md) * [react/<API key>](docs/rules/<API key>.md) ## All This plugin also exports an `all` configuration that includes every available rule. This pairs well with the `eslint:all` rule. json { "plugins": [ "react" ], "extends": ["eslint:all", "plugin:react/all"] } **Note**: These configurations will import `eslint-plugin-react` and enable JSX in [parser options](http://eslint.org/docs/user-guide/configuring#<API key>). ESLint-plugin-React is licensed under the [MIT License](http: [npm-url]: https://npmjs.org/package/eslint-plugin-react [npm-image]: https://img.shields.io/npm/v/eslint-plugin-react.svg [travis-url]: https://travis-ci.org/yannickcr/eslint-plugin-react [travis-image]: https://img.shields.io/travis/yannickcr/eslint-plugin-react/master.svg [deps-url]: https://david-dm.org/yannickcr/eslint-plugin-react [deps-image]: https://img.shields.io/david/dev/yannickcr/eslint-plugin-react.svg [coverage-url]: https://coveralls.io/r/yannickcr/eslint-plugin-react?branch=master [coverage-image]: https://img.shields.io/coveralls/yannickcr/eslint-plugin-react/master.svg [climate-url]: https://codeclimate.com/github/yannickcr/eslint-plugin-react [climate-image]: https://img.shields.io/codeclimate/maintainability/yannickcr/eslint-plugin-react.svg [status-url]: https://github.com/yannickcr/eslint-plugin-react/pulse [status-image]: https://img.shields.io/github/last-commit/yannickcr/eslint-plugin-react.svg [tidelift-url]: https://tidelift.com/subscription/pkg/<API key>?utm_source=<API key>&utm_medium=referral&utm_campaign=readme [tidelift-image]: https://tidelift.com/badges/github/yannickcr/eslint-plugin-react?style=flat
{% extends "_donut.html" %} {% block pageHead %} {{ super() }} {% endblock %} {% block header %} {{ super() }} {% endblock %} {% block main %} <div class="introduction"> <h1 class="introduction--h1">{{content.home.title}}</h1> </div> <div class="contentcards"> <ul class="contentcards--ul"> {% for type in content.types %} <li class="contentcards--li"><a href="/{{content.base}}/{{type.id}}" class="base--link">{{type.name}}</a></li> {% endfor %} </ul> </div> {% endblock %} {% block footer %} {{ super() }} {% endblock %}
#!/bin/bash #Aqueduct - Compliance Remediation Content # Vincent C. Passaro (vincent.passaro@gmail.com) # Shannon Mitchell (shannon.mitchell@<API key>.com) #This program is free software; you can redistribute it and/or #as published by the Free Software Foundation; either version 2 #This program is distributed in the hope that it will be useful, #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, #Boston, MA 02110-1301, USA. # By Vincent C. Passaro # # Fotis Networks LLC # # Vincent[.]Passaro[@]fotisnetworks[.]com # # <API key> # | Version | Change Information | Author | Date | # | 1.0 | Initial Script | Vincent C. Passaro | 1-Aug-2012 | # | | Creation | | | # Group ID (Vulid): V-986 # Group Title: GEN003320 # Rule ID: SV-37517r1_rule # Severity: medium # Rule Version (STIG-ID): GEN003320 # Rule Title: Default system accounts (with the exception of root) must # not be listed in the at.allow file or must be included in the at.deny # file if the at.allow file does not exist. # Vulnerability Discussion: Default accounts, such as bin, sys, adm, # uucp, daemon, and others, should never have access to the "at" facility. # This would create a possible vulnerability open to intruders or malicious # users. # Responsibility: System Administrator # IAControls: ECPA-1 # Check Content: # # more /etc/at.allow # If default accounts (such as bin, sys, adm, and others) are listed in the # at.allow file, this is a finding. # Fix Text: # Remove the default accounts (such as bin, sys, adm, and others, # traditionally UID less than 500) from the at.allow file. # Global Variables PDI=GEN003320 # Start-Lockdown for CURUSER in `awk -F ':' '!/^root/{if($3 < 500) print $1}' /etc/passwd` do # If the at.allow exists remove the user if there if [ -e "/etc/at.allow" ] then grep "$CURUSER" /etc/at.allow > /dev/null if [ $? -eq 0 ] then sed -i -e "/${CURUSER}/d" /etc/at.allow fi fi done # Remove emtpy lines if [ -e "/etc/at.allow" ] then sed -i -e '/^\s*$/d' /etc/at.allow fi
package org.elasticsearch.indices; import org.apache.lucene.util.automaton.Automaton; import org.apache.lucene.util.automaton.<API key>; import org.apache.lucene.util.automaton.Operations; import org.apache.lucene.util.automaton.RegExp; import org.elasticsearch.Version; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.threadpool.ThreadPool; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; /** * A system index descriptor describes one or more system indices. It can match a number of indices using * a pattern. For system indices that are managed externally to Elasticsearch, this is enough. For system * indices that are managed internally to Elasticsearch, a descriptor can also include information for * creating the system index, upgrading its mappings, and creating an alias. */ public class <API key> implements IndexPatternMatcher, Comparable<<API key>> { /** A pattern, either with a wildcard or simple regex. Indices that match one of these patterns are considered system indices. */ private final String indexPattern; /** * For internally-managed indices, specifies the name of the concrete index to create and update. This is required * since the {@link #indexPattern} can match many indices. */ private final String primaryIndex; /** A description of the index or indices */ private final String description; /** Used to determine whether an index name matches the {@link #indexPattern} */ private final <API key> <API key>; /** For internally-managed indices, contains the index mappings JSON */ private final String mappings; /** For internally-managed indices, contains the index settings */ private final Settings settings; /** For internally-managed indices, an optional alias to create */ private final String aliasName; /** For internally-managed indices, an optional {@link IndexMetadata#<API key>} value to expect */ private final int indexFormat; /** * For internally-managed indices, specifies a key name under <code>_meta</code> in the index mappings * that contains the index's mappings' version. */ private final String versionMetaKey; /** For internally-managed indices, specifies the origin to use when creating or updating the index */ private final String origin; /** The minimum cluster node version required for this descriptor */ private final Version minimumNodeVersion; /** Mapping version from the descriptor */ private final Version mappingVersion; /** Whether there are dynamic fields in this descriptor's mappings */ private final boolean hasDynamicMappings; /** The {@link Type} of system index this descriptor represents */ private final Type type; /** A list of allowed product origins that may access an external system index */ private final List<String> <API key>; /** * A list of prior system index descriptors that can be used when one or more data/master nodes is on a version lower than the * minimum supported version for this descriptor */ private final List<<API key>> <API key>; private final boolean isNetNew; /** * The thread pools that actions will use to operate on this descriptor's system indices */ private final ExecutorNames executorNames; /** * Creates a descriptor for system indices matching the supplied pattern. These indices will not be managed * by Elasticsearch internally. * @param indexPattern The pattern of index names that this descriptor will be used for. Must start with a '.' character. * @param description The name of the plugin responsible for this system index. */ public <API key>(String indexPattern, String description) { this(indexPattern, null, description, null, null, null, 0, null, null, Version.CURRENT.<API key>(), Type.INTERNAL_UNMANAGED, List.of(), List.of(), null, false); } /** * Creates a descriptor for system indices matching the supplied pattern. These indices will not be managed * by Elasticsearch internally. * @param indexPattern The pattern of index names that this descriptor will be used for. Must start with a '.' character. * @param description The name of the plugin responsible for this system index. * @param type The {@link Type} of system index * @param <API key> A list of allowed origin values that should be allowed access in the case of external system * indices */ public <API key>(String indexPattern, String description, Type type, List<String> <API key>) { this(indexPattern, null, description, null, null, null, 0, null, null, Version.CURRENT.<API key>(), type, <API key>, List.of(), null, false); } /** * Creates a descriptor for system indices matching the supplied pattern. These indices will be managed * by Elasticsearch internally if mappings or settings are provided. * * @param indexPattern The pattern of index names that this descriptor will be used for. Must start with a '.' character. * @param primaryIndex The primary index name of this descriptor. Used when creating the system index for the first time. * @param description The name of the plugin responsible for this system index. * @param mappings The mappings to apply to this index when auto-creating, if appropriate * @param settings The settings to apply to this index when auto-creating, if appropriate * @param aliasName An alias for the index, or null * @param indexFormat A value for the `index.format` setting. Pass 0 or higher. * @param versionMetaKey a mapping key under <code>_meta</code> where a version can be found, which indicates the * Elasticsearch version when the index was created. * @param origin the client origin to use when creating this index. * @param minimumNodeVersion the minimum cluster node version required for this descriptor * @param type The {@link Type} of system index * @param <API key> A list of allowed origin values that should be allowed access in the case of external system * indices * @param <API key> A list of system index descriptors that describe the same index in a way that is compatible with * older versions of Elasticsearch */ <API key>( String indexPattern, String primaryIndex, String description, String mappings, Settings settings, String aliasName, int indexFormat, String versionMetaKey, String origin, Version minimumNodeVersion, Type type, List<String> <API key>, List<<API key>> <API key>, ExecutorNames executorNames, boolean isNetNew ) { Objects.requireNonNull(indexPattern, "system index pattern must not be null"); if (indexPattern.length() < 2) { throw new <API key>( "system index pattern provided as [" + indexPattern + "] but must at least 2 characters in length" ); } if (indexPattern.charAt(0) != '.') { throw new <API key>( "system index pattern provided as [" + indexPattern + "] but must start with the character [.]" ); } if (indexPattern.charAt(1) == '*') { throw new <API key>( "system index pattern provided as [" + indexPattern + "] but must not start with the character sequence [.*] to prevent conflicts" ); } if (primaryIndex != null) { if (primaryIndex.charAt(0) != '.') { throw new <API key>( "system primary index provided as [" + primaryIndex + "] but must start with the character [.]" ); } if (primaryIndex.matches("^\\.[\\w-]+$") == false) { throw new <API key>( "system primary index provided as [" + primaryIndex + "] but cannot contain special characters or patterns" ); } } if (indexFormat < 0) { throw new <API key>("Index format cannot be negative"); } Strings.requireNonEmpty(indexPattern, "indexPattern must be supplied"); Objects.requireNonNull(type, "type must not be null"); if (type.isManaged()) { Objects.requireNonNull(settings, "Must supply settings for a managed system index"); Strings.requireNonEmpty(mappings, "Must supply mappings for a managed system index"); Strings.requireNonEmpty(primaryIndex, "Must supply primaryIndex for a managed system index"); Strings.requireNonEmpty(versionMetaKey, "Must supply versionMetaKey for a managed system index"); Strings.requireNonEmpty(origin, "Must supply origin for a managed system index"); this.mappingVersion = <API key>(mappings, versionMetaKey);; } else { this.mappingVersion = null; } Objects.requireNonNull(<API key>, "<API key> must not be null"); if (type.isInternal() && <API key>.isEmpty() == false) { throw new <API key>("Allowed origins are not valid for internal system indices"); } else if (type.isExternal() && <API key>.isEmpty()) { throw new <API key>("External system indices without allowed products is not a valid combination"); } Objects.requireNonNull(minimumNodeVersion, "minimumNodeVersion must be provided!"); Objects.requireNonNull(<API key>, "<API key> must not be null"); if (<API key>.isEmpty() == false) { // the rules for prior system index descriptors // 1. No values with the same minimum node version // 2. All prior system index descriptors must have a minimumNodeVersion before this one // 3. Prior system index descriptors may not have other prior system index descriptors // to avoid multiple branches that need followed // 4. Must have same indexPattern, primaryIndex, and alias Set<Version> versions = new HashSet<>(<API key>.size() + 1); versions.add(minimumNodeVersion); for (<API key> prior : <API key>) { if (versions.add(prior.minimumNodeVersion) == false) { throw new <API key>(prior + " has the same minimum node version as another descriptor"); } if (prior.minimumNodeVersion.after(minimumNodeVersion)) { throw new <API key>(prior + " has minimum node version [" + prior.minimumNodeVersion + "] which is after [" + minimumNodeVersion + "]"); } if (prior.<API key>.isEmpty() == false) { throw new <API key>(prior + " has its own prior descriptors but only a depth of 1 is allowed"); } if (prior.indexPattern.equals(indexPattern) == false) { throw new <API key>("index pattern must be the same"); } if (prior.primaryIndex.equals(primaryIndex) == false) { throw new <API key>("primary index must be the same"); } if (prior.aliasName.equals(aliasName) == false) { throw new <API key>("alias name must be the same"); } } } if (Objects.nonNull(executorNames)) { if (ThreadPool.THREAD_POOL_TYPES.containsKey(executorNames.threadPoolForGet()) == false) { throw new <API key>(executorNames.threadPoolForGet() + " is not a valid thread pool"); } if (ThreadPool.THREAD_POOL_TYPES.containsKey(executorNames.threadPoolForSearch()) == false) { throw new <API key>(executorNames.threadPoolForGet() + " is not a valid thread pool"); } if (ThreadPool.THREAD_POOL_TYPES.containsKey(executorNames.threadPoolForWrite()) == false) { throw new <API key>(executorNames.threadPoolForGet() + " is not a valid thread pool"); } } this.indexPattern = indexPattern; this.primaryIndex = primaryIndex; this.aliasName = aliasName; final Automaton automaton = buildAutomaton(indexPattern, aliasName); this.<API key> = new <API key>(automaton); if (primaryIndex != null && <API key>.run(primaryIndex) == false) { throw new <API key>("primary index does not match the index pattern!"); } this.description = description; this.mappings = mappings; if (Objects.nonNull(settings) && settings.getAsBoolean(IndexMetadata.<API key>, false)) { throw new <API key>("System indices cannot have " + IndexMetadata.<API key> + " set to true."); } this.settings = settings; this.indexFormat = indexFormat; this.versionMetaKey = versionMetaKey; this.origin = origin; this.minimumNodeVersion = minimumNodeVersion; this.type = type; this.<API key> = <API key>; this.hasDynamicMappings = this.mappings != null && findDynamicMapping(XContentHelper.convertToMap(JsonXContent.jsonXContent, mappings, false)); final List<<API key>> <API key>; if (<API key>.isEmpty() || <API key>.size() == 1) { <API key> = List.copyOf(<API key>); } else { List<<API key>> copy = new ArrayList<>(<API key>); Collections.sort(copy); <API key> = List.copyOf(copy); } this.<API key> = <API key>; this.executorNames = Objects.nonNull(executorNames) ? executorNames : ExecutorNames.<API key>; this.isNetNew = isNetNew; } /** * @return The pattern of index names that this descriptor will be used for. */ @Override public String getIndexPattern() { return indexPattern; } /** * @return The concrete name of an index being managed internally to Elasticsearch. Will be {@code null} * for indices managed externally to Elasticsearch. */ public String getPrimaryIndex() { return primaryIndex; } /** * Checks whether an index name matches the system index name pattern for this descriptor. * @param index The index name to be checked against the index pattern given at construction time. * @return True if the name matches the pattern, false otherwise. */ public boolean matchesIndexPattern(String index) { return <API key>.run(index); } /** * Retrieves a list of all indices which match this descriptor's pattern. * * This cannot be done via {@link org.elasticsearch.cluster.metadata.<API key>} because that class can only handle * simple wildcard expressions, but system index name patterns may use full Lucene regular expression syntax, * * @param metadata The current metadata to get the list of matching indices from * @return A list of index names that match this descriptor */ @Override public List<String> getMatchingIndices(Metadata metadata) { ArrayList<String> matchingIndices = new ArrayList<>(); metadata.indices().keysIt().forEachRemaining(indexName -> { if (matchesIndexPattern(indexName)) { matchingIndices.add(indexName); } }); return Collections.unmodifiableList(matchingIndices); } /** * @return A short description of the purpose of this system index. */ public String getDescription() { return description; } @Override public String toString() { return "<API key>[pattern=[" + indexPattern + "], description=[" + description + "], aliasName=[" + aliasName + "]]"; } public String getMappings() { return mappings; } public Settings getSettings() { return settings; } public String getAliasName() { return aliasName; } public int getIndexFormat() { return this.indexFormat; } public String getVersionMetaKey() { return this.versionMetaKey; } public Version <API key>() { return minimumNodeVersion; } public boolean <API key>() { return type.isManaged(); } public String getOrigin() { return this.origin; } public boolean hasDynamicMappings() { return this.hasDynamicMappings; } public boolean isExternal() { return type.isExternal(); } public boolean isInternal() { return type.isInternal(); } public List<String> <API key>() { return <API key>; } public boolean isNetNew() { return isNetNew; } public Version getMappingVersion() { if (type.isManaged() == false) { throw new <API key>(this + " is not managed so there are no mappings or version"); } return mappingVersion; } /** * Gets a standardized message when the node contains a data or master node whose version is less * than that of the minimum supported version of this descriptor and its prior descriptors. * * @param cause the action being attempted that triggered the check. Used in the error message. * @return the standardized error message */ public String <API key>(String cause) { Objects.requireNonNull(cause); final Version <API key> = <API key>.isEmpty() ? minimumNodeVersion : <API key>.get(<API key>.size() - 1).minimumNodeVersion; return String.format( Locale.ROOT, "[%s] failed - system index [%s] requires all data and master nodes to be at least version [%s]", cause, this.getPrimaryIndex(), <API key> ); } /** * Finds the descriptor that can be used within this cluster, by comparing the supplied minimum * node version to this descriptor's minimum version and the prior descriptors minimum version. * * @param version the lower node version in the cluster * @return <code>null</code> if the lowest node version is lower than the minimum version in this descriptor, * or the appropriate descriptor if the supplied version is acceptable. */ public <API key> <API key>(Version version) { if (minimumNodeVersion.onOrBefore(version)) { return this; } for (<API key> prior : <API key>) { if (version.onOrAfter(prior.minimumNodeVersion)) { return prior; } } return null; } /** * @return The names of thread pools that should be used for operations on this * system index. */ public ExecutorNames getThreadPoolNames() { return this.executorNames; } public static Builder builder() { return new Builder(); } @Override public int compareTo(<API key> other) { return minimumNodeVersion.compareTo(other.minimumNodeVersion) * -1; } /** * The specific type of system index that this descriptor represents. System indices can be one of four defined types; the type is used * to control behavior. Elasticsearch itself and plugins have system indices that are necessary for their features; * these system indices are referred to as internal system indices. System indices can also belong to features outside of Elasticsearch * that may be part of other Elastic stack components. These are external system indices as the intent is for these to be accessed via * normal APIs with a special value. * * Within both internal and external system indices, there are two sub-types. The first are those that are managed by Elasticsearch and * will have mappings/settings changed as the cluster itself is upgraded. The second are those managed by the owning applications code * and for those Elasticsearch will not perform any updates. * * Internal system indices are almost always managed indices that Elasticsearch manages, but there are cases where the component of * Elasticsearch will need to manage the system indices itself. */ public enum Type { INTERNAL_MANAGED(false, true), INTERNAL_UNMANAGED(false, false), EXTERNAL_MANAGED(true, true), EXTERNAL_UNMANAGED(true, false); private final boolean external; private final boolean managed; Type(boolean external, boolean managed) { this.external = external; this.managed = managed; } public boolean isExternal() { return external; } public boolean isManaged() { return managed; } public boolean isInternal() { return external == false; } } /** * Provides a fluent API for building a {@link <API key>}. Validation still happens in that class. */ public static class Builder { private String indexPattern; private String primaryIndex; private String description; private String mappings = null; private Settings settings = null; private String aliasName = null; private int indexFormat = 0; private String versionMetaKey = null; private String origin = null; private Version minimumNodeVersion = Version.CURRENT.<API key>(); private Type type = Type.INTERNAL_MANAGED; private List<String> <API key> = List.of(); private List<<API key>> <API key> = List.of(); private ExecutorNames executorNames; private boolean isNetNew = false; private Builder() {} public Builder setIndexPattern(String indexPattern) { this.indexPattern = indexPattern; return this; } public Builder setPrimaryIndex(String primaryIndex) { this.primaryIndex = primaryIndex; return this; } public Builder setDescription(String description) { this.description = description; return this; } public Builder setMappings(XContentBuilder mappingsBuilder) { mappings = mappingsBuilder == null ? null : Strings.toString(mappingsBuilder); return this; } public Builder setMappings(String mappings) { this.mappings = mappings; return this; } public Builder setSettings(Settings settings) { this.settings = settings; return this; } public Builder setAliasName(String aliasName) { this.aliasName = aliasName; return this; } public Builder setIndexFormat(int indexFormat) { this.indexFormat = indexFormat; return this; } public Builder setVersionMetaKey(String versionMetaKey) { this.versionMetaKey = versionMetaKey; return this; } public Builder setOrigin(String origin) { this.origin = origin; return this; } public Builder <API key>(Version version) { this.minimumNodeVersion = version; return this; } public Builder setType(Type type) { this.type = type; return this; } public Builder <API key>(List<String> <API key>) { this.<API key> = <API key>; return this; } public Builder <API key>(List<<API key>> <API key>) { this.<API key> = <API key>; return this; } public Builder setThreadPools(ExecutorNames executorNames) { this.executorNames = executorNames; return this; } public Builder setNetNew() { this.isNetNew = true; return this; } /** * Builds a {@link <API key>} using the fields supplied to this builder. * @return a populated descriptor. */ public <API key> build() { return new <API key>( indexPattern, primaryIndex, description, mappings, settings, aliasName, indexFormat, versionMetaKey, origin, minimumNodeVersion, type, <API key>, <API key>, executorNames, isNetNew ); } } /** * Builds an automaton for matching index names against this descriptor's index pattern. * If this descriptor has an alias name, the automaton will also try to match against * the alias as well. */ static Automaton buildAutomaton(String pattern, String alias) { final String patternAsRegex = patternToRegex(pattern); final String aliasAsRegex = alias == null ? null : patternToRegex(alias); final Automaton patternAutomaton = new RegExp(patternAsRegex).toAutomaton(); if (aliasAsRegex == null) { return patternAutomaton; } final Automaton aliasAutomaton = new RegExp(aliasAsRegex).toAutomaton(); return Operations.union(patternAutomaton, aliasAutomaton); } /** * Translate a simple string pattern into a regular expression, suitable for creating a * {@link RegExp} instance. This exists because although * {@link org.elasticsearch.common.regex.Regex#<API key>(String)} is useful * for simple patterns, it doesn't support character ranges. * * @param input the string to translate * @return the translate string */ private static String patternToRegex(String input) { String output = input; output = output.replaceAll("\\.", "\\."); output = output.replaceAll("\\*", ".*"); return output; } /** * Recursively searches for <code>dynamic: true</code> in the supplies mappings * @param map a parsed fragment of an index's mappings * @return whether the fragment contains a dynamic mapping */ @SuppressWarnings("unchecked") static boolean findDynamicMapping(Map<String, Object> map) { if (map == null) { return false; } for (Map.Entry<String, Object> entry : map.entrySet()) { final String key = entry.getKey(); final Object value = entry.getValue(); if (key.equals("dynamic") && (value instanceof Boolean) && ((Boolean) value)) { return true; } if (value instanceof Map) { if (findDynamicMapping((Map<String, Object>) value)) { return true; } } } return false; } @SuppressWarnings("unchecked") private static Version <API key>(String mappings, String versionMetaKey) { final Map<String, Object> mappingsMap = XContentHelper.convertToMap(XContentType.JSON.xContent(), mappings, false); final Map<String, Object> doc = (Map<String, Object>) mappingsMap.get("_doc"); final Map<String, Object> meta; if (doc == null) { meta = (Map<String, Object>) mappingsMap.get("_meta"); } else { meta = (Map<String, Object>) doc.get("_meta"); } if (meta == null) { throw new <API key>("mappings do not have _meta field"); } final String value = (String) meta.get(versionMetaKey); if (value == null) { throw new <API key>("mappings do not have a version in _meta." + versionMetaKey); } return Version.fromString(value); } }
package com.boldradius.cqrs import akka.actor.ActorRef import akka.pattern.ask import akka.util.Timeout import com.boldradius.cqrs.<API key>._ import com.boldradius.util.LLogging import org.joda.time.format.DateTimeFormat import spray.routing._ import scala.concurrent.ExecutionContext import scala.concurrent.duration._ import scala.util.{Failure, Success} final case class PlaceBidDto(auctionId:String, buyer:String, bidPrice:Double ) final case class StartAuctionDto(auctionId:String, start:String, end:String, initialPrice: Double, prodId: String) final case class BidDto(price:Double, buyer:String, timeStamp:String) final case class AuctionError(auctionId:String,msg:String,response:String = "AuctionError") final case class AuctionStartedDto(auctionId:String,response:String = "AuctionStartedDto") final case class <API key>(auctionId:String,response:String = "<API key>") final case class SuccessfulBidDto(auctionId:String, bidPrice: Double, timeStamp:String,response:String = "SuccessfulBidDto") final case class RejectedBidDto(auctionId:String, bidPrice: Double, currentBid:Double,response:String = "RejectedBidDto") final case class FailedBidDto(auctionId:String, bidPrice: Double, currentBid:Double,response:String = "FailedBidDto") final case class WinningBidDto(auctionId:String,bidPrice: Double,response:String = "WinningBidDto") final case class BidHistoryDto(auctionId:String,bids: List[BidDto],response:String = "BidHistoryDto") trait <API key> extends HttpService with LLogging{ implicit val ec: ExecutionContext import com.boldradius.util.MarshallingSupport._ implicit val timeout = Timeout(30 seconds) lazy val fmt = DateTimeFormat.forPattern("yyyy-MM-dd-HH:mm") def route(command: ActorRef, query:ActorRef) = { post { path("startAuction") { extract(_.request) { e => entity(as[StartAuctionDto]) { auction => onComplete( (command ? StartAuctionCmd(auction.auctionId, fmt.parseDateTime(auction.start).getMillis, fmt.parseDateTime(auction.end).getMillis, auction.initialPrice, auction.prodId)).mapTo[AuctionAck]) { case Success(ack) => ack match { case StartedAuctionAck(id) => complete(AuctionStartedDto(id)) case InvalidAuctionAck(id, msg) => complete(AuctionError("ERROR",id, msg)) case other => complete(AuctionError("ERROR",ack.auctionId, ack.toString)) } case Failure(t) => t.printStackTrace() complete(AuctionError("ERROR",auction.auctionId, t.getMessage)) } } } } ~ path("bid") { detach(ec) { extract(_.request) { e => entity(as[PlaceBidDto]) { bid => onComplete( (command ? PlaceBidCmd(bid.auctionId, bid.buyer, bid.bidPrice)).mapTo[AuctionAck]) { case Success(ack) => ack.logInfo(s"PlaceBidCmd bid.bidPrice ${bid.bidPrice} id:" + _.auctionId.toString) match { case PlacedBidAck(id, buyer, bidPrice, timeStamp) => complete(SuccessfulBidDto(id, bidPrice, fmt.print(timeStamp))) case RefusedBidAck(id, buyer, bidPrice, winningBid) => complete(RejectedBidDto(id, bidPrice, winningBid)) case other => complete(AuctionError("ERROR",bid.auctionId, other.toString)) } case Failure(t) => complete(AuctionError("ERROR",bid.auctionId, t.getMessage)) } } } } } } ~ get { path("winningBid" / Rest) { auctionId => detach(ec) { onComplete((query ? <API key>(auctionId)).mapTo[BidQueryResponse]) { case Success(s) => s match { case <API key>(id, price) => complete(WinningBidDto(id, price)) case AuctionNotStarted(id) => complete(<API key>(id)) case _ => complete(AuctionError("ERROR",auctionId, "")) } case Failure(t) => t.getMessage.logError("<API key> error: " + _) complete(AuctionError("ERROR",auctionId, t.getMessage)) } } } ~ path("bidHistory" / Rest) { auctionId => onComplete((query ? GetBidHistoryQuery(auctionId)).mapTo[BidQueryResponse]) { case Success(s) => s match { case BidHistoryResponse(id, bids) => complete(BidHistoryDto(id, bids.map(b => BidDto(b.price, b.buyer, fmt.print(b.timeStamp))))) case AuctionNotStarted(id) => complete(<API key>(id)) case _ => complete(AuctionError("ERROR",auctionId, "")) } case Failure(t) => complete(AuctionError("ERROR",auctionId, t.getMessage)) } } } } }
/* Overall layout: use whole page width */ /*.container { width: auto; }*/ /*#header{ position: relative; width: 960px; margin: 0 auto; }*/ #header .buildinfo{ display: none;} /*div#content { padding-top: 35px; padding-bottom: 0px;}*/ div#content p {text-align: left;} /* #step2, #step3 { display: none; } */ label { display: inline-block; } table.jqplot-table-legend { width: 100px; } #visualization { width: 100%; height: 100%; } #data { position: relative; width: 100%; height: 100%; background-color: #E9F0FB; padding-top: 2px; } /** START :: TABLE VISUALIZATION **/ table.tablevis { border-style: none; font-size: small; } table.tablevis th { font-weight: bold; padding: 5px 6px; background: none; background-color: #fafad2; border: 1px solid #CCCCCC; color: #444444; } table.tablevis td { border: 1px solid #CCCCCC; } table.tablevis td.caption { border-style: none; text-align: center; vertical-align: middle; font-style: italic; } table.tablevis tr:not(:first-child) td:first-child.caption { border-bottom: 1px solid #CCCCCC; } /** START :: MESSAGES**/ #message_container { position: relative; width: 100%; } .message_box { position: relative; padding: 5px 35px; margin-bottom: 5px; } .message_error { border: 1px solid #f99; } .message_warning { border: 1px solid #06C; } #<API key> { position: absolute; right: 3px; } #<API key>:hover { text-decoration: underline; background: #87cefa; cursor:pointer; } /** START :: VISUALIZATION MENU **/ #menu_container { float: left; width : 24%; margin: 0% 0% 0% 0.5%; } .menu_item { position: relative; width : 96%; margin: 0%; margin-bottom: 5px; padding: 2%; border: 1px solid #006dba; background-color: white; min-height: 60px; font-size: 11px; } span.menu_done { background-color: #67E667; } span.menu_error { background-color: pink; } span.menu_warning { background-color: #ffa07a; } span.menu_fill { background-color: #A5DCFD; } .menu_header_label { display: inline-block; font-size: 17px; color: #006DBA; vertical-align: baseline; } .menu_header_clear, .menu_header_clear a { font-size: 10px; } .menu_header_count { display: inline-block; height: 22px; width: 25px; margin-right: 5px; font-size: 16px; font-weight: bold; background-color: #DDD; color: white; text-align: center; padding-top: 3px; } #<API key> { position: relative; display: block; width: 74.5%; min-height: 500px; padding: 0px; margin-top: 5px; margin-left: 25%; border: #006dba solid 1px; background-color: white; vertical-align: middle; } #menu_go { background-color: white; text-align: center; } .settings { margin-top: 10px; } .settings img { border: 0px solid #000000; } /** START :: MISC */ #bottom_container { position: relative; } .spinner { display: none; width: 16px; height: 16px; } #button_visualize { margin: 3px; padding: 10px; width: 90%; text-align: center; background-color: #367BA4; color: white; font-size: 16pt; } .<API key> { font-weight: bold; padding: .2em .4em; margin: .8em 0 .2em; line-height: 1.5; } .ui-autocomplete { max-height: 200px; overflow-y: auto; overflow-x: hidden; } .settingInfo { font-size: smaller; color: #999; } /* START :: Block variable */ .block_variable { position: relative; width: 100%; padding: 2px 0px 5px; } .block_variable .<API key> { width: 98%; } .block_variable input[disabled='disabled'] { background-color: #DDD; } .block_variable input[type='radio'] { margin-right: 5%; } .block_variable label { width: 35%; }
package org.batfish.referencelibrary; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableSortedSet; import java.io.Serializable; import java.util.List; import java.util.Objects; import java.util.SortedSet; import javax.annotation.Nonnull; import org.batfish.datamodel.Names; import org.batfish.datamodel.Names.Type; public class ServiceObjectGroup implements Comparable<ServiceObjectGroup>, Serializable { private static final String PROP_NAME = "name"; private static final String PROP_SERVICES = "services"; @Nonnull private String _name; @Nonnull private SortedSet<String> _services; @JsonCreator public ServiceObjectGroup( @JsonProperty(PROP_NAME) String name, @JsonProperty(PROP_SERVICES) SortedSet<String> services) { checkArgument(name != null, "Service object group name cannot be null"); Names.checkName(name, "service object group", Type.REFERENCE_OBJECT); _name = name; _services = firstNonNull(services, ImmutableSortedSet.of()); } public void <API key>(List<String> allServiceNames) { _services.forEach( s -> checkArgument( allServiceNames.contains(s), "Undefined service name '%s' in service object group '%s'", s, _name)); } @Override public int compareTo(ServiceObjectGroup o) { return _name.compareTo(o._name); } @Override public boolean equals(Object o) { if (!(o instanceof ServiceObjectGroup)) { return false; } return Objects.equals(_name, ((ServiceObjectGroup) o)._name) && Objects.equals(_services, ((ServiceObjectGroup) o)._services); } @JsonProperty(PROP_NAME) public String getName() { return _name; } @JsonProperty(PROP_SERVICES) public SortedSet<String> getServices() { return _services; } @Override public int hashCode() { return Objects.hash(_name, _services); } }
#ifndef PGSTAT_H #define PGSTAT_H #include "libpq/pqcomm.h" #include "portability/instr_time.h" #include "utils/hsearch.h" #include "utils/relcache.h" #include "utils/timestamp.h" typedef enum TrackFunctionsLevel { TRACK_FUNC_OFF, TRACK_FUNC_PL, TRACK_FUNC_ALL } TrackFunctionsLevel; typedef enum StatMsgType { PGSTAT_MTYPE_DUMMY, <API key>, <API key>, <API key>, PGSTAT_MTYPE_DROPDB, <API key>, <API key>, PGSTAT_MTYPE_VACUUM, <API key>, <API key>, /* GPDB */ <API key>, <API key>, <API key> } StatMsgType; typedef int64 PgStat_Counter; typedef struct PgStat_TableCounts { PgStat_Counter t_numscans; PgStat_Counter t_tuples_returned; PgStat_Counter t_tuples_fetched; PgStat_Counter t_tuples_inserted; PgStat_Counter t_tuples_updated; PgStat_Counter t_tuples_deleted; PgStat_Counter <API key>; PgStat_Counter t_new_live_tuples; PgStat_Counter t_new_dead_tuples; PgStat_Counter t_blocks_fetched; PgStat_Counter t_blocks_hit; } PgStat_TableCounts; typedef struct PgStat_TableStatus { Oid t_id; /* table's OID */ bool t_shared; /* is it a shared catalog? */ struct <API key> *trans; /* lowest subxact's counts */ PgStat_TableCounts t_counts; /* event counts to be sent */ } PgStat_TableStatus; typedef struct <API key> { PgStat_Counter tuples_inserted; /* tuples inserted in (sub)xact */ PgStat_Counter tuples_deleted; /* tuples deleted in (sub)xact */ int nest_level; /* subtransaction nest level */ /* links to other structs for same relation: */ struct <API key> *upper; /* next higher subxact if any */ PgStat_TableStatus *parent; /* per-table status */ /* structs of same subxact level are linked here: */ struct <API key> *next; /* next of same subxact */ } <API key>; typedef struct PgStat_MsgHdr { StatMsgType m_type; int m_size; } PgStat_MsgHdr; #define PGSTAT_MSG_PAYLOAD (1000 - sizeof(PgStat_MsgHdr)) typedef struct PgStat_MsgDummy { PgStat_MsgHdr m_hdr; } PgStat_MsgDummy; typedef struct PgStat_MsgInquiry { PgStat_MsgHdr m_hdr; TimestampTz inquiry_time; /* minimum acceptable file timestamp */ } PgStat_MsgInquiry; typedef struct PgStat_TableEntry { Oid t_id; PgStat_TableCounts t_counts; } PgStat_TableEntry; #define <API key> \ ((PGSTAT_MSG_PAYLOAD - sizeof(Oid) - 3 * sizeof(int)) \ / sizeof(PgStat_TableEntry)) typedef struct PgStat_MsgTabstat { PgStat_MsgHdr m_hdr; Oid m_databaseid; int m_nentries; int m_xact_commit; int m_xact_rollback; PgStat_TableEntry m_entry[<API key>]; } PgStat_MsgTabstat; #define PGSTAT_NUM_TABPURGE \ ((PGSTAT_MSG_PAYLOAD - sizeof(Oid) - sizeof(int)) \ / sizeof(Oid)) typedef struct PgStat_MsgTabpurge { PgStat_MsgHdr m_hdr; Oid m_databaseid; int m_nentries; Oid m_tableid[PGSTAT_NUM_TABPURGE]; } PgStat_MsgTabpurge; typedef struct PgStat_MsgDropdb { PgStat_MsgHdr m_hdr; Oid m_databaseid; } PgStat_MsgDropdb; typedef struct <API key> { PgStat_MsgHdr m_hdr; Oid m_databaseid; } <API key>; typedef struct <API key> { PgStat_MsgHdr m_hdr; Oid m_databaseid; TimestampTz m_start_time; } <API key>; typedef struct PgStat_MsgVacuum { PgStat_MsgHdr m_hdr; Oid m_databaseid; Oid m_tableoid; bool m_analyze; bool m_autovacuum; TimestampTz m_vacuumtime; PgStat_Counter m_tuples; } PgStat_MsgVacuum; typedef struct PgStat_MsgAnalyze { PgStat_MsgHdr m_hdr; Oid m_databaseid; Oid m_tableoid; bool m_autovacuum; TimestampTz m_analyzetime; PgStat_Counter m_live_tuples; PgStat_Counter m_dead_tuples; } PgStat_MsgAnalyze; typedef struct PgStat_MsgQueuestat { PgStat_MsgHdr m_hdr; Oid m_queueid; PgStat_Counter m_queries_exec; PgStat_Counter m_queries_wait; PgStat_Counter m_elapsed_exec; PgStat_Counter m_elapsed_wait; } PgStat_MsgQueuestat; typedef struct PgStat_MsgBgWriter { PgStat_MsgHdr m_hdr; PgStat_Counter m_timed_checkpoints; PgStat_Counter <API key>; PgStat_Counter <API key>; PgStat_Counter m_buf_written_clean; PgStat_Counter m_maxwritten_clean; PgStat_Counter <API key>; PgStat_Counter m_buf_alloc; } PgStat_MsgBgWriter; typedef struct <API key> { PgStat_Counter f_numcalls; instr_time f_time; instr_time f_time_self; } <API key>; typedef struct <API key> { Oid f_id; <API key> f_counts; } <API key>; typedef struct <API key> { Oid f_id; PgStat_Counter f_numcalls; PgStat_Counter f_time; /* times in microseconds */ PgStat_Counter f_time_self; } <API key>; #define <API key> \ ((PGSTAT_MSG_PAYLOAD - sizeof(Oid) - sizeof(int)) \ / sizeof(<API key>)) typedef struct PgStat_MsgFuncstat { PgStat_MsgHdr m_hdr; Oid m_databaseid; int m_nentries; <API key> m_entry[<API key>]; } PgStat_MsgFuncstat; #define <API key> \ ((PGSTAT_MSG_PAYLOAD - sizeof(Oid) - sizeof(int)) \ / sizeof(Oid)) typedef struct PgStat_MsgFuncpurge { PgStat_MsgHdr m_hdr; Oid m_databaseid; int m_nentries; Oid m_functionid[<API key>]; } PgStat_MsgFuncpurge; typedef union PgStat_Msg { PgStat_MsgHdr msg_hdr; PgStat_MsgDummy msg_dummy; PgStat_MsgInquiry msg_inquiry; PgStat_MsgTabstat msg_tabstat; PgStat_MsgTabpurge msg_tabpurge; PgStat_MsgDropdb msg_dropdb; <API key> msg_resetcounter; <API key> msg_autovacuum; PgStat_MsgVacuum msg_vacuum; PgStat_MsgAnalyze msg_analyze; PgStat_MsgQueuestat msg_queuestat; /* GPDB */ PgStat_MsgBgWriter msg_bgwriter; PgStat_MsgFuncstat msg_funcstat; PgStat_MsgFuncpurge msg_funcpurge; } PgStat_Msg; #define <API key> 0x01A5BC98 typedef struct PgStat_StatDBEntry { Oid databaseid; PgStat_Counter n_xact_commit; PgStat_Counter n_xact_rollback; PgStat_Counter n_blocks_fetched; PgStat_Counter n_blocks_hit; PgStat_Counter n_tuples_returned; PgStat_Counter n_tuples_fetched; PgStat_Counter n_tuples_inserted; PgStat_Counter n_tuples_updated; PgStat_Counter n_tuples_deleted; TimestampTz last_autovac_time; /* * tables and functions must be last in the struct, because we don't write * the pointers out to the stats file. */ HTAB *tables; HTAB *functions; } PgStat_StatDBEntry; typedef struct PgStat_StatTabEntry { Oid tableid; PgStat_Counter numscans; PgStat_Counter tuples_returned; PgStat_Counter tuples_fetched; PgStat_Counter tuples_inserted; PgStat_Counter tuples_updated; PgStat_Counter tuples_deleted; PgStat_Counter tuples_hot_updated; PgStat_Counter n_live_tuples; PgStat_Counter n_dead_tuples; PgStat_Counter last_anl_tuples; PgStat_Counter blocks_fetched; PgStat_Counter blocks_hit; TimestampTz vacuum_timestamp; /* user initiated vacuum */ TimestampTz <API key>; /* autovacuum initiated */ TimestampTz analyze_timestamp; /* user initiated */ TimestampTz <API key>; /* autovacuum initiated */ } PgStat_StatTabEntry; typedef struct <API key> { Oid queueid; PgStat_Counter n_queries_exec; PgStat_Counter n_queries_wait; PgStat_Counter elapsed_exec; PgStat_Counter elapsed_wait; } <API key>; typedef struct <API key> { Oid functionid; PgStat_Counter f_numcalls; PgStat_Counter f_time; /* times in microseconds */ PgStat_Counter f_time_self; } <API key>; typedef struct <API key> { uint32 portalid; time_t t_exec_start; time_t t_exec_end; time_t t_wait_start; time_t t_wait_end; <API key> queueentry; } <API key>; /* * Global statistics kept in the stats collector */ typedef struct PgStat_GlobalStats { TimestampTz stats_timestamp; /* time of stats file update */ PgStat_Counter timed_checkpoints; PgStat_Counter <API key>; PgStat_Counter <API key>; PgStat_Counter buf_written_clean; PgStat_Counter maxwritten_clean; PgStat_Counter buf_written_backend; PgStat_Counter buf_alloc; } PgStat_GlobalStats; /* Definitions of waiting reason */ #define PGBE_WAITING_LOCK 'l' #define <API key> 'r' #define <API key> 'g' #define PGBE_WAITING_NONE '\0' typedef struct PgBackendStatus { /* * To avoid locking overhead, we use the following protocol: a backend * increments st_changecount before modifying its entry, and again after * finishing a modification. A would-be reader should note the value of * st_changecount, copy the entry into private memory, then check * st_changecount again. If the value hasn't changed, and if it's even, * the copy is valid; otherwise start over. This makes updates cheap * while reads are potentially expensive, but that's the tradeoff we want. */ int st_changecount; /* The entry is valid iff st_procpid > 0, unused if st_procpid == 0 */ int st_procpid; /* Times when current backend, transaction, and activity started */ TimestampTz <API key>; TimestampTz <API key>; TimestampTz <API key>; /* the start time of queueing on resource group */ TimestampTz <API key>; /* Database OID, owning user's OID, connection client address */ Oid st_databaseid; Oid st_userid; int st_session_id; /* GPDB only */ SockAddr st_clientaddr; /* Is backend currently waiting on something (and what)? */ char st_waiting; /* application name; MUST be null-terminated */ char *st_appname; /* current command string; MUST be null-terminated */ char *st_activity; Oid st_rsgid; } PgBackendStatus; /* * Working state needed to accumulate per-function-call timing statistics. */ typedef struct <API key> { /* Link to function's hashtable entry (must still be there at exit!) */ /* NULL means we are not tracking the current function call */ <API key> *fs; /* Total time previously charged to function, as of function start */ instr_time save_f_time; /* Backend-wide total time as of function start */ instr_time save_total; /* system clock as of function start */ instr_time f_start; } <API key>; extern bool <API key>; extern bool pgstat_track_counts; extern int <API key>; extern PGDLLIMPORT int <API key>; extern char *pgstat_stat_tmpname; extern char *<API key>; extern bool <API key>; extern int <API key>; //extern PGDLLIMPORT int <API key>; extern char *pgstat_stat_tmpname; extern char *<API key>; /* * BgWriter statistics counters are updated directly by bgwriter and bufmgr */ extern PgStat_MsgBgWriter BgWriterStats; extern Size <API key>(void); extern void <API key>(void); extern void pgstat_init(void); extern int pgstat_start(void); extern void pgstat_reset_all(void); extern void <API key>(void); #ifdef EXEC_BACKEND extern void PgstatCollectorMain(int argc, char *argv[]); #endif extern void pgstat_ping(void); extern void pgstat_report_stat(bool force); extern void pgstat_vacuum_stat(void); extern void <API key>(void); /* GPDB */ extern void <API key>(Oid databaseid); extern void <API key>(void); extern void <API key>(void); extern void <API key>(Oid dboid); extern void <API key>(Oid tableoid, bool shared, bool analyze, PgStat_Counter tuples); extern void <API key>(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples); extern void pgstat_initialize(void); extern void pgstat_bestart(void); extern void <API key>(const char *what); extern void <API key>(TimestampTz tstamp); extern void <API key>(char reason); extern void <API key>(const char *appname); extern void <API key>(TimestampTz tstamp); extern const char *<API key>(int pid, bool checkUser); extern void <API key>(TimestampTz queueStart, Oid groupid); extern TimestampTz <API key>(void); extern void pgstat_initstats(Relation rel); extern void <API key>(void); extern <API key> *<API key>(uint32 portalid, Oid queueid); /* nontransactional event counts are simple enough to inline */ #define <API key>(rel) \ do { \ if (pgstat_track_counts && (rel)->pgstat_info != NULL) \ (rel)->pgstat_info->t_counts.t_numscans++; \ } while (0) #define <API key>(rel) \ do { \ if (pgstat_track_counts && (rel)->pgstat_info != NULL) \ (rel)->pgstat_info->t_counts.t_tuples_returned++; \ } while (0) #define <API key>(rel) \ do { \ if (pgstat_track_counts && (rel)->pgstat_info != NULL) \ (rel)->pgstat_info->t_counts.t_tuples_fetched++; \ } while (0) /* #define <API key>(s) \ do { \ if (pgstat_track_counts) \ (s)->pgstat_info->t_counts.t_tuples_inserted++; \ } while (0) #define <API key>(s,h) \ do { \ if (pgstat_track_counts) \ (s)->pgstat_info->t_counts.t_tuples_updated++; \ } while (0) #define <API key>(s) \ do { \ if (pgstat_track_counts) \ (s)->pgstat_info->t_counts.t_tuples_deleted++; \ } while (0) */ #define <API key>(rel) \ do { \ if (pgstat_track_counts && (rel)->pgstat_info != NULL) \ (rel)->pgstat_info->t_counts.t_numscans++; \ } while (0) #define <API key>(rel, n) \ do { \ if (pgstat_track_counts && (rel)->pgstat_info != NULL) \ (rel)->pgstat_info->t_counts.t_tuples_returned += (n); \ } while (0) #define <API key>(rel) \ do { \ if (pgstat_track_counts && (rel)->pgstat_info != NULL) \ (rel)->pgstat_info->t_counts.t_blocks_fetched++; \ } while (0) #define <API key>(rel) \ do { \ if (pgstat_track_counts && (rel)->pgstat_info != NULL) \ (rel)->pgstat_info->t_counts.t_blocks_hit++; \ } while (0) /* Resource queue statistics: */ #define <API key>(p, q) \ do { \ if (<API key>) \ { \ <API key> *pentry; \ \ pentry = <API key>(p, q); \ ((pentry)->queueentry).n_queries_exec++; \ } \ } while (0) #define <API key>(p, q) \ do { \ if (<API key>) \ { \ <API key> *pentry; \ \ pentry = <API key>(p, q); \ (pentry)->t_exec_start = time(NULL); \ } \ } while (0) #define <API key>(p, q) \ do { \ if (<API key>) \ { \ <API key> *pentry; \ \ pentry = <API key>(p, q); \ (pentry)->t_exec_end = time(NULL); \ ((pentry)->queueentry).elapsed_exec += \ (PgStat_Counter)((pentry)->t_exec_end - (pentry)->t_exec_start); \ } \ } while (0) #define <API key>(p, q) \ do { \ if (<API key>) \ { \ <API key> *pentry; \ \ pentry = <API key>(p, q); \ ((pentry)->queueentry).n_queries_wait++; \ } \ } while (0) #define <API key>(p, q) \ do { \ if (<API key>) \ { \ <API key> *pentry; \ \ pentry = <API key>(p, q); \ (pentry)->t_wait_start = time(NULL); \ } \ } while (0) #define <API key>(p, q) \ do { \ if (<API key>) \ { \ <API key> *pentry; \ \ pentry = <API key>(p, q); \ (pentry)->t_wait_end = time(NULL); \ ((pentry)->queueentry).elapsed_wait += \ (PgStat_Counter)((pentry)->t_wait_end - (pentry)->t_wait_start); \ } \ } while (0) extern void <API key>(Relation rel); extern void <API key>(Relation rel, bool hot); extern void <API key>(Relation rel); extern void <API key>(Relation rel, int delta); extern void <API key>(<API key> *fcinfo, <API key> *fcu); extern void <API key>(<API key> *fcu, bool finalize); extern void AtEOXact_PgStat(bool isCommit); extern void AtEOSubXact_PgStat(bool isCommit, int nestDepth); extern void AtPrepare_PgStat(void); extern void PostPrepare_PgStat(void); extern void <API key>(TransactionId xid, uint16 info, void *recdata, uint32 len); extern void <API key>(TransactionId xid, uint16 info, void *recdata, uint32 len); extern void <API key>(Relation rel); extern void <API key>(Relation rel, bool hot); extern void <API key>(Relation rel); extern void <API key>(Relation rel, int delta); extern void <API key>(<API key> *fcinfo, <API key> *fcu); extern void <API key>(<API key> *fcu, bool finalize); extern void AtEOXact_PgStat(bool isCommit); extern void AtEOSubXact_PgStat(bool isCommit, int nestDepth); extern void AtPrepare_PgStat(void); extern void PostPrepare_PgStat(void); extern void <API key>(TransactionId xid, uint16 info, void *recdata, uint32 len); extern void <API key>(TransactionId xid, uint16 info, void *recdata, uint32 len); extern void <API key>(void); extern PgStat_StatDBEntry *<API key>(Oid dbid); extern PgStat_StatTabEntry *<API key>(Oid relid); extern <API key> *<API key>(Oid queueid); /* GPDB */ extern PgBackendStatus *<API key>(int beid); extern <API key> *<API key>(Oid funcid); extern int <API key>(void); extern PgStat_GlobalStats *pgstat_fetch_global(void); #endif /* PGSTAT_H */
package com.impetus.kundera.client.cassandra.pelops.crud; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import javax.persistence.<API key>; import javax.persistence.Persistence; import org.apache.cassandra.thrift.CfDef; import org.apache.cassandra.thrift.<API key>; import org.apache.cassandra.thrift.KsDef; import org.apache.cassandra.thrift.NotFoundException; import org.apache.cassandra.thrift.<API key>; import org.apache.cassandra.thrift.TimedOutException; import org.apache.cassandra.thrift.<API key>; import org.apache.thrift.TException; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.impetus.client.crud.<API key>; import com.impetus.kundera.client.cassandra.persistence.CassandraCli; public class <API key> extends <API key> { private <API key> emf; @Before public void setUp() throws Exception { CassandraCli.cassandraSetUp(); CassandraCli.createKeySpace("UUIDCassandra"); loadData(); emf = Persistence.<API key>("cass_pu"); } @After public void tearDown() throws Exception { emf.close(); CassandraCli.dropKeySpace("UUIDCassandra"); } @Test public void test() { testCRUD(emf); } /** * Load cassandra specific data. * * @throws TException * the t exception * @throws <API key> * the invalid request exception * @throws <API key> * the unavailable exception * @throws TimedOutException * the timed out exception * @throws <API key> * the schema disagreement exception */ private void loadData() throws TException, <API key>, <API key>, TimedOutException, <API key> { String table1 = "PRIMARY_TABLE"; String table2 = "SECONDARY_TABLE"; String keyspace = "UUIDCassandra"; KsDef ksDef = null; CfDef user_Def1 = new CfDef(); user_Def1.name = table1; user_Def1.keyspace = keyspace; user_Def1.column_type = "Super"; CfDef user_Def2 = new CfDef(); user_Def2.name = table2; user_Def2.keyspace = keyspace; user_Def2.column_type = "Super"; List<CfDef> cfDefs = new ArrayList<CfDef>(); cfDefs.add(user_Def1); cfDefs.add(user_Def2); try { ksDef = CassandraCli.client.describe_keyspace(keyspace); CassandraCli.client.set_keyspace(keyspace); List<CfDef> cfDefn = ksDef.getCf_defs(); for (CfDef cfDef1 : cfDefn) { if (cfDef1.getName().equalsIgnoreCase(table1)) { CassandraCli.client.<API key>(table1); } if (cfDef1.getName().equalsIgnoreCase(table2)) { CassandraCli.client.<API key>(table2); } } CassandraCli.client.<API key>(user_Def1); CassandraCli.client.<API key>(user_Def2); } catch (NotFoundException e) { ksDef = new KsDef(keyspace, "org.apache.cassandra.locator.SimpleStrategy", cfDefs); // Set replication factor if (ksDef.strategy_options == null) { ksDef.strategy_options = new LinkedHashMap<String, String>(); } // Set replication factor, the value MUST be an integer ksDef.strategy_options.put("replication_factor", "1"); CassandraCli.client.system_add_keyspace(ksDef); } } }
package com.google.api.ads.dfp.jaxws.v201405; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "<API key>", propOrder = { "codeSnippet" }) @XmlSeeAlso({ AdSenseCreative.class, AdExchangeCreative.class }) public abstract class <API key> extends <API key> { protected String codeSnippet; /** * Gets the value of the codeSnippet property. * * @return * possible object is * {@link String } * */ public String getCodeSnippet() { return codeSnippet; } /** * Sets the value of the codeSnippet property. * * @param value * allowed object is * {@link String } * */ public void setCodeSnippet(String value) { this.codeSnippet = value; } }
from pysqlite2 import dbapi2 as sqlite import re import math def getwords(doc): splitter=re.compile('\\W*') print doc # Split the words by non-alpha characters words=[s.lower() for s in splitter.split(doc) if len(s)>2 and len(s)<20] # Return the unique set of words only return dict([(w,1) for w in words]) class classifier: def __init__(self,getfeatures,filename=None): # Counts of feature/category combinations self.fc={} # Counts of documents in each category self.cc={} self.getfeatures=getfeatures def setdb(self,dbfile): self.con=sqlite.connect(dbfile) self.con.execute('create table if not exists fc(feature,category,count)') self.con.execute('create table if not exists cc(category,count)') def incf(self,f,cat): count=self.fcount(f,cat) if count==0: self.con.execute("insert into fc values ('%s','%s',1)" % (f,cat)) else: self.con.execute( "update fc set count=%d where feature='%s' and category='%s'" % (count+1,f,cat)) def fcount(self,f,cat): res=self.con.execute( 'select count from fc where feature="%s" and category="%s"' %(f,cat)).fetchone() if res==None: return 0 else: return float(res[0]) def incc(self,cat): count=self.catcount(cat) if count==0: self.con.execute("insert into cc values ('%s',1)" % (cat)) else: self.con.execute("update cc set count=%d where category='%s'" % (count+1,cat)) def catcount(self,cat): res=self.con.execute('select count from cc where category="%s"' %(cat)).fetchone() if res==None: return 0 else: return float(res[0]) def categories(self): cur=self.con.execute('select category from cc'); return [d[0] for d in cur] def totalcount(self): res=self.con.execute('select sum(count) from cc').fetchone(); if res==None: return 0 return res[0] def train(self,item,cat): features=self.getfeatures(item) # Increment the count for every feature with this category for f in features: self.incf(f,cat) # Increment the count for this category self.incc(cat) self.con.commit() def fprob(self,f,cat): if self.catcount(cat)==0: return 0 # The total number of times this feature appeared in this # category divided by the total number of items in this category return self.fcount(f,cat)/self.catcount(cat) def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5): # Calculate current probability basicprob=prf(f,cat) # Count the number of times this feature has appeared in # all categories totals=sum([self.fcount(f,c) for c in self.categories()]) # Calculate the weighted average bp=((weight*ap)+(totals*basicprob))/(weight+totals) return bp class naivebayes(classifier): def __init__(self,getfeatures): classifier.__init__(self,getfeatures) self.thresholds={} def docprob(self,item,cat): features=self.getfeatures(item) # Multiply the probabilities of all the features together p=1 for f in features: p*=self.weightedprob(f,cat,self.fprob) return p def prob(self,item,cat): catprob=self.catcount(cat)/self.totalcount() docprob=self.docprob(item,cat) return docprob*catprob def setthreshold(self,cat,t): self.thresholds[cat]=t def getthreshold(self,cat): if cat not in self.thresholds: return 1.0 return self.thresholds[cat] def classify(self,item,default=None): probs={} # Find the category with the highest probability max=0.0 for cat in self.categories(): probs[cat]=self.prob(item,cat) if probs[cat]>max: max=probs[cat] best=cat # Make sure the probability exceeds threshold*next best for cat in probs: if cat==best: continue if probs[cat]*self.getthreshold(best)>probs[best]: return default return best class fisherclassifier(classifier): def cprob(self,f,cat): # The frequency of this feature in this category clf=self.fprob(f,cat) if clf==0: return 0 # The frequency of this feature in all the categories freqsum=sum([self.fprob(f,c) for c in self.categories()]) # The probability is the frequency in this category divided by # the overall frequency p=clf/(freqsum) return p def fisherprob(self,item,cat): # Multiply all the probabilities together p=1 features=self.getfeatures(item) for f in features: p*=(self.weightedprob(f,cat,self.cprob)) # Take the natural log and multiply by -2 fscore=-2*math.log(p) # Use the inverse chi2 function to get a probability return self.invchi2(fscore,len(features)*2) def invchi2(self,chi, df): m = chi / 2.0 sum = term = math.exp(-m) for i in range(1, df term *= m / i sum += term return min(sum, 1.0) def __init__(self,getfeatures): classifier.__init__(self,getfeatures) self.minimums={} def setminimum(self,cat,min): self.minimums[cat]=min def getminimum(self,cat): if cat not in self.minimums: return 0 return self.minimums[cat] def classify(self,item,default=None): # Loop through looking for the best result best=default max=0.0 for c in self.categories(): p=self.fisherprob(item,c) # Make sure it exceeds its minimum if p>self.getminimum(c) and p>max: best=c max=p return best def sampletrain(cl): cl.train('Nobody owns the water.','good') cl.train('the quick rabbit jumps fences','good') cl.train('buy pharmaceuticals now','bad') cl.train('make quick money at the online casino','bad') cl.train('the quick brown fox jumps','good')
class X::Cannot::Lazy { ... } # Now that Iterable is defined, we add extra methods into Any for the list # operations. (They can't go into Any right away since we need Attribute to # define the various roles, and Attribute inherits from Any. We will do a # re-compose of Attribute to make sure it gets the list methods at the end # of this file. Note the general pattern for these list-y methods is that # they check if they have an Iterable already, and if not obtain one to # work on by doing a .list coercion. use MONKEY-TYPING; augment class Any { proto method map(|) is nodal { * } multi method map(Hash \h) { die "Cannot map a {self.^name} to a {h.^name}. Did you mean to add a stub (\{...\}) or did you mean to .classify?" } multi method map(\SELF: &block;; :$label, :$item) { sequential-map(($item ?? (SELF,) !! SELF).iterator, &block, :$label); } multi method map(HyperIterable:D: &block;; :$label) { # For now we only know how to parallelize when we've only one input # value needed per block. For the rest, fall back to sequential. if &block.count != 1 { sequential-map(self.iterator, &block, :$label) } else { HyperSeq.new(class :: does HyperIterator { has $!source; has &!block; method new(\source, &block) { my \iter = nqp::create(self); nqp::bindattr(iter, self, '$!source', source); nqp::bindattr(iter, self, '&!block', &block); iter } method fill-buffer(HyperWorkBuffer:D $work, int $items) { $!source.fill-buffer($work, $items); } method process-buffer(HyperWorkBuffer:D $work) { unless $!source.process-buffer($work) =:= Nil { $work.swap(); } my \buffer-mapper = sequential-map($work.input-iterator, &!block, :$label); buffer-mapper.iterator.push-all($work.output); $work } method configuration() { $!source.configuration } }.new(self.hyper-iterator, &block)) } } my role MapIterCommon does SlippyIterator { has &!block; has $!source; has $!count; has $!label; method new(&block, $source, $count, $label) { my $iter := nqp::create(self); nqp::bindattr($iter, self, '&!block', &block); nqp::bindattr($iter, self, '$!source', $source); nqp::bindattr($iter, self, '$!count', $count); nqp::bindattr($iter, self, '$!label', $label); $iter } method is-lazy() { $!source.is-lazy } } sub sequential-map(\source, &block, :$label) { # We want map to be fast, so we go to some effort to build special # case iterators that can ignore various interesting cases. my $count = &block.count; # "loop" taking 0 or 1 parameter if $count == 1 || $count == 0 || $count === Inf { Seq.new(class :: does MapIterCommon { has $!did-init; has $!did-iterate; has $!NEXT; has $!CAN_FIRE_PHASERS; method pull-one() is raw { my int $redo = 1; my $value; my $result; if !$!did-init && nqp::can(&!block, 'fire_phasers') { $!did-init = 1; $!CAN_FIRE_PHASERS = 1; $!NEXT = +&!block.phasers('NEXT'); nqp::p6setfirstflag(&!block) if &!block.phasers('FIRST'); } if $!slipping && !(($result := self.slip-one()) =:= IterationEnd) { # $result will be returned at the end } elsif ($value := $!source.pull-one()) =:= IterationEnd { $result := $value } else { nqp::while( $redo, nqp::stmts( $redo = 0, nqp::handle( nqp::stmts( ($result := &!block($value)), ($!did-iterate = 1), nqp::if( nqp::istype($result, Slip), nqp::stmts( ($result := self.start-slip($result)), nqp::if( nqp::eqaddr($result, IterationEnd), nqp::stmts( ($value := $!source.pull-one()), ($redo = 1 unless nqp::eqaddr($value,IterationEnd)) ) ) ) ), nqp::if($!NEXT, &!block.fire_phasers('NEXT')), ), 'LABELED', nqp::decont($!label), 'NEXT', nqp::stmts( ($!did-iterate = 1), nqp::if($!NEXT, &!block.fire_phasers('NEXT')), ($value := $!source.pull-one()), nqp::eqaddr($value, IterationEnd) ?? ($result := IterationEnd) !! ($redo = 1) ), 'REDO', $redo = 1, 'LAST', nqp::stmts( ($!did-iterate = 1), ($result := IterationEnd) ) ) ), :nohandler); } &!block.fire_phasers('LAST') if $!CAN_FIRE_PHASERS && $!did-iterate && nqp::eqaddr($result,IterationEnd); $result } method sink-all() { if !$!did-init && nqp::can(&!block, 'fire_phasers') { $!did-init = 1; $!CAN_FIRE_PHASERS = 1; $!NEXT = +&!block.phasers('NEXT'); nqp::p6setfirstflag(&!block) if &!block.phasers('FIRST'); } my $result; my int $redo; my $value; until nqp::eqaddr($result, IterationEnd) { if nqp::eqaddr(($value := $!source.pull-one()), IterationEnd) { $result := $value } else { $redo = 1; nqp::while( $redo, nqp::stmts( $redo = 0, nqp::handle( nqp::stmts( ($result := &!block($value)), ($!did-iterate = 1), nqp::if($!NEXT, &!block.fire_phasers('NEXT')), ), 'LABELED', nqp::decont($!label), 'NEXT', nqp::stmts( ($!did-iterate = 1), nqp::if($!NEXT, &!block.fire_phasers('NEXT')), ($value := $!source.pull-one()), nqp::eqaddr($value, IterationEnd) ?? ($result := IterationEnd) !! ($redo = 1)), 'REDO', $redo = 1, 'LAST', nqp::stmts( ($!did-iterate = 1), ($result := IterationEnd) ) ) ), :nohandler); } &!block.fire_phasers('LAST') if $!CAN_FIRE_PHASERS && $!did-iterate && nqp::eqaddr($result, IterationEnd); } IterationEnd } }.new(&block, source, 1, $label)); } # loop/map taking more than 1 param else { Seq.new(class :: does MapIterCommon { has $!value-buffer; has $!did-init; has $!did-iterate; has $!NEXT; has $!CAN_FIRE_PHASERS; method pull-one() is raw { $!value-buffer.DEFINITE ?? nqp::setelems($!value-buffer, 0) !! ($!value-buffer := IterationBuffer.new); my int $redo = 1; my $result; if !$!did-init && nqp::can(&!block, 'fire_phasers') { $!did-init = 1; $!CAN_FIRE_PHASERS = 1; $!NEXT = +&!block.phasers('NEXT'); nqp::p6setfirstflag(&!block) if &!block.phasers('FIRST'); } if $!slipping && !(($result := self.slip-one()) =:= IterationEnd) { # $result will be returned at the end } elsif $!source.push-exactly($!value-buffer, $!count) =:= IterationEnd && nqp::elems($!value-buffer) == 0 { $result := IterationEnd } else { nqp::while( $redo, nqp::stmts( $redo = 0, nqp::handle( nqp::stmts( ($result := nqp::p6invokeflat(&!block, $!value-buffer)), ($!did-iterate = 1), nqp::if( nqp::istype($result, Slip), nqp::stmts( ($result := self.start-slip($result)), nqp::if( nqp::eqaddr($result, IterationEnd), nqp::stmts( (nqp::setelems($!value-buffer, 0)), ($redo = 1 unless nqp::eqaddr( $!source.push-exactly($!value-buffer, $!count), IterationEnd) && nqp::elems($!value-buffer) == 0) ) ) ) ), nqp::if($!NEXT, &!block.fire_phasers('NEXT')), ), 'LABELED', nqp::decont($!label), 'NEXT', nqp::stmts( ($!did-iterate = 1), nqp::if($!NEXT, &!block.fire_phasers('NEXT')), (nqp::setelems($!value-buffer, 0)), nqp::eqaddr($!source.push-exactly($!value-buffer, $!count), IterationEnd) && nqp::elems($!value-buffer) == 0 ?? ($result := IterationEnd) !! ($redo = 1)), 'REDO', $redo = 1, 'LAST', nqp::stmts( ($!did-iterate = 1), ($result := IterationEnd) ) ) ), :nohandler); } &!block.fire_phasers('LAST') if $!CAN_FIRE_PHASERS && $!did-iterate && nqp::eqaddr($result, IterationEnd); $result } }.new(&block, source, $count, $label)); } } proto method flatmap (|) is nodal { * } multi method flatmap(&block, :$label) { self.map(&block, :$label).flat } method !grep-k(Callable:D $test) { Seq.new(class :: does Iterator { has Mu $!iter; has Mu $!test; has int $!index; method BUILD(\list,Mu \test) { $!iter = list.iterator; $!test := test; $!index = -1; self } method new(\list,Mu \test) { nqp::create(self).BUILD(list,test) } method pull-one() is raw { $!index = $!index + 1 until ($_ := $!iter.pull-one) =:= IterationEnd || $!test($_); $_ =:= IterationEnd ?? IterationEnd !! nqp::p6box_i($!index = $!index + 1) } method push-exactly($target, int $n) { my int $done; while $done < $n { return IterationEnd if IterationEnd =:= ($_ := $!iter.pull-one); $!index = $!index + 1; if $!test($_) { $target.push(nqp::p6box_i($!index)); $done = $done + 1; } } $done } method push-all($target) { until ($_ := $!iter.pull-one) =:= IterationEnd { $!index = $!index + 1; $target.push(nqp::p6box_i($!index)) if $!test($_); } IterationEnd } }.new(self, $test)) } method !grep-kv(Callable:D $test) { Seq.new(class :: does Iterator { has Mu $!iter; has Mu $!test; has int $!index; has Mu $!value; method BUILD(\list,Mu \test) { $!iter = list.iterator; $!test := test; $!index = -1; self } method new(\list,Mu \test) { nqp::create(self).BUILD(list,test) } method pull-one() is raw { if $!value.DEFINITE { my \tmp = $!value; $!value := Mu; tmp } else { $!index = $!index + 1 until ($_ := $!iter.pull-one) =:= IterationEnd || $!test($_); if $_ =:= IterationEnd { IterationEnd; } else { $!value := $_; nqp::p6box_i($!index = $!index + 1) } } } method push-exactly($target, int $n) { my int $done; my $no-sink; if $!value.DEFINITE { $no-sink := $target.push($!value); $!value := Mu; $done = $done + 1; } while $done < $n { return IterationEnd if IterationEnd =:= ($_ := $!iter.pull-one); $!index = $!index + 1; if $!test($_) { $target.push(nqp::p6box_i($!index)); if ($done = $done + 1) < $n { $no-sink := $target.push($_); $done = $done + 1; } else { $!value := $_; } } } $done } method push-all($target) { my $no-sink; until ($_ := $!iter.pull-one) =:= IterationEnd { $!index = $!index + 1; if $!test($_) { $target.push(nqp::p6box_i($!index)); $no-sink := $target.push($_); } } IterationEnd } }.new(self, $test)) } method !grep-p(Callable:D $test) { Seq.new(class :: does Iterator { has Mu $!iter; has Mu $!test; has int $!index; method BUILD(\list,Mu \test) { $!iter = list.iterator; $!test := test; $!index = -1; self } method new(\list,Mu \test) { nqp::create(self).BUILD(list,test) } method pull-one() is raw { $!index = $!index + 1 until ($_ := $!iter.pull-one) =:= IterationEnd || $!test($_); $_ =:= IterationEnd ?? IterationEnd !! Pair.new($!index = $!index + 1,$_) } method push-exactly($target, int $n) { my int $done; while $done < $n { return IterationEnd if IterationEnd =:= ($_ := $!iter.pull-one); $!index = $!index + 1; if $!test($_) { $target.push(Pair.new($!index,$_)); $done = $done + 1; } } $done } method push-all($target) { until ($_ := $!iter.pull-one) =:= IterationEnd { $!index = $!index + 1; $target.push(Pair.new($!index,$_)) if $!test($_); } IterationEnd } }.new(self, $test)) } role Grepper does Iterator { has Mu $!iter; has Mu $!test; method BUILD(\list,Mu \test) { $!iter = list.iterator; $!test := test; self } method new(\list,Mu \test) { nqp::create(self).BUILD(list,test) } } method !grep-regex(Regex:D $test) { Seq.new(class :: does Grepper { method pull-one() is raw { Nil until ($_ := $!iter.pull-one) =:= IterationEnd || $_.match($!test); $_ } method push-exactly($target, int $n) { my int $done; my $no-sink; while $done < $n { return IterationEnd if IterationEnd =:= ($_ := $!iter.pull-one); if $_.match($!test) { $no-sink := $target.push($_); $done = $done + 1; } } $done } method push-all($target) { my $no-sink; $no-sink := $target.push($_) if $_.match($!test) until ($_ := $!iter.pull-one) =:= IterationEnd; IterationEnd } }.new(self, $test)) } method !grep-callable(Callable:D $test) { if ($test.count == 1) { $test.?has-phasers ?? self.map({ next unless $test($_); $_ }) # cannot go fast !! Seq.new(class :: does Grepper { method pull-one() is raw { Nil until ($_ := $!iter.pull-one) =:= IterationEnd || $!test($_); $_ } method push-exactly($target, int $n) { my int $done; my $no-sink; while $done < $n { return IterationEnd if IterationEnd =:= ($_ := $!iter.pull-one); if $!test($_) { $no-sink := $target.push($_); $done = $done + 1; } } $done } method push-all($target) { my $no-sink; $no-sink := $target.push($_) if $!test($_) until ($_ := $!iter.pull-one) =:= IterationEnd; IterationEnd } method sink-all() { $!test($_) until ($_ := $!iter.pull-one) =:= IterationEnd; IterationEnd } }.new(self, $test)) } else { my role CheatArity { has $!arity; has $!count; method set-cheat($new-arity, $new-count) { $!arity = $new-arity; $!count = $new-count; } method arity(Code:D:) { $!arity } method count(Code:D:) { $!count } } my &tester = -> |c { #note "*cough* {c.perl} -> {$test(|c).perl}"; next unless $test(|c); c.list } but CheatArity; &tester.set-cheat($test.arity, $test.count); self.map(&tester); } } method !grep-accepts(Mu $test) { Seq.new(class :: does Grepper { method pull-one() is raw { Nil until ($_ := $!iter.pull-one) =:= IterationEnd || $!test.ACCEPTS($_); $_ } method push-exactly($target, int $n) { my int $done; my $no-sink; while $done < $n { return IterationEnd if IterationEnd =:= ($_ := $!iter.pull-one); if $!test.ACCEPTS($_) { $no-sink := $target.push($_); $done = $done + 1; } } $done } method push-all($target) { my $no-sink; $no-sink := $target.push($_) if $!test.ACCEPTS($_) until ($_ := $!iter.pull-one) =:= IterationEnd; IterationEnd } }.new(self, $test)) } method !first-result(\index,\value,$what,%a) is raw { if %a { if %a == 1 { if %a<k> { nqp::p6box_i(index) } elsif %a<p> { Pair.new(index,value) } elsif %a<v> { value } else { my $k = %a.keys[0]; if $k eq 'k' || $k eq 'p' { value } elsif $k eq 'v' { fail "Doesn't make sense to specify a negated :v adverb" } else { fail X::Adverb.new( :$what, :source(try { self.VAR.name } // self.WHAT.perl), :unexpected(%a.keys)) } } } else { fail X::Adverb.new( :$what, :source(try { self.VAR.name } // self.WHAT.perl), :nogo(%a.keys.grep: /k|v|p/) :unexpected(%a.keys.grep: { !.match(/k|v|p/) } )) } } else { value } } proto method grep(|) is nodal { * } multi method grep(Bool:D $t) { fail X::Match::Bool.new( type => '.grep' ); } multi method grep(Mu $t) { if %_ == 0 { nqp::istype($t,Regex:D) ?? self!grep-regex: $t !! nqp::istype($t,Callable:D) ?? self!grep-callable: $t !! self!grep-accepts: $t } elsif %_ == 1 { if %_<k> { nqp::istype($t,Regex:D) ?? self!grep-k: { $_.match($t) } !! nqp::istype($t,Callable:D) ?? self!grep-k: $t !! self!grep-k: { $t.ACCEPTS($_) } } elsif %_<kv> { nqp::istype($t,Regex:D) ?? self!grep-kv: { $_.match($t) } !! nqp::istype($t,Callable:D) ?? self!grep-kv: $t !! self!grep-kv: { $t.ACCEPTS($_) } } elsif %_<p> { nqp::istype($t,Regex:D) ?? self!grep-p: { $_.match($t) } !! nqp::istype($t,Callable:D) ?? self!grep-p: $t !! self!grep-p: { $t.ACCEPTS($_) } } elsif %_<v> { nqp::istype($t,Regex:D) ?? self!grep-regex: $t !! nqp::istype($t,Callable:D) ?? self!grep-callable: $t !! self!grep-accepts: $t } else { my $k = %_.keys[0]; if $k eq 'k' || $k eq 'kv' || $k eq 'p' { nqp::istype($t,Regex:D) ?? self!grep-regex: $t !! nqp::istype($t,Callable:D) ?? self!grep-callable: $t !! self!grep-accepts: $t } else { $k eq 'v' ?? fail "Doesn't make sense to specify a negated :v adverb" !! fail X::Adverb.new( :what<grep>, :source(try { self.VAR.name } // self.WHAT.perl), :unexpected($k)) } } } else { fail X::Adverb.new( :what<grep>, :source(try { self.VAR.name } // self.WHAT.perl), :nogo(%_.keys.grep: /k|v|kv|p/) :unexpected(%_.keys.grep: { !.match(/k|v|kv|p/) } )) } } proto method first(|) is nodal { * } multi method first(:$end) { $end ?? ((my $elems = self.elems) ?? self.AT-POS($elems - 1) !! Nil) !! ((my $x := self.iterator.pull-one) =:= IterationEnd ?? Nil !! $x) } multi method first(Bool:D $t) { fail X::Match::Bool.new( type => '.first' ); } multi method first(Regex:D $test, :$end, *%a) is raw { if $end { my $elems = self.elems; if $elems && !($elems == Inf) { my int $index = $elems; return self!first-result($index,$_,'first :end',%a) if ($_ := self.AT-POS($index)).match($test) while $index } Nil } else { my $iter := self.iterator; my int $index; $index = $index + 1 until ($_ := $iter.pull-one) =:= IterationEnd || .match($test); $_ =:= IterationEnd ?? Nil !! self!first-result($index,$_,'first',%a) } } multi method first(Callable:D $test, :$end, *%a is copy) is raw { if $end { my $elems = self.elems; if $elems && !($elems == Inf) { my int $index = $elems; return self!first-result($index,$_,'first :end',%a) if $test($_ := self.AT-POS($index)) while $index } Nil } else { my $iter := self.iterator; my int $index; $index = $index + 1 until ($_ := $iter.pull-one) =:= IterationEnd || $test($_); $_ =:= IterationEnd ?? Nil !! self!first-result($index,$_,'first',%a) } } multi method first(Mu $test, :$end, *%a) is raw { if $end { my $elems = self.elems; if $elems && !($elems == Inf) { my int $index = $elems; return self!first-result($index,$_,'first :end',%a) if $test.ACCEPTS($_ := self.AT-POS($index)) while $index } Nil } else { my $iter := self.iterator; my int $index; $index = $index + 1 until (($_ := $iter.pull-one) =:= IterationEnd) || $test.ACCEPTS($_); $_ =:= IterationEnd ?? Nil !! self!first-result($index,$_,'first',%a) } } method !first-concrete(\i,\todo,\found) { my $value; while nqp::islt_i(i,todo) { $value := self.AT-POS(i); i = i + 1; if nqp::isconcrete($value) { found = $value; last; } } } proto method min (|) is nodal { * } multi method min() { my $elems = self.cache.elems; die "Cannot .min on an infinite list" if $elems == Inf; my $value; my $min; my int $todo = $elems; my int $index; self!first-concrete($index,$todo,$min); while nqp::islt_i($index,$todo) { $value := self.AT-POS($index); $index = $index + 1; $min = $value if nqp::isconcrete($value) && $value cmp $min < 0; } $min // Inf; } multi method min(&by) { my $elems = self.cache.elems; die "Cannot .min on an infinite list" if $elems == Inf; my $cmp = &by.arity == 2 ?? &by !! { &by($^a) cmp &by($^b) } my $value; my $min; my int $todo = $elems; my int $index; self!first-concrete($index,$todo,$min); while nqp::islt_i($index,$todo) { $value := self.AT-POS($index); $index = $index + 1; $min = $value if nqp::isconcrete($value) && $cmp($value,$min) < 0; } $min // Inf; } proto method max (|) is nodal { * } multi method max() { my $elems = self.cache.elems; die "Cannot .max on an infinite list" if $elems == Inf; my $value; my $max; my int $todo = $elems; my int $index; self!first-concrete($index,$todo,$max); while nqp::islt_i($index,$todo) { $value := self.AT-POS($index); $index = $index + 1; $max = $value if nqp::isconcrete($value) && $value cmp $max > 0; } $max // -Inf; } multi method max(&by) { my $elems = self.cache.elems; die "Cannot .max on an infinite list" if $elems == Inf; my $cmp = &by.arity == 2 ?? &by !! { &by($^a) cmp &by($^b) } my $value; my $max; my int $todo = $elems; my int $index; self!first-concrete($index,$todo,$max); while nqp::islt_i($index,$todo) { $value := self.AT-POS($index); $index = $index + 1; $max = $value if nqp::isconcrete($value) && $cmp($value,$max) > 0; } $max // -Inf; } proto method minmax (|) is nodal { * } multi method minmax(&by = &infix:<cmp>) { my $cmp = &by.arity == 2 ?? &by !! { &by($^a) cmp &by($^b) }; my $min; my $max; my $excludes-min = Bool::False; my $excludes-max = Bool::False; self.map: { .defined or next; if .isa(Range) { if !$min.defined || $cmp($_.min, $min) < 0 { $min = .min; $excludes-min = $_.excludes-min; } if !$max.defined || $cmp($_.max, $max) > 0 { $max = .max; $excludes-max = $_.excludes-max; } } elsif Positional.ACCEPTS($_) { my $mm = .minmax(&by); if !$min.defined || $cmp($mm.min, $min) < 0 { $min = $mm.min; $excludes-min = $mm.excludes-min; } if !$max.defined || $cmp($mm.max, $max) > 0 { $max = $mm.max; $excludes-max = $mm.excludes-max; } } else { if !$min.defined || $cmp($_, $min) < 0 { $min = $_; $excludes-min = Bool::False; } if !$max.defined || $cmp($_, $max) > 0 { $max = $_; $excludes-max = Bool::False; } } } Range.new($min // Inf, $max // -Inf, :excludes-min($excludes-min), :excludes-max($excludes-max)); } method sort(&by = &infix:<cmp>) is nodal { # Obtain all the things to sort. my \iter = self.iterator; my \sort-buffer = IterationBuffer.new; unless iter.push-until-lazy(sort-buffer) =:= IterationEnd { fail X::Cannot::Lazy.new(:action<sort>); } # Apply any transform. my $transform = (&by.?count // 2) < 2; my $transform-buffer; if $transform { $transform-buffer := IterationBuffer.new; my \to-map = nqp::p6bindattrinvres(nqp::create(List), List, '$!reified', sort-buffer); to-map.map(&by).iterator.push-all($transform-buffer); } # Instead of sorting elements directly, we sort a list of # indices from 0..^$list.elems, then use that list as # a slice into self. The JVM implementation uses a Java # collection sort. MoarVM has its sort algorithm implemented # in NQP. my int $i = -1; my int $n = sort-buffer.elems; my $indices := nqp::list; nqp::setelems($indices,$n); nqp::bindpos($indices,$i,nqp::decont($i)) while ++$i < $n; nqp::p6sort($indices, $transform ?? (-> int $a, int $b { nqp::atpos($transform-buffer, $a) cmp nqp::atpos($transform-buffer, $b) || $a <=> $b }) !! (-> int $a, int $b { &by(nqp::atpos(sort-buffer, $a), nqp::atpos(sort-buffer, $b)) || $a <=> $b })); $i = -1; my $result := nqp::list; nqp::setelems($result,$n); nqp::bindpos($result,$i,nqp::atpos(sort-buffer,nqp::atpos($indices,$i))) while ++$i < $n; $result } proto method reduce(|) { * } multi method reduce(&with) is nodal { return unless self.DEFINITE; my $reducer := find-reducer-for-op(&with); $reducer(&with)(self) if $reducer; } proto method produce(|) { * } multi method produce(&with) is nodal { return unless self.DEFINITE; my $reducer := find-reducer-for-op(&with); $reducer(&with,1)(self) if $reducer; } proto method unique(|) is nodal {*} multi method unique() { Seq.new(class :: does Iterator { has Mu $!iter; has $!seen; method BUILD(\list) { $!iter = list.iterator; $!seen := nqp::hash(); self } method new(\list) { nqp::create(self).BUILD(list) } method pull-one() { my Mu $value; my str $needle; until ($value := $!iter.pull-one) =:= IterationEnd { $needle = nqp::unbox_s($value.WHICH); unless nqp::existskey($!seen, $needle) { nqp::bindkey($!seen, $needle, 1); return $value; } } IterationEnd } method push-exactly($target, int $n) { my Mu $value; my str $needle; my int $done; my $no-sink; while $done < $n { return IterationEnd if IterationEnd =:= ($value := $!iter.pull-one); $needle = nqp::unbox_s($value.WHICH); unless nqp::existskey($!seen, $needle) { nqp::bindkey($!seen, $needle, 1); $no-sink := $target.push($value); $done = $done + 1; } } $done } method push-all($target) { my Mu $value; my str $needle; my $no-sink; until ($value := $!iter.pull-one) =:= IterationEnd { $needle = nqp::unbox_s($value.WHICH); unless nqp::existskey($!seen, $needle) { nqp::bindkey($!seen, $needle, 1); $no-sink := $target.push($value); } } IterationEnd } }.new(self)) } multi method unique( :&as!, :&with! ) { my @seen; # should be Mu, but doesn't work in settings :-( my Mu $target; gather self.map: { $target = &as($_); if first( { with($target,$_) }, @seen ) =:= Nil { @seen.push($target); take $_; } }; } multi method unique( :&as! ) { Seq.new(class :: does Iterator { has Mu $!iter; has &!as; has $!seen; method BUILD(\list, &!as) { $!iter = list.iterator; $!seen := nqp::hash(); self } method new(\list, &as) { nqp::create(self).BUILD(list, &as) } method pull-one() { my Mu $value; my str $needle; until ($value := $!iter.pull-one) =:= IterationEnd { $needle = nqp::unbox_s(&!as($value).WHICH); unless nqp::existskey($!seen, $needle) { nqp::bindkey($!seen, $needle, 1); return $value; } } IterationEnd } method push-exactly($target, int $n) { my Mu $value; my str $needle; my int $done; my $no-sink; while $done < $n { return IterationEnd if IterationEnd =:= ($value := $!iter.pull-one); $needle = nqp::unbox_s(&!as($value).WHICH); unless nqp::existskey($!seen, $needle) { nqp::bindkey($!seen, $needle, 1); $no-sink := $target.push($value); $done = $done + 1; } } $done } method push-all($target) { my Mu $value; my str $needle; my $no-sink; until ($value := $!iter.pull-one) =:= IterationEnd { $needle = nqp::unbox_s(&!as($value).WHICH); unless nqp::existskey($!seen, $needle) { nqp::bindkey($!seen, $needle, 1); $no-sink := $target.push($value); } } IterationEnd } }.new(self, &as)) } multi method unique( :&with! ) { nextwith() if &with === &[===]; # use optimized version my @seen; # should be Mu, but doesn't work in settings :-( my Mu $target; gather self.map: { $target := $_; if first( { with($target,$_) }, @seen ) =:= Nil { @seen.push($target); take $_; } } } proto method repeated(|) is nodal {*} multi method repeated() { Seq.new(class :: does Iterator { has Mu $!iter; has $!seen; method BUILD(\list) { $!iter = list.iterator; $!seen := nqp::hash(); self } method new(\list) { nqp::create(self).BUILD(list) } method pull-one() { my Mu $value; my str $needle; until ($value := $!iter.pull-one) =:= IterationEnd { $needle = nqp::unbox_s($value.WHICH); nqp::existskey($!seen, $needle) ?? return $value !! nqp::bindkey($!seen, $needle, 1); } IterationEnd } method push-exactly($target, int $n) { my Mu $value; my str $needle; my int $done; my $no-sink; while $done < $n { return IterationEnd if IterationEnd =:= ($value := $!iter.pull-one); $needle = nqp::unbox_s($value.WHICH); if nqp::existskey($!seen, $needle) { $no-sink := $target.push($value); $done = $done + 1; } else { nqp::bindkey($!seen, $needle, 1); } } $done } method push-all($target) { my Mu $value; my str $needle; my $no-sink; until ($value := $!iter.pull-one) =:= IterationEnd { $needle = nqp::unbox_s($value.WHICH); nqp::existskey($!seen, $needle) ?? ($no-sink := $target.push($value)) !! nqp::bindkey($!seen, $needle, 1); } IterationEnd } }.new(self)) } multi method repeated( :&as!, :&with! ) { my @seen; # should be Mu, but doesn't work in settings :-( my Mu $target; gather self.map: { $target = &as($_); first( { with($target,$_) }, @seen ) =:= Nil ?? @seen.push($target) !! take $_; }; } multi method repeated( :&as! ) { Seq.new(class :: does Iterator { has Mu $!iter; has &!as; has $!seen; method BUILD(\list, &!as) { $!iter = list.iterator; $!seen := nqp::hash(); self } method new(\list, &as) { nqp::create(self).BUILD(list, &as) } method pull-one() { my Mu $value; my str $needle; until ($value := $!iter.pull-one) =:= IterationEnd { $needle = nqp::unbox_s(&!as($value).WHICH); nqp::existskey($!seen, $needle) ?? return $value !! nqp::bindkey($!seen, $needle, 1); } IterationEnd } method push-exactly($target, int $n) { my Mu $value; my str $needle; my int $done; my $no-sink; while $done < $n { return IterationEnd if IterationEnd =:= ($value := $!iter.pull-one); $needle = nqp::unbox_s(&!as($value).WHICH); if nqp::existskey($!seen, $needle) { $no-sink := $target.push($value); $done = $done + 1; } else { nqp::bindkey($!seen, $needle, 1); } } $done } method push-all($target) { my Mu $value; my str $needle; my $no-sink; until ($value := $!iter.pull-one) =:= IterationEnd { $needle = nqp::unbox_s(&!as($value).WHICH); nqp::existskey($!seen, $needle) ?? ($no-sink := $target.push($value)) !! nqp::bindkey($!seen, $needle, 1); } IterationEnd } }.new(self, &as)) } multi method repeated( :&with! ) { nextwith() if &with === &[===]; # use optimized version my @seen; # should be Mu, but doesn't work in settings :-( my Mu $target; gather self.map: { $target := $_; first( { with($target,$_) }, @seen ) =:= Nil ?? @seen.push($target) !! take $_; } } proto method squish(|) is nodal {*} multi method squish( :&as!, :&with = &[===] ) { Seq.new(class :: does Iterator { has Mu $!iter; has &!as; has &!with; has $!last; has int $!first; method BUILD(\list, &!as, &!with) { $!iter = list.iterator; $!first = 1; self } method new(\list, &as, &with) { nqp::create(self).BUILD(list, &as, &with) } method pull-one() { my Mu $value := $!iter.pull-one; my $which = &!as($value); if $!first { $!first = 0; } else { until IterationEnd =:= $value || !with($which,$!last) { $value := $!iter.pull-one; $which = &!as($value); } } $!last = $which; $value } method push-all($target) { my Mu $value := $!iter.pull-one; my $which = &!as($value); my $no-sink; if $!first { $!first = 0; unless IterationEnd =:= $value { $no-sink := $target.push($value); $!last = $which; $value := $!iter.pull-one; } } until IterationEnd =:= $value { $which = &!as($value); unless with($which,$!last) { $no-sink := $target.push($value); $!last = $which; } $value := $!iter.pull-one; } $value } }.new(self, &as, &with)) } multi method squish( :&with = &[===] ) { Seq.new(class :: does Iterator { has Mu $!iter; has &!with; has Mu $!last; has int $!first; method BUILD(\list, &!with) { $!iter = list.iterator; $!first = 1; self } method new(\list, &with) { nqp::create(self).BUILD(list, &with) } method pull-one() { my Mu $value := $!iter.pull-one; if $!first { $!first = 0; } else { $value := $!iter.pull-one until IterationEnd =:= $value || !with($value,$!last); } $!last = $value } method push-all($target) { my Mu $value := $!iter.pull-one; my $no-sink; if $!first { $!first = 0; unless IterationEnd =:= $value { $no-sink := $target.push($value); $!last = $value; $value := $!iter.pull-one; } } until IterationEnd =:= $value { unless with($value,$!last) { $no-sink := $target.push($value); $!last = $value; } $value := $!iter.pull-one; } $value } }.new(self, &with)) } proto method pairup(|) is nodal { * } multi method pairup(Any:U:) { () } multi method pairup(Any:D:) { my \iter = nqp::istype(self, Iterable) ?? self.iterator !! self.list.iterator; gather loop { my $it := iter.pull-one; if nqp::istype($it, Pair) { take $it.key => $it.value } elsif nqp::istype($it, Map) and !nqp::iscont($it) { take Slip.new(|$it.pairs) } elsif $it =:= IterationEnd { last } else { my $it-value := iter.pull-one; if $it-value =:= IterationEnd { X::Pairup::OddNumber.new.throw; } take $it => $it-value; } } } proto method head(|) { * } multi method head(Any:D: Int(Cool) $n = 1) { return () if $n <= 0; Seq.new( class :: does Iterator { has Mu $!iter; has int $!todo; method BUILD(\list,\todo) { $!iter = list.iterator; $!todo = todo; self } method new(\list,\todo) { nqp::create(self).BUILD(list,todo) } method pull-one() is raw { $!todo-- ?? $!iter.pull-one !! IterationEnd } }.new(self,$n)) } proto method tail(|) { * } multi method tail(Any:D: Int(Cool) $n = 1) { return () if $n <= 0; Seq.new( class :: does Iterator { has Mu $!iter; has Mu $!lastn; has int $!size; has int $!todo; has int $!index; method BUILD(\list,\size) { $!iter = list.iterator; X::Cannot::Lazy.new(:action<tail>).throw if $!iter.is-lazy; $!lastn := nqp::list; $!size = size; nqp::setelems($!lastn,$!size); # presize list nqp::setelems($!lastn,0); self } method new(\list,\size) { nqp::create(self).BUILD(list,size) } method !next() is raw { my int $index = $!index; $!index = ($!index + 1) % $!size; $!todo = $!todo - 1; nqp::atpos($!lastn,$index) } method pull-one() is raw { if $!todo { self!next; } elsif $!iter.DEFINITE { my Mu $pulled; my int $index; my int $size = $!size; until ($pulled := $!iter.pull-one) =:= IterationEnd { nqp::bindpos($!lastn,$index,$pulled); $index = ($index + 1) % $size; } if nqp::elems($!lastn) == $!size { # full set for tail $!index = $index; $!todo = $!size; } else { # not a full tail, $!index already 0 $!todo = nqp::elems($!lastn); } $!iter := Mu; # mark we're done iterating $!todo ?? self!next !! IterationEnd } else { IterationEnd } } }.new(self,$n)) } } BEGIN Attribute.^compose; proto sub infix:<min>(|) is pure { * } multi sub infix:<min>(Mu:D \a, Mu:U) { a } multi sub infix:<min>(Mu:U, Mu:D \b) { b } multi sub infix:<min>(Mu:D \a, Mu:D \b) { (a cmp b) < 0 ?? a !! b } multi sub infix:<min>(+args is raw) { args.min } sub min(+args, :&by = &infix:<cmp>) { args.min(&by) } proto sub infix:<max>(|) is pure { * } multi sub infix:<max>(Mu:D \a, Mu:U) { a } multi sub infix:<max>(Mu:U, Mu:D \b) { b } multi sub infix:<max>(Mu:D \a, Mu:D \b) { (a cmp b) > 0 ?? a !! b } multi sub infix:<max>(+args) { args.max } sub max(+args, :&by = &infix:<cmp>) { args.max(&by) } proto sub infix:<minmax>(|) is pure { * } multi sub infix:<minmax>(+args) { args.minmax } sub minmax(+args, :&by = &infix:<cmp>) { args.minmax(&by) } proto sub map(|) {*} multi sub map(&code, +values) { my $laze = values.is-lazy; values.map(&code).lazy-if($laze) } proto sub grep(|) {*} multi sub grep(Mu $test, +values, *%a) { my $laze = values.is-lazy; values.grep($test,|%a).lazy-if($laze) } multi sub grep(Bool:D $t, |) { fail X::Match::Bool.new( type => 'grep' ) } proto sub first(|) {*} multi sub first(Bool:D $t, |) { fail X::Match::Bool.new( type => 'first' ) } multi sub first(Mu $test, +values, *%a) { my $laze = values.is-lazy; values.first($test,|%a).lazy-if($laze) } proto sub join(|) { * } multi sub join($sep = '', *@values) { @values.join($sep) } proto sub reduce (|) { * } multi sub reduce (&with, +list) { list.reduce(&with) } proto sub produce (|) { * } multi sub produce (&with, +list) { list.produce(&with) } proto sub unique(|) { * } multi sub unique(+values, |c) { my $laze = values.is-lazy; values.unique(|c).lazy-if($laze) } proto sub squish(|) { * } multi sub squish(+values, |c) { my $laze = values.is-lazy; values.squish(|c).lazy-if($laze) } proto sub repeated(|) { * } multi sub repeated(+values, |c) { my $laze = values.is-lazy; values.repeated(|c).lazy-if($laze) } proto sub sort(|) {*} multi sub sort(@values) { @values.sort } multi sub sort($cmp, +values) { nqp::istype($cmp, Callable) ?? values.sort($cmp) !! (|$cmp,|values).sort; } # vim: ft=perl6 expandtab sw=4
/* * r360.Transformation is an utility class to perform simple point transformations through a 2d-matrix. */ r360.Transformation = function (a, b, c, d) { this._a = a; this._b = b; this._c = c; this._d = d; }; r360.Transformation.prototype = { transform: function (point, scale) { // (Point, Number) -> Point return this._transform(point.clone(), scale); }, // destructive transform (faster) _transform: function (point, scale) { scale = scale || 1; point.x = scale * (this._a * point.x + this._b); point.y = scale * (this._c * point.y + this._d); return point; }, untransform: function (point, scale) { scale = scale || 1; return new r360.Point( (point.x / scale - this._b) / this._a, (point.y / scale - this._d) / this._c); } };
var obj = {}; Object.defineProperty(obj, "property", { get: function() { return 11; }, configurable: false }); assert.throws(TypeError, function() { Object.defineProperty(obj, "property", { get: function() { return 12; }, configurable: true }); }); assert.sameValue(obj.property, 11, 'obj.property');
var f1 = { *m(x = 42) {} }.m; assert.sameValue(f1.length, 0, 'FormalsList: x = 42'); verifyNotEnumerable(f1, 'length'); verifyNotWritable(f1, 'length'); verifyConfigurable(f1, 'length'); var f2 = { *m(x = 42, y) {} }.m; assert.sameValue(f2.length, 0, 'FormalsList: x = 42, y'); verifyNotEnumerable(f2, 'length'); verifyNotWritable(f2, 'length'); verifyConfigurable(f2, 'length'); var f3 = { *m(x, y = 42) {} }.m; assert.sameValue(f3.length, 1, 'FormalsList: x, y = 42'); verifyNotEnumerable(f3, 'length'); verifyNotWritable(f3, 'length'); verifyConfigurable(f3, 'length'); var f4 = { *m(x, y = 42, z) {} }.m; assert.sameValue(f4.length, 1, 'FormalsList: x, y = 42, z'); verifyNotEnumerable(f4, 'length'); verifyNotWritable(f4, 'length'); verifyConfigurable(f4, 'length')
# The figure produced by this code is published in the textbook # "Statistics, Data Mining, and Machine Learning in Astronomy" (2013) # To report a bug or issue, use the following forum: import numpy as np from matplotlib import pyplot as plt from astroML.fourier import FT_continuous, IFT_continuous, sinegauss # This function adjusts matplotlib settings for a uniform feel in the textbook. # Note that with usetex=True, fonts are rendered with LaTeX. This may # result in an error if LaTeX is not installed on your system. In that case, # you can set usetex to False. from astroML.plotting import setup_text_plots setup_text_plots(fontsize=8, usetex=True) # Set up the wavelets t0 = 0 t = np.linspace(-0.4, 0.4, 10000) f0 = np.array([5, 5, 10, 10]) Q = np.array([1, 0.5, 1, 0.5]) # compute wavelets all at once W = sinegauss(t, t0, f0[:, None], Q[:, None]) # Plot the wavelets fig = plt.figure(figsize=(5, 3.75)) fig.subplots_adjust(hspace=0.05, wspace=0.05) # in each panel, plot and label a different wavelet for i in range(4): ax = fig.add_subplot(221 + i) ax.plot(t, W[i].real, '-k') ax.plot(t, W[i].imag, '--k') ax.text(0.04, 0.95, "$f_0 = %i$\n$Q = %.1f$" % (f0[i], Q[i]), ha='left', va='top', transform=ax.transAxes) ax.set_ylim(-1.2, 1.2) ax.set_xlim(-0.35, 0.35) ax.xaxis.set_major_locator(plt.MultipleLocator(0.2)) if i in (0, 1): ax.xaxis.set_major_formatter(plt.NullFormatter()) else: ax.set_xlabel('$t$') if i in (1, 3): ax.yaxis.set_major_formatter(plt.NullFormatter()) else: ax.set_ylabel('$w(t)$') plt.show()
assert.throws(RangeError, function() { BigInt(Infinity); }); var calls = 0; var obj = { valueOf: function() { calls++; return Infinity; } } assert.throws(RangeError, function() { BigInt(obj); }); assert.sameValue(calls, 1, "it fails after fetching the primitive value");
#ifndef <API key> #define <API key> EFI_STATUS GetOpRomInfo ( IN PCI_IO_DEVICE *PciIoDevice ) /*++ Routine Description: TODO: Add function description Arguments: PciIoDevice - TODO: add argument description Returns: TODO: add return values --*/ ; EFI_STATUS LoadOpRomImage ( IN PCI_IO_DEVICE *PciDevice, IN UINT64 ReservedMemoryBase ) /*++ Routine Description: TODO: Add function description Arguments: PciDevice - TODO: add argument description RomBase - TODO: add argument description Returns: TODO: add return values --*/ ; EFI_STATUS ProcessOpRomImage ( PCI_IO_DEVICE *PciDevice ) /*++ Routine Description: TODO: Add function description Arguments: PciDevice - TODO: add argument description Returns: TODO: add return values --*/ ; #endif
# OpenDNSSEC version specific parameters VERSION=`$INSTALL_ROOT/sbin/ods-enforcerd -V 2>&1 | grep 2.0.0` if ( [ -z "$VERSION" ] ); then export OPENDNSSEC_VERSION=1 export ENFORCER="ods-enforcerd -1 -d" export KSM_UTIL=bin/ods-ksmutil export XML_ARGS="--no-xml" else export OPENDNSSEC_VERSION=2 export ENFORCER="ods-enforcer enforce" export ENFORCERD="ods-enforcerd" export KSM_UTIL=sbin/ods-enforcer export XML_ARGS="" fi export RESULTS_TITLE="number of zones,time to add,wait for enforcer,keylist" # Check the value of the STATUS variable # Takes 2 parameters: a text string to indicate what failed # and a flag q to indicate quiet i.e. don't print test passed messages check_status() { if ( [ $STATUS -ne 0 ] ) ; then echo "******** TEST $1 FAILED ********" exit $STATUS else [ x$2 != "xq" ] && echo "******** TEST $1 PASSED ********" fi } # calculate the runtime between $MYSTART and $MYEND which are # expressed in nanoseconds and convert to seconds with 3 decimal places. calc_runtime() { # dc is RPN Calculator RUN=`echo "3k $MYEND $MYSTART - 1000000000 / p" | dc ` } test_enforcer() { echo "******** TESTING ENFORCER ********" >> $DEBUG_OUTPUT 2>&1 MYSTART=`date +%s%N` if ( [ x$1 == "xp" ] ) ; then /usr/bin/valgrind --tool=callgrind $INSTALL_ROOT/sbin/$ENFORCER >> $DEBUG_OUTPUT 2>&1 STATUS=$? check_status test_enforcer q else $INSTALL_ROOT/sbin/$ENFORCER >> $DEBUG_OUTPUT 2>&1 STATUS=$? check_status test_enforcer q fi MYEND=`date +%s%N` calc_runtime } test_keylist() { echo "******** TESTING KEYLIST ********" >> $DEBUG_OUTPUT 2>&1 MYSTART=`date +%s%N` $INSTALL_ROOT/$KSM_UTIL key list --verbose >> $DEBUG_OUTPUT 2>&1 STATUS=$? check_status test_keylist q MYEND=`date +%s%N` calc_runtime } test_key_rollover() { echo "******** TESTING KEY ROLLOVER ********" >> $DEBUG_OUTPUT 2>&1 MYSTART=`date +%s%N` echo "y" | $INSTALL_ROOT/$KSM_UTIL key rollover --policy default --keytype ZSK >> $DEBUG_OUTPUT 2>&1 STATUS=$? check_status test_key_rollover q MYEND=`date +%s%N` calc_runtime } <API key>() { echo "******** TIMING ZONE LIST EXPORT ********" >> $DEBUG_OUTPUT 2>&1 MYSTART=`date +%s%N` $INSTALL_ROOT/$KSM_UTIL zonelist export > $INSTALL_ROOT/etc/opendnssec/zonelist.xml STATUS=$? check_status <API key> q MYEND=`date +%s%N` calc_runtime } #<API key>() { # if ! log_this_timeout <API key> $<API key> /usr/bin/valgrind --tool=callgrind $INSTALL_ROOT/sbin/$ENFORCERD ; then # echo "<API key>: ERROR: Could not start ods-enforcerd. Exiting..." >&2 # return 1 # return 0
var thenResult = {}; var Thenable = function() {}; Thenable.prototype.then = function() { return thenResult; }; assert.sameValue( Promise.prototype.finally.call(new Thenable()), thenResult );
<?php class mysql5_constraint extends sql99_constraint { public static function <API key>($node_table) { return "PRIMARY"; } /** * create SQL To create the constraint passed in the $constraint array * * @return string */ public static function get_constraint_sql($constraint, $with_alter_table=TRUE) { if ( ! is_array($constraint) ) { throw new exception("constraint is not an array?"); } if ( strlen($constraint['table_name']) == 0 ) { var_dump(array_keys($constraint)); throw new exception("table_name is blank"); } switch ( strtoupper($constraint['type']) ) { case 'CHECK': // @TODO: Implement compatibility dbsteward::warning("Ignoring constraint '{$constraint['name']}' on table '{$constraint['table_name']}' because MySQL doesn't support the CHECK constraint"); return "-- Ignoring constraint '{$constraint['name']}' on table '{$constraint['table_name']}' because MySQL doesn't support the CHECK constraint"; break; case 'PRIMARY KEY': $sql = ''; if ($with_alter_table) { $sql .= "ALTER TABLE " . mysql5::<API key>($constraint['schema_name'], $constraint['table_name']) . " "; } $sql .= "ADD PRIMARY KEY " . $constraint['definition']; if ($with_alter_table) { $sql .= ";"; } return $sql; break; case 'FOREIGN KEY': // MySQL considers foreign keys to be a constraint constraining an index // naming the FK index and not the constraint (... ADD FOREIGN KEY name ...) results in the named index and an implicitly named constraint being created // naming the constraint and not the index (... ADD CONSTRAINT name FOREIGN KEY ...) results in both the index and constraint having the same name $constraint_name = mysql5::<API key>($constraint['name']); $index_name = !empty($constraint['foreignIndexName']) ? mysql5::<API key>($constraint['foreignIndexName']) : $constraint_name; $sql = ''; if ($with_alter_table) { $sql .= "ALTER TABLE " . mysql5::<API key>($constraint['schema_name'], $constraint['table_name']) . " "; } $sql .= "ADD CONSTRAINT "; $sql .= "$constraint_name FOREIGN KEY $index_name {$constraint['definition']}"; // FOREIGN KEY ON DELETE / ON UPDATE handling if ( strcasecmp($constraint['type'], 'FOREIGN KEY') == 0 && !empty($constraint['foreignOnDelete']) ) { $sql .= " ON DELETE " . self::<API key>($constraint['foreignOnDelete']); } if ( strcasecmp($constraint['type'], 'FOREIGN KEY') == 0 && !empty($constraint['foreignOnUpdate']) ) { $sql .= " ON UPDATE " . self::<API key>($constraint['foreignOnUpdate']); } if ($with_alter_table) { $sql .= ";"; } return $sql; break; case 'UNIQUE': $sql = ''; if ($with_alter_table) { $sql .= "ALTER TABLE " . mysql5::<API key>($constraint['schema_name'], $constraint['table_name']) . " "; } $sql .= "ADD UNIQUE INDEX "; $sql .= mysql5::<API key>($constraint['name']) . " {$constraint['definition']}"; if ($with_alter_table) { $sql .= ";"; } return $sql; default: // we shouldn't actually ever get here. throw new Exception("Unimplemented MySQL constraint {$constraint['type']}"); } } public static function <API key>($ref_opt) { // @TODO: "SET DEFAULT" is not supported by mysql return strtoupper(str_replace('_',' ',$ref_opt)); } public static function <API key>($constraint, $with_alter_table = TRUE) { if ( ! is_array($constraint) ) { throw new exception("constraint is not an array?"); } if ( strlen($constraint['table_name']) == 0 ) { var_dump(array_keys($constraint)); throw new exception("table_name is blank"); } // because MySQL refuses to have consistent syntax switch ( strtoupper($constraint['type']) ) { case 'CHECK': // @TODO: Implement compatibility dbsteward::warning("Not dropping constraint '{$constraint['name']}' on table '{$constraint['table_name']}' because MySQL doesn't support the CHECK constraint"); return "-- Not dropping constraint '{$constraint['name']}' on table '{$constraint['table_name']}' because MySQL doesn't support the CHECK constraint"; break; case 'UNIQUE': $drop = "INDEX " . mysql5::<API key>($constraint['name']); break; case 'PRIMARY KEY': $drop = "PRIMARY KEY"; break; case 'FOREIGN KEY': $drop = "FOREIGN KEY " . mysql5::<API key>($constraint['name']); break; case 'KEY': $drop = "KEY " . mysql5::<API key>($constraint['name']); break; default: // we shouldn't actually ever get here. throw new Exception("Unimplemented MySQL constraint {$constraint['type']}"); } $sql = ''; if ($with_alter_table) { $sql .= "ALTER TABLE " . mysql5::<API key>($constraint['schema_name'], $constraint['table_name']) . " "; } $sql .= "DROP $drop"; if ($with_alter_table) { $sql .= ";"; } return $sql; } }
class Libgeotiff < Formula desc "Library and tools for dealing with GeoTIFF" homepage "https://github.com/OSGeo/libgeotiff" url "https://github.com/OSGeo/libgeotiff/releases/download/1.7.0/libgeotiff-1.7.0.tar.gz" sha256 "<SHA256-like>" license "MIT" livecheck do url :stable regex(/^v?(\d+(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any, arm64_big_sur: "<SHA256-like>" sha256 cellar: :any, big_sur: "<SHA256-like>" sha256 cellar: :any, catalina: "<SHA256-like>" sha256 cellar: :any, mojave: "<SHA256-like>" sha256 cellar: :any_skip_relocation, x86_64_linux: "<SHA256-like>" end head do url "https://github.com/OSGeo/libgeotiff.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "jpeg" depends_on "libtiff" depends_on "proj@7" def install system "./autogen.sh" if build.head? system "./configure", "--<API key>", "--prefix=#{prefix}", "--with-jpeg" system "make" # Separate steps or install fails system "make", "install" end test do (testpath/"test.c").write <<~EOS #include "geotiffio.h" #include "xtiffio.h" #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { TIFF *tif = XTIFFOpen(argv[1], "w"); GTIF *gtif = GTIFNew(tif); TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (uint32) 10); GTIFKeySet(gtif, <API key>, TYPE_DOUBLE, 1, (double)123.456); int i; char buffer[20L]; memset(buffer,0,(size_t)20L); for (i=0;i<20L;i++){ TIFFWriteScanline(tif, buffer, i, 0); } GTIFWriteKeys(gtif); GTIFFree(gtif); XTIFFClose(tif); return 0; } EOS system ENV.cc, "test.c", "-I#{include}", "-L#{lib}", "-lgeotiff", "-L#{Formula["libtiff"].opt_lib}", "-ltiff", "-o", "test" system "./test", "test.tif" output = shell_output("#{bin}/listgeo test.tif") assert_match(/<API key>.*123.456/, output) end end
package net.runelite.api.events; import lombok.Data; import net.runelite.api.GameState; @Data public class GameStateChanged { private GameState gameState; }
#include "common.h" #include "bgfx_utils.h" #include <imgui/imgui.h> namespace { struct <API key> { float m_x; float m_y; float m_z; uint32_t m_tangent; uint32_t m_bitangent; float m_u; float m_v; static void init() { ms_decl .begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true) .add(bgfx::Attrib::Bitangent, 4, bgfx::AttribType::Uint8, true, true) .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float, true, true) .end(); } static bgfx::VertexDecl ms_decl; }; bgfx::VertexDecl <API key>::ms_decl; uint32_t packUint32(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) { union { uint32_t ui32; uint8_t arr[4]; } un; un.arr[0] = _x; un.arr[1] = _y; un.arr[2] = _z; un.arr[3] = _w; return un.ui32; } uint32_t packF4u(float _x, float _y = 0.0f, float _z = 0.0f, float _w = 0.0f) { const uint8_t xx = uint8_t(_x*127.0f + 128.0f); const uint8_t yy = uint8_t(_y*127.0f + 128.0f); const uint8_t zz = uint8_t(_z*127.0f + 128.0f); const uint8_t ww = uint8_t(_w*127.0f + 128.0f); return packUint32(xx, yy, zz, ww); } static <API key> s_cubeVertices[24] = { {-1, -1, 1, packF4u(-1, 0, 0), packF4u( 0, -1, 0), 1, 1 }, // Back { 1, 1, 1, packF4u(-1, 0, 0), packF4u( 0, -1, 0), 0, 0 }, {-1, 1, 1, packF4u(-1, 0, 0), packF4u( 0, -1, 0), 1, 0 }, { 1, -1, 1, packF4u(-1, 0, 0), packF4u( 0, -1, 0), 0, 1 }, {-1, -1, -1, packF4u( 1, 0, 0), packF4u( 0, -1, 0), 0, 1 }, // Front { 1, 1, -1, packF4u( 1, 0, 0), packF4u( 0, -1, 0), 1, 0 }, {-1, 1, -1, packF4u( 1, 0, 0), packF4u( 0, -1, 0), 0, 0 }, { 1, -1, -1, packF4u( 1, 0, 0), packF4u( 0, -1, 0), 1, 1 }, { 1, -1, -1, packF4u( 0, 0, 1), packF4u( 0, -1, 0), 0, 1 }, // Right { 1, 1, 1, packF4u( 0, 0, 1), packF4u( 0, -1, 0), 1, 0 }, { 1, -1, 1, packF4u( 0, 0, 1), packF4u( 0, -1, 0), 1, 1 }, { 1, 1, -1, packF4u( 0, 0, 1), packF4u( 0, -1, 0), 0, 0 }, {-1, -1, -1, packF4u( 0, 0, -1), packF4u( 0, -1, 0), 1, 1 }, // Left {-1, 1, 1, packF4u( 0, 0, -1), packF4u( 0, -1, 0), 0, 0 }, {-1, -1, 1, packF4u( 0, 0, -1), packF4u( 0, -1, 0), 0, 1 }, {-1, 1, -1, packF4u( 0, 0, -1), packF4u( 0, -1, 0), 1, 0 }, {-1, 1, -1, packF4u( 1, 0, 0), packF4u( 0, 0, -1), 0, 1 }, // Top { 1, 1, 1, packF4u( 1, 0, 0), packF4u( 0, 0, -1), 1, 0 }, {-1, 1, 1, packF4u( 1, 0, 0), packF4u( 0, 0, -1), 0, 0 }, { 1, 1, -1, packF4u( 1, 0, 0), packF4u( 0, 0, -1), 1, 1 }, {-1, -1, -1, packF4u( 1, 0, 0), packF4u( 0, 0, 1), 0, 0 }, // Bottom { 1, -1, 1, packF4u( 1, 0, 0), packF4u( 0, 0, 1), 1, 1 }, {-1, -1, 1, packF4u( 1, 0, 0), packF4u( 0, 0, 1), 0, 1 }, { 1, -1, -1, packF4u( 1, 0, 0), packF4u( 0, 0, 1), 1, 0 }, }; static const uint16_t s_cubeIndices[36] = { 0 , 1 , 2 , 0 , 3 , 1 , 4 , 6 , 5 , 4 , 5 , 7 , 8 , 9 , 10, 8 , 11, 9 , 12, 14, 13, 12, 13, 15, 16, 18, 17, 16, 17, 19, 20, 21, 22, 20, 23, 21, }; class ExamplePom : public entry::AppI { public: ExamplePom(const char* _name, const char* _description) : entry::AppI(_name, _description) { } void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override { Args args(_argc, _argv); m_width = _width; m_height = _height; m_debug = BGFX_DEBUG_NONE; m_reset = BGFX_RESET_VSYNC; bgfx::init(args.m_type, args.m_pciId); bgfx::reset(m_width, m_height, m_reset); // Enable debug text. bgfx::setDebug(m_debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); // Create vertex stream declaration. <API key>::init(); // Create static vertex buffer. m_vbh = bgfx::createVertexBuffer(bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ), <API key>::ms_decl); // Create static index buffer. m_ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) ); // Create texture sampler uniforms. s_texColor = bgfx::createUniform("s_texColor", bgfx::UniformType::Int1); s_texNormal = bgfx::createUniform("s_texNormal", bgfx::UniformType::Int1); s_texDepth = bgfx::createUniform("s_texDepth", bgfx::UniformType::Int1); u_light_pos = bgfx::createUniform("u_light_pos", bgfx::UniformType::Vec4); u_norm_mtx = bgfx::createUniform("u_norm_mtx", bgfx::UniformType::Mat4); u_pomParam = bgfx::createUniform("u_pomParam", bgfx::UniformType::Vec4); // Create program from shaders. m_program = loadProgram("vs_pom", "fs_pom"); // Load diffuse texture. m_textureColor = loadTexture("textures/parallax-d.ktx"); // Load normal texture. m_textureNormal = loadTexture("textures/parallax-n.ktx"); // Load depth texture. m_textureDepth = loadTexture("textures/parallax-h.ktx"); imguiCreate(); m_timeOffset = bx::getHPCounter(); m_shading_type = 4; <API key> = true; m_parallax_scale = 50; m_num_steps = 16; } virtual int shutdown() override { // Cleanup. bgfx::destroy(m_ibh); bgfx::destroy(m_vbh); bgfx::destroy(m_program); bgfx::destroy(m_textureColor); bgfx::destroy(m_textureNormal); bgfx::destroy(m_textureDepth); bgfx::destroy(s_texColor); bgfx::destroy(s_texNormal); bgfx::destroy(s_texDepth); bgfx::destroy(u_light_pos); bgfx::destroy(u_norm_mtx); bgfx::destroy(u_pomParam); imguiDestroy(); // Shutdown bgfx. bgfx::shutdown(); return 0; } bool update() override { if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) ) { // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) ); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::touch(0); int64_t now = bx::getHPCounter(); const double freq = double(bx::getHPFrequency() ); float time = (float)( (now-m_timeOffset)/freq); float at[3] = { 0.0f, 0.0f, 1.0f }; float eye[3] = { 0.0f, 0.0f, 0.0f }; // Set view and projection matrix for view 0. const bgfx::HMD* hmd = bgfx::getHMD(); if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) ) { float view[16]; bx::<API key>(view, hmd->eye[0].rotation, eye); bgfx::setViewTransform(0, view, hmd->eye[0].projection, BGFX_VIEW_STEREO, hmd->eye[1].projection); // Set view 0 default viewport. // Use HMD's width/height since HMD's internal frame buffer size // might be much larger than window size. bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height); } else { float view[16]; bx::mtxLookAt(view, eye, at); float proj[16]; bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth); bgfx::setViewTransform(0, view, proj); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) ); } imguiBeginFrame( m_mouseState.m_mx , m_mouseState.m_my , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0) , m_mouseState.m_mz , uint16_t(m_width) , uint16_t(m_height) ); showExampleDialog(this); ImGui::SetNextWindowPos( ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f) , <API key> ); ImGui::Begin("Settings" , NULL , ImVec2(m_width / 5.0f, m_height / 2.0f) , <API key> ); ImGui::RadioButton("No bump mapping", &m_shading_type, 0); ImGui::RadioButton("Normal mapping", &m_shading_type, 1); ImGui::RadioButton("Parallax mapping", &m_shading_type, 2); ImGui::RadioButton("Steep parallax mapping", &m_shading_type, 3); ImGui::RadioButton("Parallax occlusion mapping", &m_shading_type, 4); ImGui::Separator(); ImGui::Checkbox("Show diffuse texture", &<API key>); if (m_shading_type > 1) { ImGui::Separator(); float multiplier = 1000.0f; float x = (float)m_parallax_scale / multiplier; ImGui::SliderFloat("Parallax scale", &x, 0.0f, 0.1f); m_parallax_scale = (int32_t)(x * multiplier); } if (m_shading_type > 2) { ImGui::Separator(); ImGui::SliderInt("Number of steps", &m_num_steps, 1, 32); } ImGui::End(); imguiEndFrame(); float lightPos[4] = { 1.0f, 2.0f, 0.0f, 0.0f }; bgfx::setUniform(u_light_pos, lightPos); float a[16]; float b[16]; float c[16]; float d[16]; float mtx[16]; bx::mtxRotateY(a, time * 0.4f); bx::mtxRotateX(b, 0.4f); bx::mtxMul(c, a, b); bx::mtxTranslate(d, 0.0f, 0.0f, 4.0f); bx::mtxMul(mtx, c, d); // Set transform for draw call. bgfx::setTransform(mtx); float pomParam[4] = { float(m_shading_type), float(<API key>), float(m_parallax_scale), float(m_num_steps) }; bgfx::setUniform(u_pomParam, pomParam); // Set normal matrix uniform float inv[16]; float transpose[16]; bx::mtxInverse(inv, mtx); bx::mtxTranspose(transpose, inv); bgfx::setUniform(u_norm_mtx, transpose); // Set vertex and index buffer. bgfx::setVertexBuffer(0, m_vbh); bgfx::setIndexBuffer(m_ibh); // Bind textures. bgfx::setTexture(0, s_texColor, m_textureColor); bgfx::setTexture(1, s_texNormal, m_textureNormal); bgfx::setTexture(2, s_texDepth, m_textureDepth); // Set render states. bgfx::setState(0 | <API key> | <API key> | <API key> | <API key> | BGFX_STATE_MSAA ); // Submit primitive for rendering to view 0. bgfx::submit(0, m_program); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); return true; } return false; } bgfx::VertexBufferHandle m_vbh; bgfx::IndexBufferHandle m_ibh; bgfx::UniformHandle s_texColor; bgfx::UniformHandle s_texNormal; bgfx::UniformHandle s_texDepth; bgfx::UniformHandle u_light_pos; bgfx::UniformHandle u_norm_mtx; bgfx::UniformHandle u_pomParam; bgfx::ProgramHandle m_program; bgfx::TextureHandle m_textureColor; bgfx::TextureHandle m_textureNormal; bgfx::TextureHandle m_textureDepth; entry::MouseState m_mouseState; uint32_t m_width; uint32_t m_height; uint32_t m_debug; uint32_t m_reset; int64_t m_timeOffset; int32_t m_shading_type; bool <API key>; int32_t m_parallax_scale; int32_t m_num_steps; }; } // namespace <API key>(ExamplePom, "33-pom", "Parallax mapping.");
#ifdef __GNUC__ # pragma GCC diagnostic ignored "-<API key>" # if defined __clang__ || defined __APPLE__ # pragma GCC diagnostic ignored "-Wmissing-prototypes" # pragma GCC diagnostic ignored "-Wextra" # endif #endif #ifndef <API key> #define <API key> #include "opencv2/ts/ts.hpp" #include "opencv2/contrib/contrib.hpp" #include <iostream> #endif
#include <math.h> /* for round in coerceintval */ /* type-independent vector access primitives */ case ELM_FOREIGN: p=a->c.foreign.chars; /* no break*/ { /* (Fill seq item :start :end) */ seq->c.ivec.iv[start/64+i]=val; /*all zero or all one*/ seq->c.ivec.iv[start/32+i]=val; /*all zero or all one*/ { /* (MAP result-type function &rest seq) */ /*collect args*/ /* elt */ /* elt */ /* elt */ else error(E_SEQINDEX); /*list exhausted*/ else error(E_SEQINDEX); /*list exhausted*/ else error(E_SEQINDEX); /*list exhausted*/ if (testresult) /*duplicated!*/ break;} else error(E_SEQINDEX); /*list exhausted*/ else error(E_SEQINDEX); /*list exhausted*/ else error(E_SEQINDEX); /*list exhausted*/ /*replace vector elements in the first argument with the second argument*/ /* Bug: offset is ignored if vector is displaced to another array */ /*copy word by word*/ /*copy word by word*/ /*speed up for simple cases: calculate byte count*/ if (srcelmt==ELM_FOREIGN || destelmt==ELM_FOREIGN) /*copy byte by byte*/ /*coercion is required*/ /* extract src elements and place them on stack*/ if (islist(seq)) { /*sort list destructively*/ { register pointer a=argv[0]; /* (setelt seq index val) */
// are permitted provided that the following conditions are met: // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using Boo.Lang.Compiler.Ast; namespace Boo.Lang.Compiler.Steps { public class ContextAnnotations { private static readonly object EntryPointKey = new object(); private static readonly object AssemblyBuilderKey = new object(); private static readonly object AsyncKey = new object(); private static readonly object <API key> = new object(); private static readonly object FieldInvocationKey = new object(); public static Method GetEntryPoint(CompilerContext context) { if (null == context) { throw new <API key>("context"); } return (Method)context.Properties[EntryPointKey]; } public static void SetEntryPoint(CompilerContext context, Method method) { if (null == method) { throw new <API key>("method"); } Method current = GetEntryPoint(context); if (null != current) { throw <API key>.<API key>(method); } context.Properties[EntryPointKey] = method; } public static System.Reflection.Emit.AssemblyBuilder GetAssemblyBuilder(CompilerContext context) { System.Reflection.Emit.AssemblyBuilder builder = (System.Reflection.Emit.AssemblyBuilder)context.Properties[AssemblyBuilderKey]; if (null == builder) { throw <API key>.<API key>(context.CompileUnit); } return builder; } public static void SetAssemblyBuilder(CompilerContext context, System.Reflection.Emit.AssemblyBuilder builder) { if (null == context) { throw new <API key>("context"); } if (null == builder) { throw new <API key>("builder"); } context.Properties[AssemblyBuilderKey] = builder; } private ContextAnnotations() { } public static void MarkAsync(INodeWithBody node) { ((Node)node).Annotate(AsyncKey); } public static bool IsAsync(INodeWithBody node) { return ((Node) node).ContainsAnnotation(AsyncKey); } public static void <API key>(INodeWithBody node) { ((Node)node).Annotate(<API key>); } public static bool <API key>(INodeWithBody node) { return ((Node)node).ContainsAnnotation(<API key>); } public static void AddFieldInvocation(<API key> node) { var context = CompilerContext.Current; var list = context[FieldInvocationKey] as List<<API key>>; if (list == null) { list = new List<<API key>>(); context[FieldInvocationKey] = list; } list.Add(node); } public static List<<API key>> GetFieldInvocations() { var context = CompilerContext.Current; return context[FieldInvocationKey] as List<<API key>>; } } }
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/tinderbox/XR-Trunk/WINNT_5.2_Depend/mozilla/dom/public/idl/html/<API key>.idl */ #ifndef <API key> #define <API key> #ifndef <API key> #include "nsIDOMHTMLElement.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: <API key> */ #define <API key> "<API key>" #define <API key> \ {0xa6cf908b, 0x15b3, 0x11d2, \ { 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 }} class NS_NO_VTABLE NS_SCRIPTABLE <API key> : public nsIDOMHTMLElement { public: <API key>(<API key>) /* attribute DOMString href; */ NS_SCRIPTABLE NS_IMETHOD GetHref(nsAString & aHref) = 0; NS_SCRIPTABLE NS_IMETHOD SetHref(const nsAString & aHref) = 0; /* attribute DOMString target; */ NS_SCRIPTABLE NS_IMETHOD GetTarget(nsAString & aTarget) = 0; NS_SCRIPTABLE NS_IMETHOD SetTarget(const nsAString & aTarget) = 0; }; <API key>(<API key>, <API key>) /* Use this macro when declaring classes that implement this interface. */ #define <API key> \ NS_SCRIPTABLE NS_IMETHOD GetHref(nsAString & aHref); \ NS_SCRIPTABLE NS_IMETHOD SetHref(const nsAString & aHref); \ NS_SCRIPTABLE NS_IMETHOD GetTarget(nsAString & aTarget); \ NS_SCRIPTABLE NS_IMETHOD SetTarget(const nsAString & aTarget); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define <API key>(_to) \ NS_SCRIPTABLE NS_IMETHOD GetHref(nsAString & aHref) { return _to GetHref(aHref); } \ NS_SCRIPTABLE NS_IMETHOD SetHref(const nsAString & aHref) { return _to SetHref(aHref); } \ NS_SCRIPTABLE NS_IMETHOD GetTarget(nsAString & aTarget) { return _to GetTarget(aTarget); } \ NS_SCRIPTABLE NS_IMETHOD SetTarget(const nsAString & aTarget) { return _to SetTarget(aTarget); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define <API key>(_to) \ NS_SCRIPTABLE NS_IMETHOD GetHref(nsAString & aHref) { return !_to ? <API key> : _to->GetHref(aHref); } \ NS_SCRIPTABLE NS_IMETHOD SetHref(const nsAString & aHref) { return !_to ? <API key> : _to->SetHref(aHref); } \ NS_SCRIPTABLE NS_IMETHOD GetTarget(nsAString & aTarget) { return !_to ? <API key> : _to->GetTarget(aTarget); } \ NS_SCRIPTABLE NS_IMETHOD SetTarget(const nsAString & aTarget) { return !_to ? <API key> : _to->SetTarget(aTarget); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class <API key> : public <API key> { public: NS_DECL_ISUPPORTS <API key> <API key>(); private: ~<API key>(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(<API key>, <API key>) <API key>::<API key>() { /* member initializers and constructor code */ } <API key>::~<API key>() { /* destructor code */ } /* attribute DOMString href; */ NS_IMETHODIMP <API key>::GetHref(nsAString & aHref) { return <API key>; } NS_IMETHODIMP <API key>::SetHref(const nsAString & aHref) { return <API key>; } /* attribute DOMString target; */ NS_IMETHODIMP <API key>::GetTarget(nsAString & aTarget) { return <API key>; } NS_IMETHODIMP <API key>::SetTarget(const nsAString & aTarget) { return <API key>; } /* End of implementation class template. */ #endif #endif /* <API key> */
#include "core/layout/svg/LayoutSVGImage.h" #include "core/layout/HitTestResult.h" #include "core/layout/<API key>.h" #include "core/layout/LayoutAnalyzer.h" #include "core/layout/LayoutImageResource.h" #include "core/layout/<API key>.h" #include "core/layout/svg/<API key>.h" #include "core/layout/svg/SVGLayoutSupport.h" #include "core/layout/svg/SVGResources.h" #include "core/layout/svg/SVGResourcesCache.h" #include "core/paint/SVGImagePainter.h" #include "core/svg/SVGImageElement.h" #include "platform/LengthFunctions.h" #include "third_party/skia/include/core/SkPicture.h" namespace blink { LayoutSVGImage::LayoutSVGImage(SVGImageElement* impl) : <API key>(impl) , <API key>(true) , <API key>(true) , m_imageResource(LayoutImageResource::create()) { m_imageResource->initialize(this); } LayoutSVGImage::~LayoutSVGImage() { } void LayoutSVGImage::willBeDestroyed() { <API key>::remove(*this); m_imageResource->shutdown(); <API key>::willBeDestroyed(); } void LayoutSVGImage::updateBoundingBox() { FloatRect oldBoundaries = m_objectBoundingBox; SVGLengthContext lengthContext(element()); m_objectBoundingBox = FloatRect( lengthContext.valueForLength(styleRef().svgStyle().x(), styleRef(), SVGLengthMode::Width), lengthContext.valueForLength(styleRef().svgStyle().y(), styleRef(), SVGLengthMode::Height), lengthContext.valueForLength(styleRef().width(), styleRef(), SVGLengthMode::Width), lengthContext.valueForLength(styleRef().height(), styleRef(), SVGLengthMode::Height)); <API key> |= oldBoundaries != m_objectBoundingBox; } void LayoutSVGImage::layout() { ASSERT(needsLayout()); LayoutAnalyzer::Scope analyzer(*this); // Invalidate all resources of this client if our layout changed. if (everHadLayout() && selfNeedsLayout()) SVGResourcesCache::clientLayoutChanged(this); updateBoundingBox(); bool <API key> = false; if (<API key>) { m_localTransform = toSVGImageElement(element())-><API key>(); <API key> = false; <API key> = true; } if (<API key>) { <API key> = m_objectBoundingBox; SVGLayoutSupport::<API key>(this, <API key>); <API key> = false; <API key> = true; } // If our bounds changed, notify the parents. if (<API key>) <API key>::<API key>(); ASSERT(!<API key>); ASSERT(!<API key>); clearNeedsLayout(); } void LayoutSVGImage::paint(const PaintInfo& paintInfo, const LayoutPoint&) const { SVGImagePainter(*this).paint(paintInfo); } bool LayoutSVGImage::nodeAtFloatPoint(HitTestResult& result, const FloatPoint& pointInParent, HitTestAction hitTestAction) { // We only draw in the forground phase, so we only hit-test then. if (hitTestAction != HitTestForeground) return false; <API key> hitRules(<API key>::<API key>, result.hitTestRequest(), style()->pointerEvents()); bool isVisible = (style()->visibility() == VISIBLE); if (isVisible || !hitRules.requireVisible) { FloatPoint localPoint; if (!SVGLayoutSupport::<API key>(this, <API key>(), pointInParent, localPoint)) return false; if (hitRules.canHitFill || hitRules.canHitBoundingBox) { if (m_objectBoundingBox.contains(localPoint)) { const LayoutPoint& localLayoutPoint = roundedLayoutPoint(localPoint); updateHitTestResult(result, localLayoutPoint); if (result.<API key>(element(), localLayoutPoint) == StopHitTesting) return true; } } } return false; } void LayoutSVGImage::imageChanged(WrappedImagePtr, const IntRect*) { // Notify parent resources that we've changed. This also invalidates // references from resources (filters) that may have a cached // representation of this image/layout object. <API key>::<API key>(this, false); <API key>(); } void LayoutSVGImage::addOutlineRects(Vector<LayoutRect>& rects, const LayoutPoint&, <API key>) const { // this is called from paint() after the localTransform has already been applied rects.append(LayoutRect(<API key>())); } } // namespace blink
using System.Collections.Generic; using System.Threading.Tasks; using OrchardCore.Recipes.Models; namespace OrchardCore.Setup.Services { <summary> Contract that represents the setup service. </summary> public interface ISetupService { <summary> Gets the setup recipes. </summary> <returns>A list of <see cref="RecipeDescriptor"/>s.</returns> Task<IEnumerable<RecipeDescriptor>> <API key>(); <summary> Set up the tenant. </summary> <param name="context">The <see cref="SetupContext"/>.</param> <returns> A GUID string the represents a setup execution identifier.</returns> Task<string> SetupAsync(SetupContext context); } }
/** * @file <API key>.hpp * @author Sumedh Ghaisas * * SVD factorizer used in AMF (Alternating Matrix Factorization). */ #ifndef <API key> #define <API key> #include <mlpack/core.hpp> namespace mlpack { namespace amf { /** * This class computes SVD using complete incremental batch learning, as * described in the following paper: * * @code * @techreport{ma2008guide, * title={A Guide to Singular Value Decomposition for Collaborative * Filtering}, * author={Ma, Chih-Chao}, * year={2008}, * institution={Department of Computer Science, National Taiwan University} * } * @endcode * * This class implements 'Algorithm 3' given in the paper. Complete incremental * learning is an extreme case of incremental learning, where feature vectors * are updated after looking at each single element in the input matrix (V). * This approach differs from incomplete incremental learning where feature * vectors are updated after seeing columns of elements in the input matrix. * * @see <API key> */ template <class MatType> class <API key> { public: /** * Initialize the <API key> class with the given * parameters. * * @param u Step value used in batch learning. * @param kw Regularization constant for W matrix. * @param kh Regularization constant for H matrix. */ <API key>(double u = 0.0001, double kw = 0, double kh = 0) : u(u), kw(kw), kh(kh) { // Nothing to do. } /** * Initialize parameters before factorization. This function must be called * before a new factorization. For this initialization, the input parameters * are unnecessary; we are only setting the current element index to 0. * * @param dataset Input matrix to be factorized. * @param rank rank of factorization */ void Initialize(const MatType& /* dataset */, const size_t /* rank */) { // Initialize the current score counters. currentUserIndex = 0; currentItemIndex = 0; } /** * The update rule for the basis matrix W. The function takes in all the * matrices and only changes the value of the W matrix. * * @param V Input matrix to be factorized. * @param W Basis matrix to be updated. * @param H Encoding matrix. */ inline void WUpdate(const MatType& V, arma::mat& W, const arma::mat& H) { arma::mat deltaW; deltaW.zeros(1, W.n_cols); // Loop until a non-zero entry is found. while(true) { const double val = V(currentItemIndex, currentUserIndex); // Update feature vector if current entry is non-zero and break the loop. if (val != 0) { deltaW += (val - arma::dot(W.row(currentItemIndex), H.col(currentUserIndex))) * H.col(currentUserIndex).t(); // Add regularization. if (kw != 0) deltaW -= kw * W.row(currentItemIndex); break; } } W.row(currentItemIndex) += u * deltaW; } /** * The update rule for the encoding matrix H. * The function takes in all the matrices and only changes the * value of the H matrix. * * @param V Input matrix to be factorized. * @param W Basis matrix. * @param H Encoding matrix to be updated. */ inline void HUpdate(const MatType& V, const arma::mat& W, arma::mat& H) { arma::mat deltaH; deltaH.zeros(H.n_rows, 1); const double val = V(currentItemIndex, currentUserIndex); // Update H matrix based on the non-zero entry found in WUpdate function. deltaH += (val - arma::dot(W.row(currentItemIndex), H.col(currentUserIndex))) * W.row(currentItemIndex).t(); // Add regularization. if (kh != 0) deltaH -= kh * H.col(currentUserIndex); // Move on to the next entry. currentUserIndex = currentUserIndex + 1; if (currentUserIndex == V.n_rows) { currentUserIndex = 0; currentItemIndex = (currentItemIndex + 1) % V.n_cols; } H.col(currentUserIndex++) += u * deltaH; } private: //! Step count of batch learning. double u; //! Regularization parameter for matrix W. double kw; //! Regularization parameter for matrix H. double kh; //! User of index of current entry. size_t currentUserIndex; //! Item index of current entry. size_t currentItemIndex; }; //! TODO : Merge this template specialized function for sparse matrix using //! common row_col_iterator //! template specialiazed functions for sparse matrices template<> class <API key><arma::sp_mat> { public: <API key>(double u = 0.01, double kw = 0, double kh = 0) : u(u), kw(kw), kh(kh), it(NULL) {} ~<API key>() { delete it; } void Initialize(const arma::sp_mat& dataset, const size_t rank) { (void)rank; n = dataset.n_rows; m = dataset.n_cols; it = new arma::sp_mat::const_iterator(dataset.begin()); isStart = true; } /** * The update rule for the basis matrix W. * The function takes in all the matrices and only changes the * value of the W matrix. * * @param V Input matrix to be factorized. * @param W Basis matrix to be updated. * @param H Encoding matrix. */ inline void WUpdate(const arma::sp_mat& V, arma::mat& W, const arma::mat& H) { if(!isStart) (*it)++; else isStart = false; if(*it == V.end()) { delete it; it = new arma::sp_mat::const_iterator(V.begin()); } size_t currentUserIndex = it->col(); size_t currentItemIndex = it->row(); arma::mat deltaW(1, W.n_cols); deltaW.zeros(); deltaW += (**it - arma::dot(W.row(currentItemIndex), H.col(currentUserIndex))) * arma::trans(H.col(currentUserIndex)); if(kw != 0) deltaW -= kw * W.row(currentItemIndex); W.row(currentItemIndex) += u*deltaW; } /** * The update rule for the encoding matrix H. * The function takes in all the matrices and only changes the * value of the H matrix. * * @param V Input matrix to be factorized. * @param W Basis matrix. * @param H Encoding matrix to be updated. */ inline void HUpdate(const arma::sp_mat& V, const arma::mat& W, arma::mat& H) { (void)V; arma::mat deltaH(H.n_rows, 1); deltaH.zeros(); size_t currentUserIndex = it->col(); size_t currentItemIndex = it->row(); deltaH += (**it - arma::dot(W.row(currentItemIndex), H.col(currentUserIndex))) * arma::trans(W.row(currentItemIndex)); if(kh != 0) deltaH -= kh * H.col(currentUserIndex); H.col(currentUserIndex) += u * deltaH; } private: double u; double kw; double kh; size_t n; size_t m; arma::sp_mat dummy; arma::sp_mat::const_iterator* it; bool isStart; }; // class <API key> } // namespace amf } // namespace mlpack #endif
#ifndef GrMtlCaps_DEFINED #define GrMtlCaps_DEFINED #include "GrCaps.h" #include "<API key>.h" #include "SkTDArray.h" #import <Metal/Metal.h> class GrShaderCaps; /** * Stores some capabilities of a Mtl backend. */ class GrMtlCaps : public GrCaps { public: typedef <API key>::Format StencilFormat; GrMtlCaps(const GrContextOptions& contextOptions, id<MTLDevice> device, MTLFeatureSet featureSet); bool isConfigTexturable(GrPixelConfig config) const override { return SkToBool(fConfigTable[config].fFlags & ConfigInfo::kTextureable_Flag); } int <API key>(int requestedCount, GrPixelConfig) const override; int <API key>(GrPixelConfig) const override; bool <API key>(const GrSurface*) const override { return true; } bool isConfigCopyable(GrPixelConfig config) const override { return true; } /** * Returns both a supported and most prefered stencil format to use in draws. */ const StencilFormat& <API key>() const { return <API key>; } bool canCopyAsBlit(GrPixelConfig dstConfig, int dstSampleCount, GrSurfaceOrigin dstOrigin, GrPixelConfig srcConfig, int srcSampleCount, GrSurfaceOrigin srcOrigin, const SkIRect& srcRect, const SkIPoint& dstPoint, bool areDstSrcSameObj) const; bool canCopyAsDraw(GrPixelConfig dstConfig, bool dstIsRenderable, GrPixelConfig srcConfig, bool srcIsTextureable) const; bool <API key>(GrPixelConfig dstConfig, GrPixelConfig srcConfig, bool srcIsTextureable) const; bool initDescForDstCopy(const GrRenderTargetProxy* src, GrSurfaceDesc* desc, GrSurfaceOrigin*, bool* rectsMustMatch, bool* disallowSubrect) const override { return false; } GrPixelConfig <API key>(const <API key>&, SkColorType) const override; GrPixelConfig <API key>(const GrBackendFormat&, SkColorType) const override; GrPixelConfig <API key>(const GrBackendFormat&) const override; GrBackendFormat <API key>(GrColorType ct, GrSRGBEncoded srgbEncoded) const override; private: void initFeatureSet(MTLFeatureSet featureSet); void initStencilFormat(const id<MTLDevice> device); void initGrCaps(const id<MTLDevice> device); void initShaderCaps(); void initConfigTable(); bool <API key>(const GrSurface*) const override { return true; } bool onCanCopySurface(const GrSurfaceProxy* dst, const GrSurfaceProxy* src, const SkIRect& srcRect, const SkIPoint& dstPoint) const override; struct ConfigInfo { ConfigInfo() : fFlags(0) {} enum { kTextureable_Flag = 0x1, kRenderable_Flag = 0x2, // Color attachment and blendable kMSAA_Flag = 0x4, kResolve_Flag = 0x8, }; // TODO: Put kMSAA_Flag back when MSAA is implemented static const uint16_t kAllFlags = kTextureable_Flag | kRenderable_Flag | /*kMSAA_Flag |*/ kResolve_Flag; uint16_t fFlags; }; ConfigInfo fConfigTable[kGrPixelConfigCnt]; enum class Platform { kMac, kIOS }; bool isMac() { return Platform::kMac == fPlatform; } bool isIOS() { return Platform::kIOS == fPlatform; } Platform fPlatform; int fFamilyGroup; int fVersion; SkTDArray<int> fSampleCounts; StencilFormat <API key>; typedef GrCaps INHERITED; }; #endif
#include "FLA_f2c.h" /* Table of constant values */ static doublereal c_b5 = -1.; static integer c__1 = 1; static doublereal c_b11 = 1.; static doublereal c_b13 = 0.; static integer c__0 = 0; /* > \brief \b DLALS0 applies back multiplying factors in solving the least squares problem using divide and c onquer SVD approach. Used by sgelsd. */ /* Online html documentation available at */ /* > \htmlonly */ /* > Download DLALS0 + dependencies */ /* > [TGZ]</a> */ /* > [ZIP]</a> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* SUBROUTINE DLALS0( ICOMPQ, NL, NR, SQRE, NRHS, B, LDB, BX, LDBX, */ /* PERM, GIVPTR, GIVCOL, LDGCOL, GIVNUM, LDGNUM, */ /* POLES, DIFL, DIFR, Z, K, C, S, WORK, INFO ) */ /* .. Scalar Arguments .. */ /* INTEGER GIVPTR, ICOMPQ, INFO, K, LDB, LDBX, LDGCOL, */ /* $ LDGNUM, NL, NR, NRHS, SQRE */ /* DOUBLE PRECISION C, S */ /* .. Array Arguments .. */ /* INTEGER GIVCOL( LDGCOL, * ), PERM( * ) */ /* DOUBLE PRECISION B( LDB, * ), BX( LDBX, * ), DIFL( * ), */ /* $ DIFR( LDGNUM, * ), GIVNUM( LDGNUM, * ), */ /* $ POLES( LDGNUM, * ), WORK( * ), Z( * ) */ /* > \par Purpose: */ /* > \verbatim */ /* > DLALS0 applies back the multiplying factors of either the left or the */ /* > right singular vector matrix of a diagonal matrix appended by a row */ /* > to the right hand side matrix B in solving the least squares problem */ /* > using the divide-and-conquer SVD approach. */ /* > For the left singular vector matrix, three types of orthogonal */ /* > matrices are involved: */ /* > (1L) Givens rotations: the number of such rotations is GIVPTR; the */ /* > pairs of columns/rows they were applied to are stored in GIVCOL; */ /* > and the C- and S-values of these rotations are stored in GIVNUM. */ /* > (2L) Permutation. The (NL+1)-st row of B is to be moved to the first */ /* > row, and for J=2:N, PERM(J)-th row of B is to be moved to the */ /* > J-th row. */ /* > (3L) The left singular vector matrix of the remaining matrix. */ /* > For the right singular vector matrix, four types of orthogonal */ /* > matrices are involved: */ /* > (1R) The right singular vector matrix of the remaining matrix. */ /* > (2R) If SQRE = 1, one extra Givens rotation to generate the right */ /* > null space. */ /* > (3R) The inverse transformation of (2L). */ /* > (4R) The inverse transformation of (1L). */ /* > \endverbatim */ /* Arguments: */ /* > \param[in] ICOMPQ */ /* > \verbatim */ /* > ICOMPQ is INTEGER */ /* > Specifies whether singular vectors are to be computed in */ /* > factored form: */ /* > = 0: Left singular vector matrix. */ /* > = 1: Right singular vector matrix. */ /* > \endverbatim */ /* > \param[in] NL */ /* > \verbatim */ /* > NL is INTEGER */ /* > The row dimension of the upper block. NL >= 1. */ /* > \endverbatim */ /* > \param[in] NR */ /* > \verbatim */ /* > NR is INTEGER */ /* > The row dimension of the lower block. NR >= 1. */ /* > \endverbatim */ /* > \param[in] SQRE */ /* > \verbatim */ /* > SQRE is INTEGER */ /* > = 0: the lower block is an NR-by-NR square matrix. */ /* > = 1: the lower block is an NR-by-(NR+1) rectangular matrix. */ /* > The bidiagonal matrix has row dimension N = NL + NR + 1, */ /* > and column dimension M = N + SQRE. */ /* > \endverbatim */ /* > \param[in] NRHS */ /* > \verbatim */ /* > NRHS is INTEGER */ /* > The number of columns of B and BX. NRHS must be at least 1. */ /* > \endverbatim */ /* > \param[in,out] B */ /* > \verbatim */ /* > B is DOUBLE PRECISION array, dimension ( LDB, NRHS ) */ /* > On input, B contains the right hand sides of the least */ /* > squares problem in rows 1 through M. On output, B contains */ /* > the solution X in rows 1 through N. */ /* > \endverbatim */ /* > \param[in] LDB */ /* > \verbatim */ /* > LDB is INTEGER */ /* > The leading dimension of B. LDB must be at least */ /* > max(1,MAX( M, N ) ). */ /* > \endverbatim */ /* > \param[out] BX */ /* > \verbatim */ /* > BX is DOUBLE PRECISION array, dimension ( LDBX, NRHS ) */ /* > \endverbatim */ /* > \param[in] LDBX */ /* > \verbatim */ /* > LDBX is INTEGER */ /* > The leading dimension of BX. */ /* > \endverbatim */ /* > \param[in] PERM */ /* > \verbatim */ /* > PERM is INTEGER array, dimension ( N ) */ /* > The permutations (from deflation and sorting) applied */ /* > to the two blocks. */ /* > \endverbatim */ /* > \param[in] GIVPTR */ /* > \verbatim */ /* > GIVPTR is INTEGER */ /* > The number of Givens rotations which took place in this */ /* > subproblem. */ /* > \endverbatim */ /* > \param[in] GIVCOL */ /* > \verbatim */ /* > GIVCOL is INTEGER array, dimension ( LDGCOL, 2 ) */ /* > Each pair of numbers indicates a pair of rows/columns */ /* > involved in a Givens rotation. */ /* > \endverbatim */ /* > \param[in] LDGCOL */ /* > \verbatim */ /* > LDGCOL is INTEGER */ /* > The leading dimension of GIVCOL, must be at least N. */ /* > \endverbatim */ /* > \param[in] GIVNUM */ /* > \verbatim */ /* > GIVNUM is DOUBLE PRECISION array, dimension ( LDGNUM, 2 ) */ /* > Each number indicates the C or S value used in the */ /* > corresponding Givens rotation. */ /* > \endverbatim */ /* > \param[in] LDGNUM */ /* > \verbatim */ /* > LDGNUM is INTEGER */ /* > The leading dimension of arrays DIFR, POLES and */ /* > GIVNUM, must be at least K. */ /* > \endverbatim */ /* > \param[in] POLES */ /* > \verbatim */ /* > POLES is DOUBLE PRECISION array, dimension ( LDGNUM, 2 ) */ /* > On entry, POLES(1:K, 1) contains the new singular */ /* > values obtained from solving the secular equation, and */ /* > POLES(1:K, 2) is an array containing the poles in the secular */ /* > equation. */ /* > \endverbatim */ /* > \param[in] DIFL */ /* > \verbatim */ /* > DIFL is DOUBLE PRECISION array, dimension ( K ). */ /* > On entry, DIFL(I) is the distance between I-th updated */ /* > (undeflated) singular value and the I-th (undeflated) old */ /* > singular value. */ /* > \endverbatim */ /* > \param[in] DIFR */ /* > \verbatim */ /* > DIFR is DOUBLE PRECISION array, dimension ( LDGNUM, 2 ). */ /* > On entry, DIFR(I, 1) contains the distances between I-th */ /* > updated (undeflated) singular value and the I+1-th */ /* > (undeflated) old singular value. And DIFR(I, 2) is the */ /* > normalizing factor for the I-th right singular vector. */ /* > \endverbatim */ /* > \param[in] Z */ /* > \verbatim */ /* > Z is DOUBLE PRECISION array, dimension ( K ) */ /* > Contain the components of the deflation-adjusted updating row */ /* > vector. */ /* > \endverbatim */ /* > \param[in] K */ /* > \verbatim */ /* > K is INTEGER */ /* > Contains the dimension of the non-deflated matrix, */ /* > This is the order of the related secular equation. 1 <= K <=N. */ /* > \endverbatim */ /* > \param[in] C */ /* > \verbatim */ /* > C is DOUBLE PRECISION */ /* > C contains garbage if SQRE =0 and the C-value of a Givens */ /* > rotation related to the right null space if SQRE = 1. */ /* > \endverbatim */ /* > \param[in] S */ /* > \verbatim */ /* > S is DOUBLE PRECISION */ /* > S contains garbage if SQRE =0 and the S-value of a Givens */ /* > rotation related to the right null space if SQRE = 1. */ /* > \endverbatim */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is DOUBLE PRECISION array, dimension ( K ) */ /* > \endverbatim */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit. */ /* > \endverbatim */ /* Authors: */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date September 2012 */ /* > \ingroup <API key> */ /* > \par Contributors: */ /* > Ming Gu and Ren-Cang Li, Computer Science Division, University of */ /* > California at Berkeley, USA \n */ /* > Osni Marques, LBNL/NERSC, USA \n */ /* Subroutine */ int dlals0_(integer *icompq, integer *nl, integer *nr, integer *sqre, integer *nrhs, doublereal *b, integer *ldb, doublereal *bx, integer *ldbx, integer *perm, integer *givptr, integer *givcol, integer *ldgcol, doublereal *givnum, integer *ldgnum, doublereal * poles, doublereal *difl, doublereal *difr, doublereal *z__, integer * k, doublereal *c__, doublereal *s, doublereal *work, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, b_dim1, b_offset, bx_dim1, bx_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, i__1, i__2; doublereal d__1; /* Local variables */ integer i__, j, m, n; doublereal dj; integer nlp1; doublereal temp; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *); extern doublereal dnrm2_(integer *, doublereal *, integer *); extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); doublereal diflj, difrj, dsigj; extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); extern doublereal dlamc3_(doublereal *, doublereal *); extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), xerbla_(char *, integer *); doublereal dsigjp; /* -- LAPACK computational routine (version 3.4.2) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* September 2012 */ /* .. Scalar Arguments .. */ /* .. Array Arguments .. */ /* .. Parameters .. */ /* .. Local Scalars .. */ /* .. External Subroutines .. */ /* .. External Functions .. */ /* .. Intrinsic Functions .. */ /* .. Executable Statements .. */ /* Test the input parameters. */ /* Parameter adjustments */ b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; bx_dim1 = *ldbx; bx_offset = 1 + bx_dim1; bx -= bx_offset; --perm; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; difr_dim1 = *ldgnum; difr_offset = 1 + difr_dim1; difr -= difr_offset; poles_dim1 = *ldgnum; poles_offset = 1 + poles_dim1; poles -= poles_offset; givnum_dim1 = *ldgnum; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; --difl; --z__; --work; /* Function Body */ *info = 0; if (*icompq < 0 || *icompq > 1) { *info = -1; } else if (*nl < 1) { *info = -2; } else if (*nr < 1) { *info = -3; } else if (*sqre < 0 || *sqre > 1) { *info = -4; } n = *nl + *nr + 1; if (*nrhs < 1) { *info = -5; } else if (*ldb < n) { *info = -7; } else if (*ldbx < n) { *info = -9; } else if (*givptr < 0) { *info = -11; } else if (*ldgcol < n) { *info = -13; } else if (*ldgnum < n) { *info = -15; } else if (*k < 1) { *info = -20; } if (*info != 0) { i__1 = -(*info); xerbla_("DLALS0", &i__1); return 0; } m = n + *sqre; nlp1 = *nl + 1; if (*icompq == 0) { /* Apply back orthogonal transformations from the left. */ /* Step (1L): apply back the Givens rotations performed. */ i__1 = *givptr; for (i__ = 1; i__ <= i__1; ++i__) { drot_(nrhs, &b[givcol[i__ + (givcol_dim1 << 1)] + b_dim1], ldb, & b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[i__ + (givnum_dim1 << 1)], &givnum[i__ + givnum_dim1]); /* L10: */ } /* Step (2L): permute rows of B. */ dcopy_(nrhs, &b[nlp1 + b_dim1], ldb, &bx[bx_dim1 + 1], ldbx); i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { dcopy_(nrhs, &b[perm[i__] + b_dim1], ldb, &bx[i__ + bx_dim1], ldbx); /* L20: */ } /* Step (3L): apply the inverse of the left singular vector */ /* matrix to BX. */ if (*k == 1) { dcopy_(nrhs, &bx[bx_offset], ldbx, &b[b_offset], ldb); if (z__[1] < 0.) { dscal_(nrhs, &c_b5, &b[b_offset], ldb); } } else { i__1 = *k; for (j = 1; j <= i__1; ++j) { diflj = difl[j]; dj = poles[j + poles_dim1]; dsigj = -poles[j + (poles_dim1 << 1)]; if (j < *k) { difrj = -difr[j + difr_dim1]; dsigjp = -poles[j + 1 + (poles_dim1 << 1)]; } if (z__[j] == 0. || poles[j + (poles_dim1 << 1)] == 0.) { work[j] = 0.; } else { work[j] = -poles[j + (poles_dim1 << 1)] * z__[j] / diflj / (poles[j + (poles_dim1 << 1)] + dj); } i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { if (z__[i__] == 0. || poles[i__ + (poles_dim1 << 1)] == 0.) { work[i__] = 0.; } else { work[i__] = poles[i__ + (poles_dim1 << 1)] * z__[i__] / (dlamc3_(&poles[i__ + (poles_dim1 << 1)], & dsigj) - diflj) / (poles[i__ + (poles_dim1 << 1)] + dj); } /* L30: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { if (z__[i__] == 0. || poles[i__ + (poles_dim1 << 1)] == 0.) { work[i__] = 0.; } else { work[i__] = poles[i__ + (poles_dim1 << 1)] * z__[i__] / (dlamc3_(&poles[i__ + (poles_dim1 << 1)], & dsigjp) + difrj) / (poles[i__ + (poles_dim1 << 1)] + dj); } /* L40: */ } work[1] = -1.; temp = dnrm2_(k, &work[1], &c__1); dgemv_("T", k, nrhs, &c_b11, &bx[bx_offset], ldbx, &work[1], & c__1, &c_b13, &b[j + b_dim1], ldb); dlascl_("G", &c__0, &c__0, &temp, &c_b11, &c__1, nrhs, &b[j + b_dim1], ldb, info); /* L50: */ } } /* Move the deflated rows of BX to B also. */ if (*k < max(m,n)) { i__1 = n - *k; dlacpy_("A", &i__1, nrhs, &bx[*k + 1 + bx_dim1], ldbx, &b[*k + 1 + b_dim1], ldb); } } else { /* Apply back the right orthogonal transformations. */ /* Step (1R): apply back the new right singular vector matrix */ /* to B. */ if (*k == 1) { dcopy_(nrhs, &b[b_offset], ldb, &bx[bx_offset], ldbx); } else { i__1 = *k; for (j = 1; j <= i__1; ++j) { dsigj = poles[j + (poles_dim1 << 1)]; if (z__[j] == 0.) { work[j] = 0.; } else { work[j] = -z__[j] / difl[j] / (dsigj + poles[j + poles_dim1]) / difr[j + (difr_dim1 << 1)]; } i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { if (z__[j] == 0.) { work[i__] = 0.; } else { d__1 = -poles[i__ + 1 + (poles_dim1 << 1)]; work[i__] = z__[j] / (dlamc3_(&dsigj, &d__1) - difr[ i__ + difr_dim1]) / (dsigj + poles[i__ + poles_dim1]) / difr[i__ + (difr_dim1 << 1)]; } /* L60: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { if (z__[j] == 0.) { work[i__] = 0.; } else { d__1 = -poles[i__ + (poles_dim1 << 1)]; work[i__] = z__[j] / (dlamc3_(&dsigj, &d__1) - difl[ i__]) / (dsigj + poles[i__ + poles_dim1]) / difr[i__ + (difr_dim1 << 1)]; } /* L70: */ } dgemv_("T", k, nrhs, &c_b11, &b[b_offset], ldb, &work[1], & c__1, &c_b13, &bx[j + bx_dim1], ldbx); /* L80: */ } } /* Step (2R): if SQRE = 1, apply back the rotation that is */ /* related to the right null space of the subproblem. */ if (*sqre == 1) { dcopy_(nrhs, &b[m + b_dim1], ldb, &bx[m + bx_dim1], ldbx); drot_(nrhs, &bx[bx_dim1 + 1], ldbx, &bx[m + bx_dim1], ldbx, c__, s); } if (*k < max(m,n)) { i__1 = n - *k; dlacpy_("A", &i__1, nrhs, &b[*k + 1 + b_dim1], ldb, &bx[*k + 1 + bx_dim1], ldbx); } /* Step (3R): permute rows of B. */ dcopy_(nrhs, &bx[bx_dim1 + 1], ldbx, &b[nlp1 + b_dim1], ldb); if (*sqre == 1) { dcopy_(nrhs, &bx[m + bx_dim1], ldbx, &b[m + b_dim1], ldb); } i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { dcopy_(nrhs, &bx[i__ + bx_dim1], ldbx, &b[perm[i__] + b_dim1], ldb); /* L90: */ } /* Step (4R): apply back the Givens rotations performed. */ for (i__ = *givptr; i__ >= 1; --i__) { d__1 = -givnum[i__ + givnum_dim1]; drot_(nrhs, &b[givcol[i__ + (givcol_dim1 << 1)] + b_dim1], ldb, & b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[i__ + (givnum_dim1 << 1)], &d__1); /* L100: */ } } return 0; /* End of DLALS0 */ } /* dlals0_ */
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: <html xmlns="http: <head> <script src="../../svgweb/svg.js" data-path="../../svgweb"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/> <meta name="description" content="W3C SVG 1.1 2nd Edition SVGWeb Test Suite"/> <title> SVG 1.1 2nd Edition Test (svgweb): <API key>.svg </title> <style type="text/css"> <! .bodytext { font-family:verdana, helvetica, sans-serif; font-size: 12pt; line-height: 125%; text-align: Left; margin-top: 0; margin-bottom: 0 } .pageTitle { line-height: 150%; font-size: 20pt; font-weight : 900; margin-bottom: 20pt } .pageSubTitle { color : blue; line-height: 100%; font-size: 24pt; font-weight : 900 } .openChapter { color : blue; line-height: 125%; font-weight : 900 } .openSection { color : blue; line-height: 125%; font-weight : 900 } .info { color : black; line-height: 110%; font-size: 10pt; font-weight : 100 } p { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } blockquote { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } .opscript { margin-left: 3%; margin-right: 3%; } .opscript p { margin-top: 0.7em } .navbar { background: black; color: white; font-weight: bold } .warning { color: red; text-align: Center;} a,a:visited { color: blue } </style> <link rel="prev" href="interact-order-03-b.html" /> <link rel="index" href="index.html" /> <link rel="next" href="<API key>.html" /> <script src="../resources/testharnessreport.js"></script> </head> <body class="bodytext"> <div class="linkbar"> <p>Specification link: <a target="spec" href="http://www.w3.org/TR/SVG11/interact.html#<API key>">16.4 Pointer events</a></p> <p> <a href="interact-order-03-b.html" rel="prev">interact-order-03-b ←</a> <a href="index.html" rel="index">index</a> <a href="<API key>.html" rel="next">→ <API key></a> </p> </div> <div> <br /> <p class="warning"> Tests that contain the draft-watermark are under development and may be incorrectly testing a feature. </p> </div> <table align="center" border="0" cellspacing="0" cellpadding="10"> <tr> <td align="center" colspan="3"> <table border="0" cellpadding="8"> <tr> <td align="center" colspan="2" class="pageTitle"> <h1><API key>.svg</h1> </td> </tr> <tr class="navbar"> <td align="center"> SVG Image </td> <td align="center"> PNG Image </td> </tr> <tr> <td align="right"> <!--[if IE]> <object src="../../svg/<API key>.svg" width="480" height="360" classid="image/svg+xml"><p style="font-size:300%;color:red">FAIL</p> <![endif] <!--[if !IE]>--> <object data="../../svg/<API key>.svg" width="480" height="360" type="image/svg+xml"><p style="font-size:300%;color:red">FAIL</p> <!--<![endif]--> </object> </td> <td align="left"> <img alt="raster image of <API key>.svg" src="../../png/<API key>.png" width="480" height="360"/> </td> </tr> </table> </td> </tr> </table> <div class="opscript"> <h2 id="operatorscript"> Operator Script </h2> <div> <p> Using the pointer device move the cursor over the rects all the rects from left to right. As the mouseover event triggers the 'O':s will become visible and marked in either green (a pass) or red (a fail). </p> </div> <h2 id="passcriteria"> Pass Criteria </h2> <div> <p> The test has passed if after moving the cursor over all the rects: </p><ol> <li>all the 'O':s in the green rects have green fill</li> <li>there are no red 'O':s visible</li> <li>there are 9 green 'O':s in the first and second rect, 4 in the third rect and 6 in the fourth rect</li> </ol> </div> <h2 id="testdescription"> Test Description </h2> <div> <p> This test tests 'pointer-events' on text. Initially you should see four big rects with black stroke. In the uppermost rect there should be 10 'O':s with black fill. In the second rect from the top there should be 10 'O':s with no fill but with black stroke. In the third and fourth rects there should be no visible 'O':s at all. In the fourth rect there should be two green rects, and in each of the other three rects there should be one green rect. </p><p> For UA debugging purposes it's possible to click the "Toggle freeze" button before running the test. That will reset the visibility, fill and stroke on each 'O' as the cursor moves over them so that it's possible to trigger the change more than once. If the "Toggle freeze" button is clicked once again that means the change will remain after the cursor moves out. </p> </div> </div> <br/> <div class="linkbar"> <p> <a href="interact-order-03-b.html" rel="prev">interact-order-03-b ←</a> <a href="index.html" rel="index">index</a> <a href="<API key>.html" rel="next">→ <API key></a> </p> </div> </body> </html>
title: Square root convergents localeTitle: [](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/<API key>/project-euler/<API key>/index.md) [](https://github.com/freecodecamp/guides/blob/master/README.md)
package org.eclipse.collections.impl.block.factory; import org.eclipse.collections.impl.block.predicate.CodePointPredicate; import org.eclipse.collections.impl.utility.StringIterate; /** * The StringPredicates class is a factory that produces Predicates that work with Strings. */ public final class StringPredicates { private static final Predicates<String> EMPTY = new Empty(); private static final Predicates<String> NOT_EMPTY = new NotEmpty(); private static final Predicates<String> HAS_LETTERS = new HasLetters(); private static final Predicates<String> HAS_DIGITS = new HasDigits(); private static final Predicates<String> <API key> = new HasLettersOrDigits(); private static final Predicates<String> <API key> = new HasLettersAndDigits(); private static final Predicates<String> HAS_SPACES = new HasSpaces(); private static final Predicates<String> HAS_UPPERCASE = new HasUppercase(); private static final Predicates<String> HAS_LOWERCASE = new HasLowercase(); private static final Predicates<String> HAS_UNDEFINED = new HasUndefined(); private static final Predicates<String> IS_NUMERIC = new IsNumeric(); private static final Predicates<String> IS_ALPHANUMERIC = new IsAlphanumeric(); private static final Predicates<String> IS_BLANK = new IsBlank(); private static final Predicates<String> NOT_BLANK = new NotBlank(); private static final Predicates<String> IS_ALPHA = new IsAlpha(); private StringPredicates() { throw new AssertionError("Suppress default constructor for noninstantiability"); } public static Predicates<String> empty() { return EMPTY; } public static Predicates<String> notEmpty() { return NOT_EMPTY; } /** * Returns true if a String specified on the predicate is contained within a String passed to the the accept * method. */ public static Predicates<String> contains(String otherString) { return new ContainsString(otherString); } /** * Returns true if a String specified on the predicate is contained within a String passed to the the accept * method. * * @since 5.0 */ public static Predicates<String> notContains(String otherString) { return new NotContainsString(otherString); } /** * Returns true if a char specified on the predicate is contained within a String passed to the the accept * method. */ public static Predicates<String> contains(char character) { return new ContainsCharacter(character); } /** * Returns true if a String passed to the the accept method starts with the string specified on the predicate. */ public static Predicates<String> startsWith(String substring) { return new StartsWith(substring); } /** * Returns true if a String passed to the the accept method ends with the string specified on the predicate. */ public static Predicates<String> endsWith(String substring) { return new EndsWith(substring); } public static Predicates<String> size(int size) { return new Size(size); } public static Predicates<String> equalsIgnoreCase(String otherString) { return new EqualsIgnoreCase(otherString); } public static Predicates<String> matches(String regex) { return new MatchesRegex(regex); } public static Predicates<String> lessThan(String string) { return new LessThan(string); } public static Predicates<String> lessThanOrEqualTo(String string) { return new LessThanOrEqualTo(string); } public static Predicates<String> greaterThan(String string) { return new GreaterThan(string); } public static Predicates<String> <API key>(String string) { return new <API key>(string); } public static Predicates<String> hasLetters() { return HAS_LETTERS; } public static Predicates<String> hasDigits() { return HAS_DIGITS; } public static Predicates<String> hasLettersOrDigits() { return <API key>; } public static Predicates<String> hasLettersAndDigits() { return <API key>; } public static Predicates<String> hasSpaces() { return HAS_SPACES; } public static Predicates<String> hasUpperCase() { return HAS_UPPERCASE; } public static Predicates<String> hasLowerCase() { return HAS_LOWERCASE; } public static Predicates<String> hasUndefined() { return HAS_UNDEFINED; } public static Predicates<String> isNumeric() { return IS_NUMERIC; } public static Predicates<String> isAlphanumeric() { return IS_ALPHANUMERIC; } public static Predicates<String> isBlank() { return IS_BLANK; } public static Predicates<String> notBlank() { return NOT_BLANK; } public static Predicates<String> isAlpha() { return IS_ALPHA; } private static class Empty extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return anObject != null && anObject.length() == 0; } @Override public String toString() { return "StringPredicates.empty()"; } } private static class NotEmpty extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return anObject != null && anObject.length() > 0; } @Override public String toString() { return "StringPredicates.notEmpty()"; } } private static class HasLetters extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return StringIterate.anySatisfy(anObject, CodePointPredicate.IS_LETTER); } @Override public String toString() { return "StringPredicates.hasLetters()"; } } private static class HasDigits extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return StringIterate.anySatisfy(anObject, CodePointPredicate.IS_DIGIT); } @Override public String toString() { return "StringPredicates.hasDigits()"; } } private static class HasLettersOrDigits extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return StringIterate.anySatisfy(anObject, CodePointPredicate.IS_LETTER_OR_DIGIT); } @Override public String toString() { return "StringPredicates.hasLettersOrDigits()"; } } private static class HasLettersAndDigits extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String string) { boolean hasLetter = false; boolean hasDigit = false; for (int i = 0; i < string.length(); i++) { if (Character.isLetter(string.codePointAt(i))) { hasLetter = true; } if (Character.isDigit(string.codePointAt(i))) { hasDigit = true; } if (hasLetter && hasDigit) { return true; } } return false; } @Override public String toString() { return "StringPredicates.hasLettersAndDigits()"; } } private static class HasSpaces extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return StringIterate.anySatisfy(anObject, CodePointPredicate.IS_WHITESPACE); } @Override public String toString() { return "StringPredicates.hasSpaces()"; } } private static class HasUppercase extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return StringIterate.anySatisfy(anObject, CodePointPredicate.IS_UPPERCASE); } @Override public String toString() { return "StringPredicates.hasUpperCase()"; } } private static class HasLowercase extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return StringIterate.anySatisfy(anObject, CodePointPredicate.IS_LOWERCASE); } @Override public String toString() { return "StringPredicates.hasLowerCase()"; } } private static class HasUndefined extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return StringIterate.anySatisfy(anObject, CodePointPredicate.IS_UNDEFINED); } @Override public String toString() { return "StringPredicates.hasUndefined()"; } } private static class IsNumeric extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return StringIterate.allSatisfy(anObject, CodePointPredicate.IS_DIGIT); } @Override public String toString() { return "StringPredicates.isNumeric()"; } } private static class IsAlphanumeric extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return StringIterate.allSatisfy(anObject, CodePointPredicate.IS_LETTER_OR_DIGIT); } @Override public String toString() { return "StringPredicates.isAlphanumeric()"; } } private static class IsBlank extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String string) { return StringIterate.isEmptyOrWhitespace(string); } @Override public String toString() { return "StringPredicates.isBlank()"; } } private static class NotBlank extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String string) { return StringIterate.<API key>(string); } @Override public String toString() { return "StringPredicates.notBlank()"; } } private static class IsAlpha extends Predicates<String> { private static final long serialVersionUID = 1L; @Override public boolean accept(String anObject) { return anObject != null && StringIterate.allSatisfy(anObject, CodePointPredicate.IS_LETTER); } @Override public String toString() { return "StringPredicates.isAlpha()"; } } private static final class ContainsString extends Predicates<String> { private static final long serialVersionUID = 1L; private final String otherString; private ContainsString(String newOtherString) { this.otherString = newOtherString; } @Override public boolean accept(String string) { return StringIterate.notEmpty(string) && string.contains(this.otherString); } @Override public String toString() { return "StringPredicates.contains(\"" + this.otherString + "\")"; } } private static final class NotContainsString extends Predicates<String> { private static final long serialVersionUID = 1L; private final String otherString; private NotContainsString(String newOtherString) { this.otherString = newOtherString; } @Override public boolean accept(String string) { return StringIterate.isEmpty(string) || !string.contains(this.otherString); } @Override public String toString() { return "StringPredicates.notContains(\"" + this.otherString + "\")"; } } private static final class ContainsCharacter extends Predicates<String> { private static final long serialVersionUID = 1L; private final char character; private ContainsCharacter(char newCharacter) { this.character = newCharacter; } @Override public boolean accept(String string) { return StringIterate.notEmpty(string) && string.indexOf(this.character) > -1; } @Override public String toString() { return "StringPredicates.contains(\"" + this.character + "\")"; } } private static final class StartsWith extends Predicates<String> { private static final long serialVersionUID = 1L; private final String substring; private StartsWith(String newSubstring) { this.substring = newSubstring; } @Override public boolean accept(String anObject) { return anObject != null && anObject.startsWith(this.substring); } @Override public String toString() { return "StringPredicates.startsWith(\"" + this.substring + "\")"; } } private static final class EndsWith extends Predicates<String> { private static final long serialVersionUID = 1L; private final String substring; private EndsWith(String newSubstring) { this.substring = newSubstring; } @Override public boolean accept(String anObject) { return anObject != null && anObject.endsWith(this.substring); } @Override public String toString() { return "StringPredicates.endsWith(\"" + this.substring + "\")"; } } private static final class Size extends Predicates<String> { private static final long serialVersionUID = 1L; private final int size; private Size(int newSize) { this.size = newSize; } @Override public boolean accept(String anObject) { return anObject != null && anObject.length() == this.size; } @Override public String toString() { return "StringPredicates.size(" + this.size + ')'; } } private static final class EqualsIgnoreCase extends Predicates<String> { private static final long serialVersionUID = 1L; private final String otherString; private EqualsIgnoreCase(String newOtherString) { this.otherString = newOtherString; } @Override public boolean accept(String anObject) { return anObject != null && anObject.equalsIgnoreCase(this.otherString); } @Override public String toString() { return "StringPredicates.equalsIgnoreCase(\"" + this.otherString + "\")"; } } private static final class MatchesRegex extends Predicates<String> { private static final long serialVersionUID = 1L; private final String regex; private MatchesRegex(String newRegex) { this.regex = newRegex; } @Override public boolean accept(String anObject) { return anObject != null && anObject.matches(this.regex); } @Override public String toString() { return "StringPredicates.matches(\"" + this.regex + "\")"; } } private static final class LessThan extends Predicates<String> { private static final long serialVersionUID = 1L; private final String string; private LessThan(String newString) { this.string = newString; } @Override public boolean accept(String anObject) { return anObject != null && anObject.compareTo(this.string) < 0; } @Override public String toString() { return "StringPredicates.lessThan(\"" + this.string + "\")"; } } private static final class LessThanOrEqualTo extends Predicates<String> { private static final long serialVersionUID = 1L; private final String string; private LessThanOrEqualTo(String newString) { this.string = newString; } @Override public boolean accept(String anObject) { return anObject != null && anObject.compareTo(this.string) <= 0; } @Override public String toString() { return "StringPredicates.lessThanOrEqualTo(\"" + this.string + "\")"; } } private static final class GreaterThan extends Predicates<String> { private static final long serialVersionUID = 1L; private final String string; private GreaterThan(String newString) { this.string = newString; } @Override public boolean accept(String anObject) { return anObject != null && anObject.compareTo(this.string) > 0; } @Override public String toString() { return "StringPredicates.greaterThan(\"" + this.string + "\")"; } } private static final class <API key> extends Predicates<String> { private static final long serialVersionUID = 1L; private final String string; private <API key>(String newString) { this.string = newString; } @Override public boolean accept(String anObject) { return anObject != null && anObject.compareTo(this.string) >= 0; } @Override public String toString() { return "StringPredicates.<API key>(\"" + this.string + "\")"; } } }
/* Bit vector functions */ #ifndef CR_BITS_H #define CR_BITS_H #include "cr_compiler.h" #define CR_MAX_CONTEXTS 512 #define CR_MAX_BITARRAY (CR_MAX_CONTEXTS / 32) /* 32 contexts per uint */ #ifdef __cplusplus extern "C" { #endif static INLINE void RESET( unsigned int *b, const unsigned int *d ) { int j; for (j=0;j<CR_MAX_BITARRAY;j++) b[j] |= d[j]; } static INLINE void DIRTY( unsigned int *b, const unsigned int *d ) { int j; for (j=0;j<CR_MAX_BITARRAY;j++) b[j] = d[j]; } static INLINE void FILLDIRTY( unsigned int *b ) { int j; for (j=0;j<CR_MAX_BITARRAY;j++) b[j] = 0xffffffff; } static INLINE void CLEARDIRTY( unsigned int *b, const unsigned int *d ) { int j; for (j=0;j<CR_MAX_BITARRAY;j++) b[j] &= d[j]; } /* As above, but complement the bits here instead of in the calling code */ static INLINE void CLEARDIRTY2( unsigned int *b, const unsigned int *d ) { int j; for (j=0;j<CR_MAX_BITARRAY;j++) b[j] &= ~d[j]; } static INLINE int CHECKDIRTY( const unsigned int *b, const unsigned int *d ) { int j; for (j=0;j<CR_MAX_BITARRAY;j++) if (b[j] & d[j]) return 1; return 0; } #ifdef __cplusplus } #endif #endif /* CR_BITS_H */
<?php /** Zend_Exception */ require_once 'Zend/Exception.php'; class Zend_Dom_Exception extends Zend_Exception { }
#ifndef _MACHINE_RTAS_H_ #define _MACHINE_RTAS_H_ #include <sys/cdefs.h> #include <sys/types.h> #include <dev/ofw/openfirm.h> /* * RTAS functions are defined by 32-bit integer tokens. These vary from * system to system, and can be looked up from their standardized names * using rtas_token_lookup(). If RTAS is not available, rtas_token_lookup() * and rtas_call_method() return -1; this can be checked in advance using * rtas_exists(). Otherwise, rtas_call_method() returns one of the RTAS * status codes from the bottom of this file. */ int rtas_exists(void); int rtas_call_method(cell_t token, int nargs, int nreturns, ...); cell_t rtas_token_lookup(const char *method); /* RTAS Status Codes: see CHRP or PAPR specification */ #define RTAS_OK 0 #define RTAS_HW_ERROR -1 #define RTAS_BUSY -2 #define RTAS_PARAM_ERROR -3 #define RTAS_STATE_CHANGE -7 #define RTAS_VENDOR_BEGIN 9000 #define RTAS_EXTENDED_DELAY 9900 #define <API key> -9000 #define <API key> -9004 #endif /* _MACHINE_RTAS_H_ */
id: <API key> challengeType: 5 title: 'Problem 91: Right triangles with integer coordinates' videoUrl: '' localeTitle: 'Задача 91: Прямые треугольники с целыми координатами' ## Description <section id="description"> Точки P (x1, y1) и Q (x2, y2) нанесены на целые координаты и соединяются с началом O (0,0) с образованием ΔOPQ. <p> Есть ровно четырнадцать треугольников, содержащих прямой угол, который может быть сформирован, когда каждая координата находится между 0 и 2 включительно; то есть 0 ≤ x1, y1, x2, y2 ≤ 2. </p><p> Учитывая, что 0 ≤ x1, y1, x2, y2 ≤ 50, сколько правых треугольников может быть сформировано? </p></section> ## Instructions <section id="instructions"> </section> ## Tests <section id='tests'> yml tests: - text: <code>euler91()</code> должен возвращать 14234. testString: 'assert.strictEqual(euler91(), 14234, "<code>euler91()</code> should return 14234.");' </section> ## Challenge Seed <section id='challengeSeed'> <div id='js-seed'> js function euler91() { // Good luck! return true; } euler91(); </div> </section> ## Solution <section id='solution'> js // solution required </section>
package com.salesforce.dva.argus.service; import static com.salesforce.dva.argus.service.MQService.MQQueue.ALERT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; import org.slf4j.LoggerFactory; import com.salesforce.dva.argus.AbstractTest; import com.salesforce.dva.argus.entity.Alert; import com.salesforce.dva.argus.entity.Audit; import com.salesforce.dva.argus.entity.History; import com.salesforce.dva.argus.entity.History.JobStatus; import com.salesforce.dva.argus.entity.Metric; import com.salesforce.dva.argus.entity.Notification; import com.salesforce.dva.argus.entity.PrincipalUser; import com.salesforce.dva.argus.entity.Trigger; import com.salesforce.dva.argus.entity.Trigger.TriggerType; import com.salesforce.dva.argus.service.alert.DefaultAlertService; import com.salesforce.dva.argus.service.alert.DefaultAlertService.<API key>; public class AlertServiceTest extends AbstractTest { private static final String expression = "DIVIDE(-1h:argus.jvm:file.descriptor.open{host=unknown-host}:avg, -1h:argus.jvm:file.descriptor.max{host=unknown-host}:avg)"; @Test public void testUpdateAlert() { UserService userService = system.getServiceFactory().getUserService(); AlertService alertService = system.getServiceFactory().getAlertService(); Alert expected = new Alert(userService.findAdminUser(), userService.findAdminUser(), "alert-name", expression, "* * * * *"); Notification notification = new Notification("notification", expected, "notifier-name", new ArrayList<String>(), 5000L); Trigger trigger = new Trigger(expected, TriggerType.GREATER_THAN, "trigger-name", 0.95, 60000); notification.setAlert(expected); expected.setNotifications(Arrays.asList(new Notification[] { notification })); expected.setTriggers(Arrays.asList(new Trigger[] { trigger })); assertTrue(!expected.isEnabled()); expected = alertService.updateAlert(expected); Alert actual = alertService.<API key>(expected.getName(), userService.findAdminUser()); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getTriggers(), actual.getTriggers()); actual.setEnabled(true); actual = alertService.updateAlert(actual); assertTrue(actual.isEnabled()); alertService.deleteAlert(actual.getName(), userService.findAdminUser()); assertTrue(alertService.<API key>(expected.getName(), expected.getOwner()) == null); } @Test public void testDeleteAlert() { UserService userService = system.getServiceFactory().getUserService(); AlertService alertService = system.getServiceFactory().getAlertService(); Alert alert = new Alert(userService.findAdminUser(), userService.findAdminUser(), "alert-name", expression, "* * * * *"); Notification notification1 = new Notification("notification1", alert, "notifier-name1", new ArrayList<String>(), 5000L); Notification notification2 = new Notification("notification2", alert, "notifier-name2", new ArrayList<String>(), 5000L); Trigger trigger1 = new Trigger(alert, TriggerType.GREATER_THAN_OR_EQ, "trigger-name1", 0.95, 60000); Trigger trigger2 = new Trigger(alert, TriggerType.GREATER_THAN, "trigger-name2", 0.95, 60000); alert.setNotifications(Arrays.asList(new Notification[] { notification1, notification2 })); alert.setTriggers(Arrays.asList(new Trigger[] { trigger1, trigger2 })); for (Notification notification : alert.getNotifications()) { notification.setTriggers(alert.getTriggers()); } alert = alertService.updateAlert(alert); for (Notification notification : alert.getNotifications()) { alertService.deleteNotification(notification); } for (Trigger trigger : alert.getTriggers()) { alertService.deleteTrigger(trigger); } alert.setTriggers(null); alert.setNotifications(null); alert = alertService.updateAlert(alert); Trigger trigger3 = new Trigger(alert, TriggerType.GREATER_THAN, "trigger-name3", 0.95, 60000); Notification notification3 = new Notification("notification3", alert, "notifier-name3", new ArrayList<String>(), 5000L); notification3.setTriggers(Arrays.asList(new Trigger[] { trigger3 })); alert.setTriggers(Arrays.asList(new Trigger[] { trigger3 })); alert.setNotifications(Arrays.asList(new Notification[] { notification3 })); alert = alertService.updateAlert(alert); alertService.<API key>(alert); assertNull("Failed to mark alert as deleted", alertService.<API key>(alert.getId())); Alert result = null; List<Alert> results = alertService.<API key>(); for (Alert a : results) { if (alert.getId().equals(a.getId())) { result = a; break; } } assertNotNull("Could not find the alert that was marked for deletion", result); assertTrue(result.isDeleted()); alertService.deleteAlert(alert); assertNull("Failed to delete alert", alertService.<API key>(alert.getId())); } @Test public void <API key>() { AlertService alertService = system.getServiceFactory().getAlertService(); String alertName = "testAlert"; PrincipalUser expectedUser = new PrincipalUser("testUser", "testuser@testcompany.com"); Alert expectedAlert = new Alert(expectedUser, expectedUser, alertName, expression, "* * * * *"); expectedAlert = alertService.updateAlert(expectedAlert); Alert actualAlert = alertService.<API key>(alertName, expectedAlert.getOwner()); assertNotNull(actualAlert); assertEquals(expectedAlert.getId(), actualAlert.getId()); } @Test public void <API key>() { UserService userService = system.getServiceFactory().getUserService(); AlertService alertService = system.getServiceFactory().getAlertService(); String userName = createRandomName(); int alertsCount = random.nextInt(20) + 1; PrincipalUser user = new PrincipalUser(userName, userName + "@testcompany.com"); user = userService.updateUser(user); List<Alert> expectedAlerts = new ArrayList<>(); for (int i = 0; i < alertsCount; i++) { expectedAlerts.add(alertService.updateAlert(new Alert(user, user, "alert_" + i, expression, "* * * * *"))); } List<Alert> actualAlerts = alertService.findAlertsByOwner(user); assertEquals(actualAlerts.size(), expectedAlerts.size()); Set<Alert> actualSet = new HashSet<>(); actualSet.addAll(actualAlerts); for (Alert alert : expectedAlerts) { assertTrue(actualSet.contains(alert)); } } @Test public void findAllAlerts() { UserService userService = system.getServiceFactory().getUserService(); AlertService alertService = system.getServiceFactory().getAlertService(); String userName = createRandomName(); int alertsCount = random.nextInt(100) + 1; PrincipalUser user = new PrincipalUser(userName, userName + "@testcompany.com"); user = userService.updateUser(user); List<Alert> expectedAlerts = new ArrayList<>(); for (int i = 0; i < alertsCount; i++) { expectedAlerts.add(alertService.updateAlert(new Alert(user, user, "alert_" + i, expression, "* * * * *"))); } List<Alert> actualAlerts = alertService.findAllAlerts(); assertEquals(actualAlerts.size(), expectedAlerts.size()); Set<Alert> actualSet = new HashSet<>(); actualSet.addAll(actualAlerts); for (Alert alert : expectedAlerts) { assertTrue(actualSet.contains(alert)); } } @Test public void testAlertDelete() { UserService userService = system.getServiceFactory().getUserService(); AlertService alertService = system.getServiceFactory().getAlertService(); PrincipalUser user = userService.findAdminUser(); String alertName = createRandomName(); Alert expectedAlert = new Alert(user, user, alertName, expression, "* * * * *"); expectedAlert = alertService.updateAlert(expectedAlert); alertService.deleteAlert(expectedAlert); assertNull(alertService.<API key>(alertName, user)); } @Test public void <API key>() { UserService userService = system.getServiceFactory().getUserService(); AlertService alertService = system.getServiceFactory().getAlertService(); AuditService auditService = system.getServiceFactory().getAuditService(); HistoryService historyService = system.getServiceFactory().getHistoryService(); PrincipalUser user = userService.findAdminUser(); int alertCount = 10; int auditCount = 5000; int historyCount = 5000; Alert[] alerts = new Alert[alertCount]; for (int i = 0; i < alerts.length; i++) { Alert alert = new Alert(user, user, createRandomName() + i, "-1d:scope:metric:avg", "1 1 1 1 1"); alerts[i] = alertService.updateAlert(alert); for (int j = 0; j < auditCount; j++) { Audit audit = new Audit("message", "localhost", alerts[i]); auditService.createAudit(audit); } for (int j = 0; j < historyCount; j++) { History history = new History("message", "localhost", alerts[i], JobStatus.DEQUEUED); historyService.updateHistory(history); } LoggerFactory.getLogger(getClass()).info("Created alert " + i); } double total = 0; for (Alert alert : alerts) { long start = System.currentTimeMillis(); alertService.deleteAlert(alert); long delta = System.currentTimeMillis() - start; total += delta; LoggerFactory.getLogger(getClass()).info("Alert delete latency = " + delta); } LoggerFactory.getLogger(getClass()).info("Average delete latency = " + (total / alerts.length)); } @Test public void <API key>() { UserService userService = system.getServiceFactory().getUserService(); AlertService alertService = system.getServiceFactory().getAlertService(); Alert alert = new Alert(userService.findAdminUser(), userService.findAdminUser(), "alert-name", expression, "* * * * *"); Notification notification1 = new Notification("notification1", alert, "notifier-name1", new ArrayList<String>(), 5000L); Notification notification2 = new Notification("notification2", alert, "notifier-name2", new ArrayList<String>(), 5000L); Notification notification3 = new Notification("notification3", alert, "notifier-name3", new ArrayList<String>(), 5000L); Trigger trigger1 = new Trigger(alert, TriggerType.GREATER_THAN_OR_EQ, "trigger-name1", 0.95, 60000); alert.setNotifications(Arrays.asList(new Notification[] { notification1, notification2, notification3 })); alert.setTriggers(Arrays.asList(new Trigger[] { trigger1 })); notification1.setTriggers(alert.getTriggers()); notification2.setTriggers(alert.getTriggers()); notification3.setTriggers(alert.getTriggers()); alert = alertService.updateAlert(alert); for (Notification notification : alert.getNotifications()) { notification.setTriggers(null); } alert.setTriggers(new ArrayList<Trigger>()); alert = alertService.updateAlert(alert); for (Notification notification : alert.getNotifications()) { assertTrue(notification.getTriggers().isEmpty()); } } @Test public void <API key>() { ServiceFactory factory = system.getServiceFactory(); NotifierFactory notifierFactory = system.getNotifierFactory(); DefaultAlertService service = new DefaultAlertService(factory.getMQService(), factory.getMetricService(), factory.<API key>(), factory.getAuditService(), factory.getTSDBService(), factory.getMailService(), system.getConfiguration(), factory.getHistoryService(), factory.getMonitorService(), notifierFactory); UserService userService = system.getServiceFactory().getUserService(); Alert alert = new Alert(userService.findAdminUser(), userService.findAdminUser(), "alert-name_test", expression, "* * * * *"); Metric metric = new Metric("scope", "metric"); double thresholdValue = 90; long inertia = 10; long startTime = 1; long expectedTriggerTime; Trigger trigger = new Trigger(alert, TriggerType.GREATER_THAN_OR_EQ, "name_test", thresholdValue, inertia); Map<Long, String> datapoints = new HashMap<Long, String>(); datapoints.putAll(createDatapoints(inertia + 1, thresholdValue, startTime, true)); metric.setDatapoints(datapoints); expectedTriggerTime = datapoints.size(); long actualValue = service.<API key>(trigger, metric); assertEquals(expectedTriggerTime, actualValue); startTime = datapoints.size() + 1; datapoints.putAll(createDatapoints(201, thresholdValue, startTime, false)); metric.setDatapoints(datapoints); actualValue = service.<API key>(trigger, metric); assertEquals(expectedTriggerTime, actualValue); startTime = datapoints.size() + 1; datapoints.putAll(createDatapoints(inertia - 1, thresholdValue, startTime, true)); metric.setDatapoints(datapoints); actualValue = service.<API key>(trigger, metric); assertEquals(expectedTriggerTime, actualValue); startTime = datapoints.size() + 1; datapoints.putAll(createDatapoints(inertia + 1, thresholdValue, startTime, true)); metric.setDatapoints(datapoints); actualValue = service.<API key>(trigger, metric); expectedTriggerTime = datapoints.size(); assertEquals(expectedTriggerTime, actualValue); startTime = datapoints.size() + 1; datapoints.putAll(createDatapoints(201, thresholdValue, startTime, false)); metric.setDatapoints(datapoints); actualValue = service.<API key>(trigger, metric); assertEquals(expectedTriggerTime, actualValue); } @Test public void <API key>() { ServiceFactory factory = system.getServiceFactory(); NotifierFactory notifierFactory = system.getNotifierFactory(); DefaultAlertService service = new DefaultAlertService(factory.getMQService(), factory.getMetricService(), factory.<API key>(), factory.getAuditService(), factory.getTSDBService(), factory.getMailService(), system.getConfiguration(), factory.getHistoryService(), factory.getMonitorService(), notifierFactory); UserService userService = system.getServiceFactory().getUserService(); Alert alert = new Alert(userService.findAdminUser(), userService.findAdminUser(), "alert-name_test", expression, "* * * * *"); Metric metric = new Metric("scope", "metric"); double thresholdValue = 90; long inertia = 0; long startTime = 1000; long expectedTriggerTime; Trigger trigger = new Trigger(alert, TriggerType.GREATER_THAN_OR_EQ, "name_test", thresholdValue, inertia); Map<Long, String> datapoints = new HashMap<Long, String>(); datapoints.putAll(createDatapoints(1, thresholdValue, startTime, true)); metric.setDatapoints(datapoints); expectedTriggerTime = startTime; long actualValue = service.<API key>(trigger, metric); assertEquals(expectedTriggerTime, actualValue); } @Test public void <API key>() { ServiceFactory factory = system.getServiceFactory(); NotifierFactory notifierFactory = system.getNotifierFactory(); DefaultAlertService service = new DefaultAlertService(factory.getMQService(), factory.getMetricService(), factory.<API key>(), factory.getAuditService(), factory.getTSDBService(), factory.getMailService(), system.getConfiguration(), factory.getHistoryService(), factory.getMonitorService(), notifierFactory); UserService userService = system.getServiceFactory().getUserService(); Alert alert = new Alert(userService.findAdminUser(), userService.findAdminUser(), "alert-name_test", expression, "* * * * *"); Metric metric = new Metric("scope", "metric"); double thresholdValue = 90; long inertia = 1; long startTime = 1000; Trigger trigger = new Trigger(alert, TriggerType.GREATER_THAN_OR_EQ, "name_test", thresholdValue, inertia); Map<Long, String> datapoints = new HashMap<Long, String>(); datapoints.putAll(createDatapoints(1, thresholdValue, startTime, true)); metric.setDatapoints(datapoints); Long actualValue = service.<API key>(trigger, metric); assertNull(actualValue); } @Test public void <API key>() { ServiceFactory factory = system.getServiceFactory(); NotifierFactory notifierFactory = system.getNotifierFactory(); DefaultAlertService service = new DefaultAlertService(factory.getMQService(), factory.getMetricService(), factory.<API key>(), factory.getAuditService(), factory.getTSDBService(), factory.getMailService(), system.getConfiguration(), factory.getHistoryService(), factory.getMonitorService(), notifierFactory); UserService userService = system.getServiceFactory().getUserService(); Alert alert = new Alert(userService.findAdminUser(), userService.findAdminUser(), "alert-name_test", expression, "* * * * *"); Metric metric = new Metric("scope", "metric"); double thresholdValue = 90; long inertia = 0; long startTime = 1000; Trigger trigger = new Trigger(alert, TriggerType.GREATER_THAN_OR_EQ, "name_test", thresholdValue, inertia); Map<Long, String> datapoints = new HashMap<Long, String>(); datapoints.putAll(createDatapoints(0, thresholdValue, startTime, true)); metric.setDatapoints(datapoints); Long actualValue = service.<API key>(trigger, metric); assertNull(actualValue); } @Test public void <API key>() { UserService userService = system.getServiceFactory().getUserService(); AlertService alertService = system.getServiceFactory().getAlertService(); PrincipalUser user = userService.findAdminUser(); String alertName = createRandomName(); Alert alert = new Alert(user, user, alertName, expression, "* * * * *"); alert = alertService.updateAlert(alert); alertService.<API key>(alert); assertNull(alertService.<API key>(alertName, user)); alert = new Alert(user, user, alertName, expression, "* * * * *"); alert = alertService.updateAlert(alert); assertNotNull((alertService.<API key>(alertName, user))); } private Map<Long, String> createDatapoints(long size, Double value, long startTime, boolean greaterThan) { Map<Long, String> result = new HashMap<Long, String>(); for (int i = 0; i < size; i++) { double dataPointValue = random.nextInt(value.intValue()) + (greaterThan ? (value + 2) : -1); result.put(startTime++, String.valueOf(dataPointValue)); } return result; } }
#include "CommentsTest.h" #include "../src/CommentsPlugin.h" #include "../src/nodes/CommentNode.h" #include "../src/nodes/CommentDiagram.h" #include "SelfTest/src/Test.h" #include "SelfTest/src/TestAssertions.h" #include "VisualizationBase/src/<API key>.h" #include "VisualizationBase/src/Scene.h" #include "VisualizationBase/src/items/VComposite.h" #include "VisualizationBase/src/items/VList.h" #include "VisualizationBase/src/nodes/TestBoxNode.h" #include "ModelBase/src/test_nodes/BinaryNode.h" #include "ModelBase/src/nodes/Text.h" #include "ModelBase/src/nodes/List.h" #include "ModelBase/src/model/TreeManager.h" using namespace Visualization; namespace Comments { CommentNode* CommentsTestUtil::<API key>() { return new CommentNode{ "Envision's comments support several useful features:\n" " * Baisc markdown syntax and **rich** <span style=\"font-size:20px\"><i>text</i></span>.\n" " * Lists\n" " * Diagrams\n" " * Embeded source code\n" " * Tables\n" " * Embedded HTML/Javascript" }; } CommentNode* CommentsTestUtil::<API key>() { auto diagramComment = new CommentNode{ "# Diagrams!\n" "A diagram can be drawn directly in the code\n" "[diagram#main]" }; auto diagram = new CommentDiagram{nullptr, "main"}; auto shape1 = new CommentDiagramShape{50, 10, 60, 50, CommentDiagramShape::ShapeType::Rectangle}; shape1->setLabel(new CommentText{"Model"}); shape1->setOutlineType(Qt::NoPen); shape1->setBackgroundColor("#a3c0f2"); shape1->setTextColor("colors/DarkCornflowerBlue3"); diagram->shapes()->append(shape1); auto shape2 = new CommentDiagramShape{10, 100, 60, 50, CommentDiagramShape::ShapeType::Ellipse}; shape2->setLabel(new CommentText{"View"}); shape2->setOutlineType(Qt::NoPen); shape2->setBackgroundColor("#f4b16b"); shape2->setTextColor("colors/DarkOrange2"); diagram->shapes()->append(shape2); auto shape3 = new CommentDiagramShape{100, 100, 90, 50, CommentDiagramShape::ShapeType::Ellipse}; shape3->setLabel(new CommentText{"Controller"}); shape3->setShapeColor("#990000"); shape3->setOutlineSize(3); shape3->setOutlineType(Qt::DashLine); shape3->setBackgroundColor("#f4b16b"); shape3->setTextColor("colors/DarkOrange2"); diagram->shapes()->append(shape3); diagram->connectors()->append(new <API key>{0, 8, 1, 0}); diagram->connectors()->last()->setEndArrow(true); diagram->connectors()->append(new <API key>{0, 8, 2, 0}); diagram->connectors()->last()->setEndArrow(true); diagram->connectors()->append(new <API key>{1, 4, 2, 12}); diagramComment->diagrams()->append(diagram); return diagramComment; } CommentNode* CommentsTestUtil::createTableComment() { auto structuresComment = new CommentNode{ "# Sourcecode!\n" "[code#aCode]\n" "# Tables!\n" "[table#aTable#3#4]" }; auto code = new CommentFreeNode{nullptr, "aCode"}; code->setNode( new Model::Text{"Code comes here"}); structuresComment->codes()->append(code); auto table = new CommentTable{nullptr, "aTable", 3, 3}; table->setNodeAt(0, 0, new CommentNode{"##The code"}); table->setNodeAt(0, 1, new CommentNode{"##Details"}); table->setNodeAt(0, 2, new CommentNode{"##Notes"}); table->setNodeAt(2, 0, new CommentText{"some text"}); structuresComment->tables()->append(table); return structuresComment; } CommentNode* CommentsTestUtil::createImageComment() { return new CommentNode{ "# Images\n" "[image#styles/icon/loop.svg|20x]\n" "Images can be resized with Shift + Right click & Drag." }; } CommentNode* CommentsTestUtil::<API key>() { return new CommentNode{ "# Browsers\n" "[browser "...\n" "# Inline HTML to Browser\n" "<html>\n" " <script type=\"text/javascript\">\n" " function hi() { alert(\"Hello World!\"); } \n" " </script>\n" " <button onclick=\"hi()\">Try it</button>\n" "</html>" }; } class CommentsTest : public SelfTest::Test<CommentsPlugin, CommentsTest> { public: void test() { auto list = new Model::List{}; auto manager = new Model::TreeManager{list}; manager->beginModification(list, "set"); list->append( CommentsTestUtil::<API key>() ); list->append(new Model::Text("")); list->append( CommentsTestUtil::<API key>()); list->append(new Model::Text("")); list->append( CommentsTestUtil::createTableComment()); list->append(new Model::Text("")); list->append( CommentsTestUtil::createImageComment() ); list->append(new Model::Text("")); list->append(CommentsTestUtil::<API key>()); manager->endModification(); auto scene = <API key>::instance().mainScene(); scene->addTopLevelNode(list); QApplication::processEvents(); scene->scheduleUpdate(); scene->listenToTreeManager(manager); CHECK_CONDITION(scene); }}; }
// Configuration for other mojio_*.h. Note that this is a C header. // Things in this file may be tweaked (the values of macros or the underlying // types for typedefs) as necessary/appropriate, but they should not be used // directly by application code. #ifndef <API key> #define <API key> #define MOJIO_CONFIG_BUFSIZ 8192 #define <API key> 4096 #define <API key> 16 // What to use for the C |restrict| keyword (not supported in C++). // TODO(vtl): Is this right? #define <API key> __restrict__ // Maximum number of (simultaneously open) FDs. #define <API key> 1024 // We want types of exact bitwidths (since values will usually come from Mojo // messages), but we don't want to include <stdint.h> from our headers. Thus we // define our own. These are meant for internal use only. // TODO(vtl): Add static_assert()s/_Static_assert()s verifying the sizes. typedef int mojio_config_int32; typedef unsigned mojio_config_uint32; typedef long long mojio_config_int64; typedef unsigned long long mojio_config_uint64; #endif // <API key>
goog.provide('gxnat.slicerNode.BackgroundColor'); goog.require('nrg.string'); goog.require('gxnat.slicerNode.Node'); /** * @struct * @param {!string | !Array.<number>} color1 * @param {!string | !Array.<number>} color2 * @extends {gxnat.slicerNode.Node} * @constructor */ gxnat.slicerNode.BackgroundColor = function(color1, color2){ goog.base(this); this.backgroundColor = nrg.string.mrmlColorToRgb(color1); this.backgroundColor2 = nrg.string.mrmlColorToRgb(color2); } goog.inherits(gxnat.slicerNode.BackgroundColor, gxnat.slicerNode.Node); goog.exportSymbol('gxnat.slicerNode.BackgroundColor', gxnat.slicerNode.BackgroundColor);
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: <html xmlns="http: <head> <script src="../../../../../tools/svgweb/src/svg.js" data-path="../../../../../tools/svgweb/src"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/> <meta name="description" content="W3C SVG 1.1 2nd Edition SVGWeb Test Suite"/> <title> SVG 1.1 2nd Edition Test (svgweb): struct-use-08-b.svg </title> <style type="text/css"> <! .bodytext { font-family:verdana, helvetica, sans-serif; font-size: 12pt; line-height: 125%; text-align: Left; margin-top: 0; margin-bottom: 0 } .pageTitle { line-height: 150%; font-size: 20pt; font-weight : 900; margin-bottom: 20pt } .pageSubTitle { color : blue; line-height: 100%; font-size: 24pt; font-weight : 900 } .openChapter { color : blue; line-height: 125%; font-weight : 900 } .openSection { color : blue; line-height: 125%; font-weight : 900 } .info { color : black; line-height: 110%; font-size: 10pt; font-weight : 100 } p { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } blockquote { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } .opscript { margin-left: 3%; margin-right: 3%; } .opscript p { margin-top: 0.7em } .navbar { background: black; color: white; font-weight: bold } .warning { color: red; text-align: Center;} a,a:visited { color: blue } </style> <link rel="prev" href="struct-use-07-b.html" /> <link rel="index" href="index.html" /> <link rel="next" href="struct-use-09-b.html" /> <script src="../resources/testharnessreport.js"></script> </head> <body class="bodytext"> <div class="linkbar"> <p>Specification link: <a target="spec" href="http://www.w3.org/TR/SVG11/struct.html#UseElement">5.6 The 'use' element</a></p> <p> <a href="struct-use-07-b.html" rel="prev">struct-use-07-b ←</a> <a href="index.html" rel="index">index</a> <a href="struct-use-09-b.html" rel="next">→ struct-use-09-b</a> </p> </div> <div> <br /> <p class="warning"> Tests that contain the draft-watermark are under development and may be incorrectly testing a feature. </p> </div> <table align="center" border="0" cellspacing="0" cellpadding="10"> <tr> <td align="center" colspan="3"> <table border="0" cellpadding="8"> <tr> <td align="center" colspan="2" class="pageTitle"> <h1>struct-use-08-b.svg</h1> </td> </tr> <tr class="navbar"> <td align="center"> SVG Image </td> <td align="center"> PNG Image </td> </tr> <tr> <td align="right"> <!--[if IE]> <object src="../../svg/struct-use-08-b.svg" width="480" height="360" classid="image/svg+xml"><p style="font-size:300%;color:red">FAIL</p> <![endif] <!--[if !IE]>--> <object data="../../svg/struct-use-08-b.svg" width="480" height="360" type="image/svg+xml"><p style="font-size:300%;color:red">FAIL</p> <!--<![endif]--> </object> </td> <td align="left"> <img alt="raster image of struct-use-08-b.svg" src="../../png/struct-use-08-b.png" width="480" height="360"/> </td> </tr> </table> </td> </tr> </table> <div class="opscript"> <h2 id="operatorscript"> Operator Script </h2> <div> <p> [[Describe how to use the here. The instructions should specify any steps requied to run the test or any manual operation that need to be performed to run the test.]] </p> </div> <h2 id="passcriteria"> Pass Criteria </h2> <div> <p> [[Describe the pass criteria of the test here. The pass criteria is what should be displayed when the test is run.]] </p> </div> <h2 id="testdescription"> Test Description </h2> <div> <p> [[Describe which section and what specific assertion is being tested by the test. If the test has a number of sub tests, multiple "testComponent" elements can be specified within the "testDescription" element.]] </p> </div> </div> <br/> <div class="linkbar"> <p> <a href="struct-use-07-b.html" rel="prev">struct-use-07-b ←</a> <a href="index.html" rel="index">index</a> <a href="struct-use-09-b.html" rel="next">→ struct-use-09-b</a> </p> </div> </body> </html>
#include "<API key>.h" #include "mitkTestingMacros.h" int <API key>(int /*argc*/, char * /*argv*/ []) { MITK_TEST_BEGIN("CoreObjectFactory") mitk::CoreObjectFactory::Pointer instance = mitk::CoreObjectFactory::GetInstance(); <API key>(instance.IsNotNull(), "Testing instantiation"); MITK_TEST_CONDITION(strcmp(instance->GetNameOfClass(), "CoreObjectFactory") == 0, "Is this a CoreObjectFactory?"); MITK_TEST_END() }
<?php namespace Pimcore\Model\Document\Tag; use Pimcore\Model; class Input extends Model\Document\Tag { /** * Contains the text for this element * * @var integer */ public $text = ""; /** * @see Document\Tag\TagInterface::getType * @return string */ public function getType() { return "input"; } /** * @see Document\Tag\TagInterface::getData * @return mixed */ public function getData() { return $this->text; } /** * @see Document\Tag\TagInterface::frontend * @return string */ public function frontend() { $options = $this->getOptions(); $text = $this->text; if (isset($options["htmlspecialchars"]) AND $options["htmlspecialchars"] !== false) { $text = htmlspecialchars($this->text); } return $text; } public function getDataEditmode() { return htmlentities($this->text); } /** * @see Document\Tag\TagInterface::setDataFromResource * @param mixed $data * @return void */ public function setDataFromResource($data) { $this->text = $data; return $this; } /** * @see Document\Tag\TagInterface::setDataFromEditmode * @param mixed $data * @return void */ public function setDataFromEditmode($data) { $data = html_entity_decode($data, ENT_HTML5); // this is because the input is now an div contenteditable -> therefore in entities $this->text = $data; return $this; } /** * @return boolean */ public function isEmpty() { return !(boolean) strlen($this->text); } /** * @param Model\Document\Webservice\Data\Document\Element $wsElement * @param null $idMapper * @throws \Exception */ public function <API key>($wsElement, $idMapper = null) { $data = $wsElement->value; if ($data->text === null or is_string($data->text)) { $this->text = $data->text; } else { throw new \Exception("cannot get values from web service import - invalid data"); } } }
using System.Collections.Generic; using GraphQL.Types; using OrchardCore.Apis.GraphQL; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.GraphQL.Queries.Types; using OrchardCore.Taxonomies.Models; namespace OrchardCore.Taxonomies.GraphQL { public class <API key> : ObjectGraphType<TaxonomyPart> { public <API key>() { Name = "TaxonomyPart"; Field(x => x.TermContentType); Field<ListGraphType<<API key>>, IEnumerable<ContentItem>>() .Name("contentItems") .Description("the content items") .PagingArguments() .Resolve(x => x.Page(x.Source.Terms)); } } }
using System; using System.Diagnostics; using System.Collections.Generic; using System.Text; using DDay.iCal; using System.Runtime.Serialization; using System.IO; using DDay.iCal.Serialization.iCalendar; namespace DDay.iCal { <summary> A class that represents the organizer of an event/todo/journal. </summary> [DebuggerDisplay("{Value}")] #if !SILVERLIGHT [Serializable] #endif public class Organizer : EncodableDataType, IOrganizer { #region IOrganizer Members virtual public Uri SentBy { get { return new Uri(Parameters.Get("SENT-BY")); } set { if (value != null) Parameters.Set("SENT-BY", value.OriginalString); else Parameters.Set("SENT-BY", (string)null); } } virtual public string CommonName { get { return Parameters.Get("CN"); } set { Parameters.Set("CN", value); } } virtual public Uri DirectoryEntry { get { return new Uri(Parameters.Get("DIR")); } set { if (value != null) Parameters.Set("DIR", value.OriginalString); else Parameters.Set("DIR", (string)null); } } virtual public Uri Value { get; set; } #endregion #region Constructors public Organizer() : base() { } public Organizer(string value) : this() { OrganizerSerializer serializer = new OrganizerSerializer(); CopyFrom(serializer.Deserialize(new StringReader(value)) as ICopyable); } #endregion #region Overrides public override bool Equals(object obj) { IOrganizer o = obj as IOrganizer; if (o != null) return object.Equals(Value, o.Value); return base.Equals(obj); } public override void CopyFrom(ICopyable obj) { base.CopyFrom(obj); IOrganizer o = obj as IOrganizer; if (o != null) { Value = o.Value; } } #endregion } }
(function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(true===c.data(b.target,a.widgetName+".preventClickEvent")){c.removeData(b.target,a.widgetName+".preventClickEvent");b.<API key>();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent= a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&&this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted= this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault();return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!(document.documentMode>=9)&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a); return a.preventDefault()}if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;a.target==this._mouseDownEvent.target&&c.data(a.target,this.widgetName+".preventClickEvent", true);this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery);
<!DOCTYPE html><!-- DO NOT EDIT. This file auto-generated by <API key>.js --><!-- Copyright 2017 The Closure Library Authors. All Rights Reserved. Use of this source code is governed by the Apache License, Version 2.0. See the COPYING file for details. --><html><head><meta charset="UTF-8"> <script src="../base.js"></script> <script>goog.require('goog.positioning.<API key>');</script> <title>Closure Unit Tests - goog.positioning.<API key></title><! Copyright 2017 The Closure Library Authors. All Rights Reserved. Use of this source code is governed by the Apache License, Version 2.0. See the COPYING file for details. </head><body><iframe id="frame1" src="<API key>.html" style="width: 200px; height: 200px;"> </iframe></body></html>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//CL//DTD XHTML 1.0 Transitional plus Embed//EN" "http: <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/> <meta name="description" content="W3C SVG 1.1 2nd Edition Embedded Test Suite"/> <title> SVG 1.1 2nd Edition Test (&lt;embed&gt;): shapes-rect-02-t.svg </title> <style type="text/css"> <! .bodytext { font-family:verdana, helvetica, sans-serif; font-size: 12pt; line-height: 125%; text-align: Left; margin-top: 0; margin-bottom: 0 } .pageTitle { line-height: 150%; font-size: 20pt; font-weight : 900; margin-bottom: 20pt } .pageSubTitle { color : blue; line-height: 100%; font-size: 24pt; font-weight : 900 } .openChapter { color : blue; line-height: 125%; font-weight : 900 } .openSection { color : blue; line-height: 125%; font-weight : 900 } .info { color : black; line-height: 110%; font-size: 10pt; font-weight : 100 } p { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } blockquote { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } .opscript { margin-left: 3%; margin-right: 3%; } .opscript p { margin-top: 0.7em } .navbar { background: black; color: white; font-weight: bold } .warning { color: red; text-align: Center;} a,a:visited { color: blue } </style> <link rel="prev" href="shapes-rect-01-t.html" /> <link rel="index" href="index.html" /> <link rel="next" href="shapes-rect-03-t.html" /> <script src="../resources/testharnessreport.js"></script> </head> <body class="bodytext"> <div class="linkbar"> <p>Specification link: <a target="spec" href="http://www.w3.org/TR/SVG11/shapes.html#RectElement">9.2 The 'rect' element</a></p> <p> <a href="shapes-rect-01-t.html" rel="prev">shapes-rect-01-t ←</a> <a href="index.html" rel="index">index</a> <a href="shapes-rect-03-t.html" rel="next">→ shapes-rect-03-t</a> </p> </div> <div> <br /> <p class="warning"> Tests that contain the draft-watermark are under development and may be incorrectly testing a feature. </p> </div> <table align="center" border="0" cellspacing="0" cellpadding="10"> <tr> <td align="center" colspan="3"> <table border="0" cellpadding="8"> <tr> <td align="center" colspan="2" class="pageTitle"> <h1>shapes-rect-02-t.svg</h1> </td> </tr> <tr class="navbar"> <td align="center"> SVG Image </td> <td align="center"> PNG Image </td> </tr> <tr> <td align="right"> <embed src="../../svg/shapes-rect-02-t.svg" width="480" height="360"/> </td> <td align="left"> <img alt="raster image of shapes-rect-02-t.svg" src="../../png/shapes-rect-02-t.png" width="480" height="360"/> </td> </tr> </table> </td> </tr> </table> <div class="opscript"> <h2 id="operatorscript"> Operator Script </h2> <div> <p> Run the test. No interaction required. </p> </div> <h2 id="passcriteria"> Pass Criteria </h2> <div> <p> There should be four green rectangles visible, two of them should have rounded corners. </p> </div> <h2 id="testdescription"> Test Description </h2> <div> <p> Test x, y, width, height, rx and ry default/lacuna values on a rect element. </p> </div> </div> <br/> <div class="linkbar"> <p> <a href="shapes-rect-01-t.html" rel="prev">shapes-rect-01-t ←</a> <a href="index.html" rel="index">index</a> <a href="shapes-rect-03-t.html" rel="next">→ shapes-rect-03-t</a> </p> </div> </body> </html>
<!DOCTYPE HTML> <html> <head> <title> Encodings test suite: UTF-8 RU (autodetect) </title> </head> <body> <h2>Encoding: UTF-8 RU (autodetect)</h2> <p>The text in the iframe below should look similar to the reference rendering at the bottom.</p> <h2>Test</h2> <iframe style="border: 1px solid black" src="UTF-8_RU/UTF-8_RU_autodetect.html"></iframe><br /> <h2>Reference rendering</h2> <img style="border: 1px solid black" src="UTF-8_RU/UTF-8_RU.jpg"/> </body> </html>
#ifndef <API key> #define <API key> #include "base/basictypes.h" #include "base/memory/scoped_ptr.h" #include "ui/events/gesture_detection/<API key>.h" #include "ui/events/gesture_detection/gesture_detector.h" #include "ui/events/gesture_detection/gesture_event_data.h" #include "ui/events/gesture_detection/<API key>.h" #include "ui/events/gesture_detection/<API key>.h" #include "ui/gfx/display.h" namespace ui { class <API key> <API key> { public: virtual ~<API key>() {} virtual void OnGestureEvent(const GestureEventData& gesture) = 0; }; // Given a stream of |MotionEvent|'s, provides gesture detection and gesture // event dispatch. class <API key> GestureProvider { public: struct <API key> Config { Config(); ~Config(); gfx::Display display; GestureDetector::Config <API key>; <API key>::Config <API key>; // If |disable_click_delay| is true and double-tap support is disabled, // there will be no delay before tap events. When double-tap support is // enabled, there will always be a delay before a tap event is fired, in // order to allow the double tap gesture to occur without firing any tap // events. bool disable_click_delay; // If |<API key>| is true, fire an ET_GESTURE_BEGIN // event for every added touch point, and an ET_GESTURE_END event for every // removed touch point. This requires one ACTION_CANCEL event to be sent per // touch point, which only occurs on Aura. Defaults to false. bool <API key>; // The min and max size (both length and width, in dips) of the generated // bounding box for all gesture types. This is useful for touch streams // that may report zero or unreasonably small or large touch sizes. // Note that these bounds are only applied for touch or unknown tool types; // mouse and stylus-derived gestures will not be affected. // Both values default to 0 (disabled). float <API key>; float <API key>; }; GestureProvider(const Config& config, <API key>* client); ~GestureProvider(); // Handle the incoming MotionEvent, returning false if the event could not // be handled. bool OnTouchEvent(const MotionEvent& event); // Update whether multi-touch pinch zoom is supported by the platform. void <API key>(bool enabled); // Update whether double-tap gestures are supported by the platform. void <API key>(bool enabled); // Update whether double-tap gesture detection should be suppressed, e.g., // if the page scale is fixed or the page has a mobile viewport. This disables // the tap delay, allowing rapid and responsive single-tap gestures. void <API key>(bool enabled); // Whether a scroll gesture is in-progress. bool IsScrollInProgress() const; // Whether a pinch gesture is in-progress (i.e. a pinch update has been // forwarded and detection is still active). bool IsPinchInProgress() const; // Whether a double-tap gesture is in-progress (either double-tap or // double-tap drag zoom). bool <API key>() const; // May be NULL if there is no currently active touch sequence. const ui::MotionEvent* current_down_event() const { return current_down_event_.get(); } private: void <API key>(const Config& config); bool CanHandle(const MotionEvent& event) const; void Fling(const MotionEvent& e, float velocity_x, float velocity_y); void Send(GestureEventData gesture); bool <API key>(const MotionEvent& event); void <API key>(const MotionEvent& event, bool <API key>); void <API key>(const MotionEvent& event); void <API key>(const MotionEvent& event); void <API key>(); <API key>* const client_; class GestureListenerImpl; friend class GestureListenerImpl; scoped_ptr<GestureListenerImpl> gesture_listener_; class <API key>; friend class <API key>; scoped_ptr<<API key>> <API key>; scoped_ptr<MotionEvent> current_down_event_; // Whether the respective {SCROLL,PINCH}_BEGIN gestures have been terminated // with a {SCROLL,PINCH}_END. bool <API key>; bool pinch_in_progress_; // Whether double-tap gesture detection is currently supported. bool <API key>; bool <API key>; // Keeps track of the current GESTURE_LONG_PRESS event. If a context menu is // opened after a GESTURE_LONG_PRESS, this is used to insert a // GESTURE_TAP_CANCEL for removing any ::active styling. base::TimeTicks <API key>; const bool <API key>; const float <API key>; const float <API key>; }; } // namespace ui #endif // <API key>
#include <string.h> #include <sys/types.h> void * bcopy(void const *src, void *dest, size_t count) { return memcpy(dest, src, count); }
// Use of this source code is governed by a BSD-style package types import ( "exec" "go/ast" "io/ioutil" "path/filepath" "runtime" "strings" "testing" "time" ) var gcName, gcPath string // compiler name and path func init() { // determine compiler switch runtime.GOARCH { case "386": gcName = "8g" case "amd64": gcName = "6g" case "arm": gcName = "5g" default: gcName = "<API key>" gcPath = gcName return } gcPath, _ = exec.LookPath(gcName) } func compile(t *testing.T, dirname, filename string) { cmd := exec.Command(gcPath, filename) cmd.Dir = dirname out, err := cmd.CombinedOutput() if err != nil { t.Errorf("%s %s failed: %s", gcName, filename, err) return } t.Logf("%s", string(out)) } // Use the same global imports map for all tests. The effect is // as if all tested packages were imported into a single package. var imports = make(map[string]*ast.Object) func testPath(t *testing.T, path string) bool { _, err := GcImporter(imports, path) if err != nil { t.Errorf("testPath(%s): %s", path, err) return false } return true } const maxTime = 3e9 // maximum allotted testing time in ns func testDir(t *testing.T, dir string, endTime int64) (nimports int) { dirname := filepath.Join(pkgRoot, dir) list, err := ioutil.ReadDir(dirname) if err != nil { t.Errorf("testDir(%s): %s", dirname, err) } for _, f := range list { if time.Nanoseconds() >= endTime { t.Log("testing time used up") return } switch { case f.IsRegular(): // try extensions for _, ext := range pkgExts { if strings.HasSuffix(f.Name, ext) { name := f.Name[0 : len(f.Name)-len(ext)] // remove extension if testPath(t, filepath.Join(dir, name)) { nimports++ } } } case f.IsDirectory(): nimports += testDir(t, filepath.Join(dir, f.Name), endTime) } } return } func TestGcImport(t *testing.T) { compile(t, "testdata", "exports.go") nimports := 0 if testPath(t, "./testdata/exports") { nimports++ } nimports += testDir(t, "", time.Nanoseconds()+maxTime) // installed packages t.Logf("tested %d imports", nimports) }
namespace OrchardCore.Deployment.ViewModels { public class <API key> { public string RecipeName { get; set; } public string DisplayName { get; set; } public string Description { get; set; } public string Author { get; set; } public string WebSite { get; set; } public string Version { get; set; } public bool IsSetupRecipe { get; set; } public string Categories { get; set; } public string Tags { get; set; } } }
#include "onyx_int.h" #include "vp8/common/threading.h" #include "vp8/common/common.h" #include "vp8/common/extend.h" #include "bitstream.h" #include "encodeframe.h" #if CONFIG_MULTITHREAD extern void <API key>(VP8_COMP *cpi, MACROBLOCK *x, int ok_to_skip); extern void <API key>(VP8_COMP *cpi, VP8_COMMON *cm); static THREAD_FUNCTION thread_loopfilter(void *p_data) { VP8_COMP *cpi = (VP8_COMP *)(((LPFTHREAD_DATA *)p_data)->ptr1); VP8_COMMON *cm = &cpi->common; while (1) { if (cpi->b_multi_threaded == 0) break; if (sem_wait(&cpi->h_event_start_lpf) == 0) { if (cpi->b_multi_threaded == 0) /* we're shutting down */ break; <API key>(cpi, cm); sem_post(&cpi->h_event_end_lpf); } } return 0; } static THREAD_FUNCTION <API key>(void *p_data) { int ithread = ((ENCODETHREAD_DATA *)p_data)->ithread; VP8_COMP *cpi = (VP8_COMP *)(((ENCODETHREAD_DATA *)p_data)->ptr1); MB_ROW_COMP *mbri = (MB_ROW_COMP *)(((ENCODETHREAD_DATA *)p_data)->ptr2); <API key> mb_row_left_context; while (1) { if (cpi->b_multi_threaded == 0) break; if (sem_wait(&cpi-><API key>[ithread]) == 0) { const int nsync = cpi->mt_sync_range; VP8_COMMON *cm = &cpi->common; int mb_row; MACROBLOCK *x = &mbri->mb; MACROBLOCKD *xd = &x->e_mbd; TOKENEXTRA *tp ; #if <API key> & <API key> TOKENEXTRA *tp_start = cpi->tok + (1 + ithread) * (16 * 24); const int num_part = (1 << cm-><API key>); #endif int *segment_counts = mbri->segment_counts; int *totalrate = &mbri->totalrate; if (cpi->b_multi_threaded == 0) /* we're shutting down */ break; for (mb_row = ithread + 1; mb_row < cm->mb_rows; mb_row += (cpi-><API key> + 1)) { int recon_yoffset, recon_uvoffset; int mb_col; int ref_fb_idx = cm->lst_fb_idx; int dst_fb_idx = cm->new_fb_idx; int recon_y_stride = cm->yv12_fb[ref_fb_idx].y_stride; int recon_uv_stride = cm->yv12_fb[ref_fb_idx].uv_stride; int map_index = (mb_row * cm->mb_cols); volatile const int *<API key>; volatile int *current_mb_col = &cpi->mt_current_mb_col[mb_row]; #if (<API key> & <API key>) vp8_writer *w = &cpi->bc[1 + (mb_row % num_part)]; #else tp = cpi->tok + (mb_row * (cm->mb_cols * 16 * 24)); cpi->tplist[mb_row].start = tp; #endif <API key> = &cpi->mt_current_mb_col[mb_row - 1]; /* reset above block coeffs */ xd->above_context = cm->above_context; xd->left_context = &mb_row_left_context; vp8_zero(mb_row_left_context); xd->up_available = (mb_row != 0); recon_yoffset = (mb_row * recon_y_stride * 16); recon_uvoffset = (mb_row * recon_uv_stride * 8); /* Set the mb activity pointer to the start of the row. */ x->mb_activity_ptr = &cpi->mb_activity_map[map_index]; /* for each macroblock col in image */ for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) { *current_mb_col = mb_col - 1; if ((mb_col & (nsync - 1)) == 0) { while (mb_col > (*<API key> - nsync)) { x86_pause_hint(); thread_sleep(0); } } #if <API key> & <API key> tp = tp_start; #endif /* Distance of Mb to the various image edges. * These specified to 8th pel as they are always compared * to values that are in 1/8th pel units */ xd->mb_to_left_edge = -((mb_col * 16) << 3); xd->mb_to_right_edge = ((cm->mb_cols - 1 - mb_col) * 16) << 3; xd->mb_to_top_edge = -((mb_row * 16) << 3); xd->mb_to_bottom_edge = ((cm->mb_rows - 1 - mb_row) * 16) << 3; /* Set up limit values for motion vectors used to prevent * them extending outside the UMV borders */ x->mv_col_min = -((mb_col * 16) + (VP8BORDERINPIXELS - 16)); x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16) + (VP8BORDERINPIXELS - 16); x->mv_row_min = -((mb_row * 16) + (VP8BORDERINPIXELS - 16)); x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16) + (VP8BORDERINPIXELS - 16); xd->dst.y_buffer = cm->yv12_fb[dst_fb_idx].y_buffer + recon_yoffset; xd->dst.u_buffer = cm->yv12_fb[dst_fb_idx].u_buffer + recon_uvoffset; xd->dst.v_buffer = cm->yv12_fb[dst_fb_idx].v_buffer + recon_uvoffset; xd->left_available = (mb_col != 0); x->rddiv = cpi->RDDIV; x->rdmult = cpi->RDMULT; /* Copy current mb to a buffer */ vp8_copy_mem16x16(x->src.y_buffer, x->src.y_stride, x->thismb, 16); if (cpi->oxcf.tuning == VP8_TUNE_SSIM) <API key>(cpi, x); /* Is segmentation enabled */ /* MB level adjustment to quantizer */ if (xd-><API key>) { /* Code to set segment id in xd->mbmi.segment_id for * current MB (with range checking) */ if (cpi->segmentation_map[map_index + mb_col] <= 3) xd->mode_info_context->mbmi.segment_id = cpi->segmentation_map[map_index + mb_col]; else xd->mode_info_context->mbmi.segment_id = 0; <API key>(cpi, x, 1); } else /* Set to Segment 0 by default */ xd->mode_info_context->mbmi.segment_id = 0; x->active_ptr = cpi->active_map + map_index + mb_col; if (cm->frame_type == KEY_FRAME) { *totalrate += <API key>(cpi, x, &tp); #ifdef MODE_STATS y_modes[xd->mbmi.mode] ++; #endif } else { *totalrate += <API key>(cpi, x, &tp, recon_yoffset, recon_uvoffset, mb_row, mb_col); #ifdef MODE_STATS inter_y_modes[xd->mbmi.mode] ++; if (xd->mbmi.mode == SPLITMV) { int b; for (b = 0; b < xd->mbmi.partition_count; b++) { inter_b_modes[x->partition->bmi[b].mode] ++; } } #endif // Keep track of how many (consecutive) times a block // is coded as ZEROMV_LASTREF, for base layer frames. // Reset to 0 if its coded as anything else. if (cpi->current_layer == 0) { if (xd->mode_info_context->mbmi.mode == ZEROMV && xd->mode_info_context->mbmi.ref_frame == LAST_FRAME) { // Increment, check for wrap-around. if (cpi->consec_zero_last[map_index+mb_col] < 255) cpi->consec_zero_last[map_index+mb_col] += 1; } else { cpi->consec_zero_last[map_index+mb_col] = 0; } } /* Special case code for cyclic refresh * If cyclic update enabled then copy * xd->mbmi.segment_id; (which may have been updated * based on mode during * <API key>()) back into the * global segmentation map */ if ((cpi->current_layer == 0) && (cpi-><API key> && xd-><API key>)) { const MB_MODE_INFO * mbmi = &xd->mode_info_context->mbmi; cpi->segmentation_map[map_index + mb_col] = mbmi->segment_id; /* If the block has been refreshed mark it as clean * (the magnitude of the -ve influences how long it * will be before we consider another refresh): * Else if it was coded (last frame 0,0) and has * not already been refreshed then mark it as a * candidate for cleanup next time (marked 0) else * mark it as dirty (1). */ if (mbmi->segment_id) cpi->cyclic_refresh_map[map_index + mb_col] = -1; else if ((mbmi->mode == ZEROMV) && (mbmi->ref_frame == LAST_FRAME)) { if (cpi->cyclic_refresh_map[map_index + mb_col] == 1) cpi->cyclic_refresh_map[map_index + mb_col] = 0; } else cpi->cyclic_refresh_map[map_index + mb_col] = 1; } } #if <API key> & <API key> /* pack tokens for this MB */ { int tok_count = tp - tp_start; pack_tokens(w, tp_start, tok_count); } #else cpi->tplist[mb_row].stop = tp; #endif /* Increment pointer into gf usage flags structure. */ x->gf_active_ptr++; /* Increment the activity mask pointers. */ x->mb_activity_ptr++; /* adjust to the next column of macroblocks */ x->src.y_buffer += 16; x->src.u_buffer += 8; x->src.v_buffer += 8; recon_yoffset += 16; recon_uvoffset += 8; /* Keep track of segment usage */ segment_counts[xd->mode_info_context->mbmi.segment_id]++; /* skip to next mb */ xd->mode_info_context++; x->partition_info++; xd->above_context++; } vp8_extend_mb_row( &cm->yv12_fb[dst_fb_idx], xd->dst.y_buffer + 16, xd->dst.u_buffer + 8, xd->dst.v_buffer + 8); *current_mb_col = mb_col + nsync; /* this is to account for the border */ xd->mode_info_context++; x->partition_info++; x->src.y_buffer += 16 * x->src.y_stride * (cpi-><API key> + 1) - 16 * cm->mb_cols; x->src.u_buffer += 8 * x->src.uv_stride * (cpi-><API key> + 1) - 8 * cm->mb_cols; x->src.v_buffer += 8 * x->src.uv_stride * (cpi-><API key> + 1) - 8 * cm->mb_cols; xd->mode_info_context += xd->mode_info_stride * cpi-><API key>; x->partition_info += xd->mode_info_stride * cpi-><API key>; x->gf_active_ptr += cm->mb_cols * cpi-><API key>; if (mb_row == cm->mb_rows - 1) { sem_post(&cpi-><API key>); /* signal frame encoding end */ } } } } /* printf("exit thread %d\n", ithread); */ return 0; } static void setup_mbby_copy(MACROBLOCK *mbdst, MACROBLOCK *mbsrc) { MACROBLOCK *x = mbsrc; MACROBLOCK *z = mbdst; int i; z->ss = x->ss; z->ss_count = x->ss_count; z->searches_per_step = x->searches_per_step; z->errorperbit = x->errorperbit; z->sadperbit16 = x->sadperbit16; z->sadperbit4 = x->sadperbit4; /* z->mv_col_min = x->mv_col_min; z->mv_col_max = x->mv_col_max; z->mv_row_min = x->mv_row_min; z->mv_row_max = x->mv_row_max; */ z->short_fdct4x4 = x->short_fdct4x4; z->short_fdct8x4 = x->short_fdct8x4; z->short_walsh4x4 = x->short_walsh4x4; z->quantize_b = x->quantize_b; z->quantize_b_pair = x->quantize_b_pair; z->optimize = x->optimize; /* z->mvc = x->mvc; z->src.y_buffer = x->src.y_buffer; z->src.u_buffer = x->src.u_buffer; z->src.v_buffer = x->src.v_buffer; */ z->mvcost[0] = x->mvcost[0]; z->mvcost[1] = x->mvcost[1]; z->mvsadcost[0] = x->mvsadcost[0]; z->mvsadcost[1] = x->mvsadcost[1]; z->token_costs = x->token_costs; z->inter_bmode_costs = x->inter_bmode_costs; z->mbmode_cost = x->mbmode_cost; z->intra_uv_mode_cost = x->intra_uv_mode_cost; z->bmode_costs = x->bmode_costs; for (i = 0; i < 25; i++) { z->block[i].quant = x->block[i].quant; z->block[i].quant_fast = x->block[i].quant_fast; z->block[i].quant_shift = x->block[i].quant_shift; z->block[i].zbin = x->block[i].zbin; z->block[i].zrun_zbin_boost = x->block[i].zrun_zbin_boost; z->block[i].round = x->block[i].round; z->block[i].src_stride = x->block[i].src_stride; } z->q_index = x->q_index; z->act_zbin_adj = x->act_zbin_adj; z->last_act_zbin_adj = x->last_act_zbin_adj; { MACROBLOCKD *xd = &x->e_mbd; MACROBLOCKD *zd = &z->e_mbd; /* zd->mode_info_context = xd->mode_info_context; zd->mode_info = xd->mode_info; zd->mode_info_stride = xd->mode_info_stride; zd->frame_type = xd->frame_type; zd->up_available = xd->up_available ; zd->left_available = xd->left_available; zd->left_context = xd->left_context; zd->last_frame_dc = xd->last_frame_dc; zd->last_frame_dccons = xd->last_frame_dccons; zd->gold_frame_dc = xd->gold_frame_dc; zd->gold_frame_dccons = xd->gold_frame_dccons; zd->mb_to_left_edge = xd->mb_to_left_edge; zd->mb_to_right_edge = xd->mb_to_right_edge; zd->mb_to_top_edge = xd->mb_to_top_edge ; zd->mb_to_bottom_edge = xd->mb_to_bottom_edge; zd->gf_active_ptr = xd->gf_active_ptr; zd->frames_since_golden = xd->frames_since_golden; zd-><API key> = xd-><API key>; */ zd->subpixel_predict = xd->subpixel_predict; zd->subpixel_predict8x4 = xd->subpixel_predict8x4; zd->subpixel_predict8x8 = xd->subpixel_predict8x8; zd-><API key> = xd-><API key>; zd-><API key> = xd-><API key>; zd-><API key> = xd-><API key>; vpx_memcpy(zd-><API key>, xd-><API key>, sizeof(xd-><API key>)); vpx_memcpy(zd->dequant_y1_dc, xd->dequant_y1_dc, sizeof(xd->dequant_y1_dc)); vpx_memcpy(zd->dequant_y1, xd->dequant_y1, sizeof(xd->dequant_y1)); vpx_memcpy(zd->dequant_y2, xd->dequant_y2, sizeof(xd->dequant_y2)); vpx_memcpy(zd->dequant_uv, xd->dequant_uv, sizeof(xd->dequant_uv)); #if 1 /*TODO: Remove dequant from BLOCKD. This is a temporary solution until * the quantizer code uses a passed in pointer to the dequant constants. * This will also require modifications to the x86 and neon assembly. * */ for (i = 0; i < 16; i++) zd->block[i].dequant = zd->dequant_y1; for (i = 16; i < 24; i++) zd->block[i].dequant = zd->dequant_uv; zd->block[24].dequant = zd->dequant_y2; #endif vpx_memcpy(z->rd_threshes, x->rd_threshes, sizeof(x->rd_threshes)); vpx_memcpy(z->rd_thresh_mult, x->rd_thresh_mult, sizeof(x->rd_thresh_mult)); z->zbin_over_quant = x->zbin_over_quant; z-><API key> = x-><API key>; z->zbin_mode_boost = x->zbin_mode_boost; vpx_memset(z->error_bins, 0, sizeof(z->error_bins)); } } void <API key>(VP8_COMP *cpi, MACROBLOCK *x, MB_ROW_COMP *mbr_ei, int count ) { VP8_COMMON *const cm = & cpi->common; MACROBLOCKD *const xd = & x->e_mbd; int i; for (i = 0; i < count; i++) { MACROBLOCK *mb = & mbr_ei[i].mb; MACROBLOCKD *mbd = &mb->e_mbd; mbd->subpixel_predict = xd->subpixel_predict; mbd->subpixel_predict8x4 = xd->subpixel_predict8x4; mbd->subpixel_predict8x8 = xd->subpixel_predict8x8; mbd-><API key> = xd-><API key>; mb->gf_active_ptr = x->gf_active_ptr; vpx_memset(mbr_ei[i].segment_counts, 0, sizeof(mbr_ei[i].segment_counts)); mbr_ei[i].totalrate = 0; mb->partition_info = x->pi + x->e_mbd.mode_info_stride * (i + 1); mbd->mode_info_context = cm->mi + x->e_mbd.mode_info_stride * (i + 1); mbd->mode_info_stride = cm->mode_info_stride; mbd->frame_type = cm->frame_type; mb->src = * cpi->Source; mbd->pre = cm->yv12_fb[cm->lst_fb_idx]; mbd->dst = cm->yv12_fb[cm->new_fb_idx]; mb->src.y_buffer += 16 * x->src.y_stride * (i + 1); mb->src.u_buffer += 8 * x->src.uv_stride * (i + 1); mb->src.v_buffer += 8 * x->src.uv_stride * (i + 1); <API key>(mb); mbd->left_context = &cm->left_context; mb->mvc = cm->fc.mvc; setup_mbby_copy(&mbr_ei[i].mb, x); mbd->fullpixel_mask = 0xffffffff; if(cm->full_pixel) mbd->fullpixel_mask = 0xfffffff8; vp8_zero(mb->coef_counts); vp8_zero(x->ymode_count); mb->skip_true_count = 0; vp8_zero(mb->MVcount); mb->prediction_error = 0; mb->intra_error = 0; vp8_zero(mb-><API key>); mb->mbs_tested_so_far = 0; } } int <API key>(VP8_COMP *cpi) { const VP8_COMMON * cm = &cpi->common; cpi->b_multi_threaded = 0; cpi-><API key> = 0; cpi->b_lpf_running = 0; if (cm-><API key> > 1 && cpi->oxcf.multi_threaded > 1) { int ithread; int th_count = cpi->oxcf.multi_threaded - 1; int rc = 0; /* don't allocate more threads than cores available */ if (cpi->oxcf.multi_threaded > cm-><API key>) th_count = cm-><API key> - 1; /* we have th_count + 1 (main) threads processing one row each */ /* no point to have more threads than the sync range allows */ if(th_count > ((cm->mb_cols / cpi->mt_sync_range) - 1)) { th_count = (cm->mb_cols / cpi->mt_sync_range) - 1; } if(th_count == 0) return 0; CHECK_MEM_ERROR(cpi->h_encoding_thread, vpx_malloc(sizeof(pthread_t) * th_count)); CHECK_MEM_ERROR(cpi-><API key>, vpx_malloc(sizeof(sem_t) * th_count)); CHECK_MEM_ERROR(cpi->mb_row_ei, vpx_memalign(32, sizeof(MB_ROW_COMP) * th_count)); vpx_memset(cpi->mb_row_ei, 0, sizeof(MB_ROW_COMP) * th_count); CHECK_MEM_ERROR(cpi->en_thread_data, vpx_malloc(sizeof(ENCODETHREAD_DATA) * th_count)); sem_init(&cpi-><API key>, 0, 0); cpi->b_multi_threaded = 1; cpi-><API key> = th_count; /* printf("[VP8:] multi_threaded encoding is enabled with %d threads\n\n", (cpi-><API key> +1)); */ for (ithread = 0; ithread < th_count; ithread++) { ENCODETHREAD_DATA *ethd = &cpi->en_thread_data[ithread]; /* Setup block ptrs and offsets */ <API key>(&cpi->mb_row_ei[ithread].mb); <API key>(&cpi->mb_row_ei[ithread].mb.e_mbd); sem_init(&cpi-><API key>[ithread], 0, 0); ethd->ithread = ithread; ethd->ptr1 = (void *)cpi; ethd->ptr2 = (void *)&cpi->mb_row_ei[ithread]; rc = pthread_create(&cpi->h_encoding_thread[ithread], 0, <API key>, ethd); if(rc) break; } if(rc) { /* shutdown other threads */ cpi->b_multi_threaded = 0; for(--ithread; ithread >= 0; ithread { pthread_join(cpi->h_encoding_thread[ithread], 0); sem_destroy(&cpi-><API key>[ithread]); } sem_destroy(&cpi-><API key>); /* free thread related resources */ vpx_free(cpi-><API key>); vpx_free(cpi->h_encoding_thread); vpx_free(cpi->mb_row_ei); vpx_free(cpi->en_thread_data); return -1; } { LPFTHREAD_DATA * lpfthd = &cpi->lpf_thread_data; sem_init(&cpi->h_event_start_lpf, 0, 0); sem_init(&cpi->h_event_end_lpf, 0, 0); lpfthd->ptr1 = (void *)cpi; rc = pthread_create(&cpi->h_filter_thread, 0, thread_loopfilter, lpfthd); if(rc) { /* shutdown other threads */ cpi->b_multi_threaded = 0; for(--ithread; ithread >= 0; ithread { sem_post(&cpi-><API key>[ithread]); pthread_join(cpi->h_encoding_thread[ithread], 0); sem_destroy(&cpi-><API key>[ithread]); } sem_destroy(&cpi-><API key>); sem_destroy(&cpi->h_event_end_lpf); sem_destroy(&cpi->h_event_start_lpf); /* free thread related resources */ vpx_free(cpi-><API key>); vpx_free(cpi->h_encoding_thread); vpx_free(cpi->mb_row_ei); vpx_free(cpi->en_thread_data); return -2; } } } return 0; } void <API key>(VP8_COMP *cpi) { if (cpi->b_multi_threaded) { /* shutdown other threads */ cpi->b_multi_threaded = 0; { int i; for (i = 0; i < cpi-><API key>; i++) { sem_post(&cpi-><API key>[i]); pthread_join(cpi->h_encoding_thread[i], 0); sem_destroy(&cpi-><API key>[i]); } sem_post(&cpi->h_event_start_lpf); pthread_join(cpi->h_filter_thread, 0); } sem_destroy(&cpi-><API key>); sem_destroy(&cpi->h_event_end_lpf); sem_destroy(&cpi->h_event_start_lpf); /* free thread related resources */ vpx_free(cpi-><API key>); vpx_free(cpi->h_encoding_thread); vpx_free(cpi->mb_row_ei); vpx_free(cpi->en_thread_data); } } #endif
// The primary entry point into fulfilling a GraphQL request. export { graphql } from './graphql'; // Produce a GraphQL type schema. export { GraphQLSchema } from './type/schema'; export { GraphQLScalarType, GraphQLObjectType, <API key>, GraphQLUnionType, GraphQLEnumType, <API key>, GraphQLList, GraphQLNonNull } from './type/definition'; export { GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLID } from './type/scalars';
#include <cstddef> // NULL #include <algorithm> #include <iomanip> #include <fstream> #include <errno.h> #include "Timer.hh" #include "LnaReaderCircular.hh" #include "NowayHmmReader.hh" #include "NowayLexiconReader.hh" #include "Expander.hh" using namespace std; class Main { public: Main(); void run(); void print_token(Lexicon::Token *token); NowayHmmReader hr; NowayLexiconReader lr; LnaReaderCircular lna; }; Main::Main() : hr(), lr(hr.hmm_map(), hr.hmms()), lna() { } void Main::print_token(Lexicon::Token *token) { std::cout.setf(std::cout.right, std::cout.adjustfield); std::cout.setf(std::cout.fixed, std::cout.floatfield); std::cout.precision(2); std::cout << token->log_prob << std::endl; std::vector<Lexicon::Path*> paths; for (Lexicon::Path *path = token->path; path != NULL; path = path->prev) paths.push_back(path); for (int i = paths.size() - 1; i >= 0; i Lexicon::Path *path = paths[i]; int start = path->frame; int end = token->frame; if (i > 0) end = paths[i-1]->frame; float log_prob; if (i > 0) log_prob = paths[i-1]->log_prob - paths[i]->log_prob; else log_prob = token->log_prob - paths[i]->log_prob; std::cout.setf(std::cout.left, std::cout.adjustfield); std::cout << setw(8) << start << setw(8) << end << setw(8) << end - start << setw(4) << hr.hmms()[paths[i]->hmm_id].label; std::cout << setw(10) << -log_prob << std::endl; } } void Main::run() { { std::cout << "load hmms" << std::endl; std::ifstream in("/home/neuro/thirsima/share/synt/pk_synt5.pho_mod"); if (!in) { std::cerr << "could not read hmm file" << std::endl; exit(1); } hr.read(in); } { std::cout << "load lexicon" << std::endl; // std::ifstream in("/home/neuro/thirsima/share/synt/iso64000.lex"); // std::ifstream in("/home/neuro/thirsima/share/synt/words20000.lex"); // std::ifstream in("synt.lex"); std::ifstream in("/home/neuro/thirsima/share/synt/pk_synt5.lex"); if (!in) { std::cerr << "could not open lex file" << std::endl; exit(1); } try { lr.read(in); } catch (std::exception &e) { std::cerr << e.what() << std::endl << lr.word() << std::endl; exit(1); } } lna.open("/home/neuro/thirsima/share/synt/pk_synt5.lna", 76, 1024*1024); std::cout << "expand" << std::endl; Expander ex(hr.hmms(), lr.lexicon(), lna); // Timer timer; // timer.start(); // timer.stop(); // std::cout << std::endl << timer.sec() << " seconds" << std::endl; // std::vector<Expander::Word*> &words = ex.words(); // int start = 0; // int length = 125 * 2; // std::cout.setf(std::cout.left, std::cout.adjustfield); // for (int i = 0; i < 100; i++) { // ex.expand(start, length); // std::sort(words.begin(), words.end(), Expander::WordCompare()); // Expander::Word *word = words[0]; // int old = start; // start += word->frames; // std::cout << setw(8) << old << setw(8) << start // << lr.vocabulary().word(word->word_id) << std::endl; ex.<API key>(8); ex.set_token_limit(300); ex.expand(0, 125 * 60 * 1); // minutes ex.sort_best_tokens(1); std::vector<Lexicon::Token*> &tokens = ex.tokens(); ex.debug_print_timit(tokens[0]); // std::vector<Expander::Word*> &words = ex.words(); // std::cout << tokens.size() << " tokens\n" << std::endl; // std::cout << words.size() << " words\n" << std::endl; // std::sort(words.begin(), words.end(), Expander::WordCompare()); // std::cout.setf(std::cout.left, std::cout.adjustfield); // std::cout.setf(std::cout.fixed, std::cout.floatfield); // std::cout.precision(2); // for (int i = 0; i < words.size(); i++) { // std::cout << setw(10) << words[i]->frames // << setw(10) << words[i]->avg_log_prob // << setw(10) << words[i]->log_prob // << lr.vocabulary().word(words[i]->word_id) // << std::endl; // ex.sort_best_tokens(tokens.size()); // for (int i = 0; i < tokens.size(); i++) // print_token(tokens[i]); // for (int t = 0; t < tokens.size(); t++) { // if (tokens[t]->node->next.size() == 0) { // std::cout << "token number " << t << std::endl; // print_token(tokens[t]); } int main(int argc, char *argv[]) { try { Main m; m.run(); } catch (exception &e) { cerr << e.what() << std::endl; cerr << strerror(errno) << std::endl; exit(1); } exit(0); }
set(<API key> "ALWAYS") set(<API key> "${CMAKE_BINARY_DIR}/prefix") install(DIRECTORY dir/ DESTINATION dir MESSAGE_NEVER)
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112-release) on Sat May 06 16:33:03 CEST 2017 --> <title>Constants.PreProcParam</title> <meta name="date" content="2017-05-06"> <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="Constants.PreProcParam"; } } catch(err) { } var methods = {"i0":9,"i1":9,"i2":9}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <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-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/echopen/asso/echopen/utils/Constants.ParseConstants.html" title="class in com.echopen.asso.echopen.utils"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/echopen/asso/echopen/utils/Constants.RulerParam.html" title="class in com.echopen.asso.echopen.utils"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/echopen/asso/echopen/utils/Constants.PreProcParam.html" target="_top">Frames</a></li> <li><a href="Constants.PreProcParam.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <div class="subTitle">com.echopen.asso.echopen.utils</div> <h2 title="Class Constants.PreProcParam" class="title">Class Constants.PreProcParam</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.echopen.asso.echopen.utils.Constants.PreProcParam</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../com/echopen/asso/echopen/utils/Constants.html" title="class in com.echopen.asso.echopen.utils">Constants</a></dd> </dl> <hr> <br> <pre>public static class <span class="typeNameLabel">Constants.PreProcParam</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="field.summary"> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#ADC_FREQUENCY_CLOCK">ADC_FREQUENCY_CLOCK</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#ANGLE_INIT">ANGLE_INIT</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static float</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#IMAGE_SIZE">IMAGE_SIZE</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#IMAGE_WIDTH">IMAGE_WIDTH</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#LOCAL_IMG_DATA">LOCAL_IMG_DATA</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#LOCAL_NUM_SAMPLES">LOCAL_NUM_SAMPLES</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#N_x">N_x</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#N_z">N_z</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.Integer</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#NUM_IMG_DATA">NUM_IMG_DATA</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#NUM_LINES">NUM_LINES</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.Integer</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#NUM_LINES_PER_IMAGE">NUM_LINES_PER_IMAGE</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#NUM_SAMPLES">NUM_SAMPLES</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.Integer</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#RADIAL_DATA_INIT">RADIAL_DATA_INIT</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#RADIAL_IMG_INIT">RADIAL_IMG_INIT</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#SAMPLING_FREQUENCY">SAMPLING_FREQUENCY</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#SCALE_FACTOR">SCALE_FACTOR</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#SCALE_IMG_FACTOR">SCALE_IMG_FACTOR</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#SPEED_OF_SOUND">SPEED_OF_SOUND</a></span></code> <div class="block">todo define the pre-processing params - largest number of pixels in x-direction - largest number of pixels in z-direction - number of weight coefficients</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static float</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#STEP_ANGLE_INIT">STEP_ANGLE_INIT</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#STEP_RADIAL_INIT">STEP_RADIAL_INIT</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#TCP_IMG_DATA">TCP_IMG_DATA</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#TCP_NUM_SAMPLES">TCP_NUM_SAMPLES</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#tmp_SAMPLING_POINTS">tmp_SAMPLING_POINTS</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#UDP_IMG_DATA">UDP_IMG_DATA</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#UDP_NUM_SAMPLES">UDP_NUM_SAMPLES</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <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="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#PreProcParam--">PreProcParam</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method.summary"> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>static double[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>--"><API key></a></span>()</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>static float[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>--"><API key></a></span>()</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>static int[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/echopen/asso/echopen/utils/Constants.PreProcParam.html#<API key>--"><API key></a></span>()</code>&nbsp;</td> </tr> </table> <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"> <ul class="blockList"> <li class="blockList"><a name="field.detail"> </a> <h3>Field Detail</h3> <a name="SPEED_OF_SOUND"> </a> <ul class="blockList"> <li class="blockList"> <h4>SPEED_OF_SOUND</h4> <pre>public static final&nbsp;int SPEED_OF_SOUND</pre> <div class="block">todo define the pre-processing params - largest number of pixels in x-direction - largest number of pixels in z-direction - number of weight coefficients</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.SPEED_OF_SOUND">Constant Field Values</a></dd> </dl> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;int <API key></pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.<API key>">Constant Field Values</a></dd> </dl> </li> </ul> <a name="SAMPLING_FREQUENCY"> </a> <ul class="blockList"> <li class="blockList"> <h4>SAMPLING_FREQUENCY</h4> <pre>public static final&nbsp;int SAMPLING_FREQUENCY</pre> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;int <API key></pre> </li> </ul> <a name="ADC_FREQUENCY_CLOCK"> </a> <ul class="blockList"> <li class="blockList"> <h4>ADC_FREQUENCY_CLOCK</h4> <pre>public static final&nbsp;double ADC_FREQUENCY_CLOCK</pre> </li> </ul> <a name="N_x"> </a> <ul class="blockList"> <li class="blockList"> <h4>N_x</h4> <pre>public static final&nbsp;int N_x</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.N_x">Constant Field Values</a></dd> </dl> </li> </ul> <a name="N_z"> </a> <ul class="blockList"> <li class="blockList"> <h4>N_z</h4> <pre>public static final&nbsp;int N_z</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.N_z">Constant Field Values</a></dd> </dl> </li> </ul> <a name="NUM_LINES"> </a> <ul class="blockList"> <li class="blockList"> <h4>NUM_LINES</h4> <pre>public static final&nbsp;int NUM_LINES</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.NUM_LINES">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IMAGE_SIZE"> </a> <ul class="blockList"> <li class="blockList"> <h4>IMAGE_SIZE</h4> <pre>public static final&nbsp;float IMAGE_SIZE</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.IMAGE_SIZE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IMAGE_WIDTH"> </a> <ul class="blockList"> <li class="blockList"> <h4>IMAGE_WIDTH</h4> <pre>public static final&nbsp;double IMAGE_WIDTH</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.IMAGE_WIDTH">Constant Field Values</a></dd> </dl> </li> </ul> <a name="NUM_SAMPLES"> </a> <ul class="blockList"> <li class="blockList"> <h4>NUM_SAMPLES</h4> <pre>public static&nbsp;int NUM_SAMPLES</pre> </li> </ul> <a name="NUM_IMG_DATA"> </a> <ul class="blockList"> <li class="blockList"> <h4>NUM_IMG_DATA</h4> <pre>public static&nbsp;int NUM_IMG_DATA</pre> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static&nbsp;java.lang.Integer <API key></pre> </li> </ul> <a name="NUM_LINES_PER_IMAGE"> </a> <ul class="blockList"> <li class="blockList"> <h4>NUM_LINES_PER_IMAGE</h4> <pre>public static&nbsp;java.lang.Integer NUM_LINES_PER_IMAGE</pre> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static&nbsp;java.lang.Integer <API key></pre> </li> </ul> <a name="SCALE_IMG_FACTOR"> </a> <ul class="blockList"> <li class="blockList"> <h4>SCALE_IMG_FACTOR</h4> <pre>public static&nbsp;int SCALE_IMG_FACTOR</pre> </li> </ul> <a name="LOCAL_NUM_SAMPLES"> </a> <ul class="blockList"> <li class="blockList"> <h4>LOCAL_NUM_SAMPLES</h4> <pre>public static final&nbsp;int LOCAL_NUM_SAMPLES</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.LOCAL_NUM_SAMPLES">Constant Field Values</a></dd> </dl> </li> </ul> <a name="LOCAL_IMG_DATA"> </a> <ul class="blockList"> <li class="blockList"> <h4>LOCAL_IMG_DATA</h4> <pre>public static final&nbsp;int LOCAL_IMG_DATA</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.LOCAL_IMG_DATA">Constant Field Values</a></dd> </dl> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;int <API key></pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.<API key>">Constant Field Values</a></dd> </dl> </li> </ul> <a name="TCP_NUM_SAMPLES"> </a> <ul class="blockList"> <li class="blockList"> <h4>TCP_NUM_SAMPLES</h4> <pre>public static final&nbsp;int TCP_NUM_SAMPLES</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.TCP_NUM_SAMPLES">Constant Field Values</a></dd> </dl> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;int <API key></pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.<API key>">Constant Field Values</a></dd> </dl> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;int <API key></pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.<API key>">Constant Field Values</a></dd> </dl> </li> </ul> <a name="TCP_IMG_DATA"> </a> <ul class="blockList"> <li class="blockList"> <h4>TCP_IMG_DATA</h4> <pre>public static final&nbsp;int TCP_IMG_DATA</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.TCP_IMG_DATA">Constant Field Values</a></dd> </dl> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;int <API key></pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.<API key>">Constant Field Values</a></dd> </dl> </li> </ul> <a name="UDP_NUM_SAMPLES"> </a> <ul class="blockList"> <li class="blockList"> <h4>UDP_NUM_SAMPLES</h4> <pre>public static final&nbsp;int UDP_NUM_SAMPLES</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.UDP_NUM_SAMPLES">Constant Field Values</a></dd> </dl> </li> </ul> <a name="UDP_IMG_DATA"> </a> <ul class="blockList"> <li class="blockList"> <h4>UDP_IMG_DATA</h4> <pre>public static final&nbsp;int UDP_IMG_DATA</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.UDP_IMG_DATA">Constant Field Values</a></dd> </dl> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;int <API key></pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.<API key>">Constant Field Values</a></dd> </dl> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;int <API key></pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.<API key>">Constant Field Values</a></dd> </dl> </li> </ul> <a name="RADIAL_IMG_INIT"> </a> <ul class="blockList"> <li class="blockList"> <h4>RADIAL_IMG_INIT</h4> <pre>public static final&nbsp;double RADIAL_IMG_INIT</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.RADIAL_IMG_INIT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="RADIAL_DATA_INIT"> </a> <ul class="blockList"> <li class="blockList"> <h4>RADIAL_DATA_INIT</h4> <pre>public static final&nbsp;double RADIAL_DATA_INIT</pre> </li> </ul> <a name="ANGLE_INIT"> </a> <ul class="blockList"> <li class="blockList"> <h4>ANGLE_INIT</h4> <pre>public static final&nbsp;int ANGLE_INIT</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.ANGLE_INIT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="STEP_ANGLE_INIT"> </a> <ul class="blockList"> <li class="blockList"> <h4>STEP_ANGLE_INIT</h4> <pre>public static final&nbsp;float STEP_ANGLE_INIT</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.STEP_ANGLE_INIT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="STEP_RADIAL_INIT"> </a> <ul class="blockList"> <li class="blockList"> <h4>STEP_RADIAL_INIT</h4> <pre>public static final&nbsp;double STEP_RADIAL_INIT</pre> </li> </ul> <a name="SCALE_FACTOR"> </a> <ul class="blockList"> <li class="blockList"> <h4>SCALE_FACTOR</h4> <pre>public static final&nbsp;int SCALE_FACTOR</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.SCALE_FACTOR">Constant Field Values</a></dd> </dl> </li> </ul> <a name="tmp_SAMPLING_POINTS"> </a> <ul class="blockList"> <li class="blockList"> <h4>tmp_SAMPLING_POINTS</h4> <pre>public static final&nbsp;int tmp_SAMPLING_POINTS</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.tmp_SAMPLING_POINTS">Constant Field Values</a></dd> </dl> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;int <API key></pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.<API key>">Constant Field Values</a></dd> </dl> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;int <API key></pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.echopen.asso.echopen.utils.Constants.PreProcParam.<API key>">Constant Field Values</a></dd> </dl> </li> </ul> <a name="<API key>"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;double <API key></pre> </li> </ul> <a name="<API key>"> </a> <ul class="blockListLast"> <li class="blockList"> <h4><API key></h4> <pre>public static final&nbsp;double <API key></pre> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> </a> <h3>Constructor Detail</h3> <a name="PreProcParam </a> <ul class="blockListLast"> <li class="blockList"> <h4>PreProcParam</h4> <pre>public&nbsp;PreProcParam()</pre> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method.detail"> </a> <h3>Method Detail</h3> <a name="<API key> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static&nbsp;int[]&nbsp;<API key>()</pre> </li> </ul> <a name="<API key> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static&nbsp;float[]&nbsp;<API key>()</pre> </li> </ul> <a name="<API key> </a> <ul class="blockListLast"> <li class="blockList"> <h4><API key></h4> <pre>public static&nbsp;double[]&nbsp;<API key>()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <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-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/echopen/asso/echopen/utils/Constants.ParseConstants.html" title="class in com.echopen.asso.echopen.utils"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/echopen/asso/echopen/utils/Constants.RulerParam.html" title="class in com.echopen.asso.echopen.utils"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/echopen/asso/echopen/utils/Constants.PreProcParam.html" target="_top">Frames</a></li> <li><a href="Constants.PreProcParam.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
#ifndef <API key> #define <API key> #pragma once #include <string> namespace chromeos { // Interface that handles notifications received from any of login wizard // screens. class ScreenObserver { public: // Each login screen or a view shown within login wizard view is itself a // state. Upon exit each view returns one of the results by calling // OnExit() method. Depending on the result and the current view or state // login wizard decides what is the next view to show. There must be an // exit code for each way to exit the screen for each screen. enum ExitCodes { NETWORK_CONNECTED, NETWORK_OFFLINE, CONNECTION_FAILED, UPDATE_INSTALLED, UPDATE_NOUPDATE, <API key>, <API key>, USER_IMAGE_SELECTED, USER_IMAGE_SKIPPED, EULA_ACCEPTED, EULA_BACK, <API key>, <API key>, <API key>, <API key>, EXIT_CODES_COUNT // not a real code, must be the last }; // Method called by a screen when user's done with it. virtual void OnExit(ExitCodes exit_code) = 0; // Forces current screen showing. virtual void ShowCurrentScreen() = 0; // Notify about new user names and password. It is used to autologin // just created user without asking the same info once again. virtual void <API key>(const std::string& username, const std::string& password) = 0; // Set/get usage statistics reporting checkbox status on EULA screen. virtual void <API key>(bool val) = 0; virtual bool <API key>() const = 0; protected: virtual ~ScreenObserver() {} }; } // namespace chromeos #endif // <API key>
#include <stdint.h> #include "base/macros.h" #include "media/base/video_frame.h" #include "media/cdm/api/<API key>.h" #include "media/cdm/cdm_helpers.h" #include "media/cdm/<API key>.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace media { class TestCdmBuffer : public cdm::Buffer { public: static TestCdmBuffer* Create(uint32_t capacity) { return new TestCdmBuffer(capacity); } // cdm::Buffer implementation. void Destroy() { DestroyCalled(); delete this; } uint32_t Capacity() const { return buffer_.size(); } uint8_t* Data() { return buffer_.data(); } void SetSize(uint32_t size) { size_ = size > Capacity() ? 0 : size; } uint32_t Size() const { return size_; } private: TestCdmBuffer(uint32_t capacity) : buffer_(capacity), size_(0) { // Verify that Destroy() is called on this object. EXPECT_CALL(*this, DestroyCalled()); } ~TestCdmBuffer() final {} MOCK_METHOD0(DestroyCalled, void()); std::vector<uint8_t> buffer_; uint32_t size_; <API key>(TestCdmBuffer); }; class <API key> : public testing::Test { public: <API key>() {} ~<API key>() override {} protected: SimpleCdmAllocator allocator_; private: <API key>(<API key>); }; TEST_F(<API key>, CreateCdmBuffer) { cdm::Buffer* buffer = allocator_.CreateCdmBuffer(100); EXPECT_GE(buffer->Capacity(), 100u); buffer->Destroy(); } TEST_F(<API key>, CreateCdmVideoFrame) { scoped_ptr<VideoFrameImpl> video_frame = allocator_.CreateCdmVideoFrame(); EXPECT_EQ(video_frame->FrameBuffer(), nullptr); video_frame->SetFrameBuffer(TestCdmBuffer::Create(100)); EXPECT_NE(video_frame->FrameBuffer(), nullptr); // Releasing |video_frame| should free the cdm::Buffer created above // (verified by the mock method TestCdmBuffer::DestroyCalled). video_frame.reset(); } TEST_F(<API key>, <API key>) { // For this test we need to pretend we have valid video data. So create // a small video frame of size 2x2. gfx::Size size(2, 2); size_t memory_needed = VideoFrame::AllocationSize(PIXEL_FORMAT_YV12, size); // Now create a VideoFrameImpl. scoped_ptr<VideoFrameImpl> video_frame = allocator_.CreateCdmVideoFrame(); EXPECT_EQ(video_frame->FrameBuffer(), nullptr); // Fill VideoFrameImpl as if it was a small video frame. video_frame->SetFormat(cdm::kI420); video_frame->SetSize(cdm::Size(size.width(), size.height())); video_frame->SetFrameBuffer(TestCdmBuffer::Create(memory_needed)); video_frame->FrameBuffer()->SetSize(memory_needed); // Now transform VideoFrameImpl to a VideoFrame, and make sure that // FrameBuffer() is transferred to the new object. EXPECT_NE(video_frame->FrameBuffer(), nullptr); scoped_refptr<media::VideoFrame> transformed_frame = video_frame-><API key>(size); EXPECT_EQ(video_frame->FrameBuffer(), nullptr); // Releasing |transformed_frame| should free the cdm::Buffer created above // (verified by the mock method TestCdmBuffer::DestroyCalled). transformed_frame = nullptr; } } // namespace media
// This creates and maintains the communication channel between // the inspectedPage and the dev tools panel. // In this example, messages are JSON objects // action: ['code'|'script'|'message'], // What action to perform on the inspected page // content: [String|Path to script|Object], // data to be passed through // tabId: [Automatically added] (function createChannel() { //Create a port with background page for continous message communication var port = chrome.extension.connect({ name: "Sample Communication" //Given a Name }); // Listen to messages from the background page port.onMessage.addListener(function (message) { document.querySelector('#insertmessagebutton').innerHTML = message.content; // port.postMessage(message); }); }()); // This sends an object to the background page // where it can be relayed to the inspected page function <API key>(message) { message.tabId = chrome.devtools.inspectedWindow.tabId; chrome.extension.sendMessage(message); }
/* * This is a basic func test for a Common application. */ YUI({ useConsoleOutput: true, useBrowserConsole: true, logInclude: { TestRunner: true } }).use('node', 'node-event-simulate', 'test', 'console', function (Y) { var suite = new Y.Test.Suite("Common: <API key>"); suite.add(new Y.Test.Case({ "test <API key>": function() { Y.Assert.areEqual('ac.config.getDefinition\(\'something_unknown\', \'definition not found\'\) -', Y.one('#noMatchDefinition').get('innerHTML').match(/ac.config.getDefinition\(\'something_unknown\', \'definition not found\'\) -/gi)); Y.Assert.areEqual('\"definition not found\"', Y.one('#noMatchDefinition').get('innerHTML').match(/\"definition not found\"/gi)); Y.Assert.areEqual('ac.config.getDefinition\(\'something_unknown\'\, \'\[\"I\"\, \"am\"\, \"an\"\, \"array\"\]\'\) -', Y.one('#<API key>').get('innerHTML').match(/ac.config.getDefinition\(\'something_unknown\'\, \'\[\"I\"\, \"am\"\, \"an\"\, \"array\"\]\'\) -/gi)); Y.Assert.areEqual('ac.config.getDefinition\(\'something_unknown\', \'\{one\: \{two\: \"I am two\"\, three\: \"I am three\"\}\}\'\) -', Y.one('#<API key>').get('innerHTML').match(/ac.config.getDefinition\(\'something_unknown\', \'\{one\: \{two\: \"I am two\"\, three\: \"I am three\"\}\}\'\) -/gi)); } })); Y.Test.Runner.add(suite); });
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Globalization; using VW.Labels; using VW.Serializer.Intermediate; namespace VW.Serializer { <summary> The default marshaller for most types supported by VW. </summary> public sealed partial class <API key> { <summary> Singleton default marshaller as it is stateless. </summary> public static readonly <API key> Instance = new <API key>(); <summary> Marshals a boolean value into native VW. e.g. loggedIn = true yields "loggedIn" in VW native string format. e.g. loggedIn = false yields an empty string. </summary> <param name="context">The marshalling context.</param> <param name="ns">The namespace description.</param> <param name="feature">The feature description.</param> <param name="value">The actual feature value.</param> public void MarshalFeature(<API key> context, Namespace ns, PreHashedFeature feature, bool value) { Contract.Requires(context != null); Contract.Requires(ns != null); Contract.Requires(feature != null); if (!value) { return; } context.NamespaceBuilder.AddFeature(feature.FeatureHash, 1f); context.AppendStringExample(feature.Dictify, " {0}", feature.Name); } <summary> Marshals an enum value into native VW. </summary> <typeparam name="T">The enum type.</typeparam> <param name="context">The marshalling context.</param> <param name="ns">The namespace description.</param> <param name="feature">The feature description.</param> <param name="value">The actual feature value.</param> <example>Gender = Male yields "GenderMale" in VW native string format.</example> public void MarshalEnumFeature<T>(<API key> context, Namespace ns, EnumerizedFeature<T> feature, T value) { Contract.Requires(context != null); Contract.Requires(ns != null); Contract.Requires(feature != null); context.NamespaceBuilder.AddFeature(feature.FeatureHash(value), 1f); context.AppendStringExample(feature.Dictify, " {0}{1}", feature.Name, value); } <summary> Marshals any type into native VW, by constructing a 1-hot encoding using <see cref="object.ToString()"/>. </summary> <typeparam name="T">The type to be enumerized.</typeparam> <param name="context">The marshalling context.</param> <param name="ns">The namespace description.</param> <param name="feature">The feature description.</param> <param name="value">The actual feature value.</param> <example><typeparamref name="T"/> is <see cref="System.Int32"/>, actual value '25' and <see cref="Feature.Name"/> is 'Age'. The result is equivalent to 'Age25'. </example> public void <API key><T>(<API key> context, Namespace ns, Feature feature, T value) { Contract.Requires(context != null); Contract.Requires(ns != null); Contract.Requires(feature != null); var stringValue = feature.Name + value.ToString(); context.NamespaceBuilder.AddFeature(context.VW.HashFeature(stringValue, ns.NamespaceHash), 1f); context.AppendStringExample(feature.Dictify, " {0}", stringValue); } <summary> Marshals the supplied string into VW native space. Spaces are escaped using '_'. Only <paramref name="value"/> is serialized, <paramref name="feature"/> Name is ignored. </summary> <param name="context">The marshalling context.</param> <param name="ns">The namespace description.</param> <param name="feature">The feature description.</param> <param name="value">The actual feature value.</param> <example><paramref name="value"/> is "New York". Result is "New_York".</example> public void <API key>(<API key> context, Namespace ns, Feature feature, string value) { Contract.Requires(context != null); Contract.Requires(ns != null); Contract.Requires(feature != null); if (string.IsNullOrWhiteSpace(value)) return; // safe escape spaces value = value.Replace(' ', '_'); var featureHash = context.VW.HashFeature(value, ns.NamespaceHash); context.NamespaceBuilder.AddFeature(featureHash, 1f); context.AppendStringExample(feature.Dictify, " {0}", value); } <summary> Marshals the supplied string into VW native space. Spaces are escaped using '_'. Includes the <see cref="Feature.Name"/> in the 1-hot encoded feature. </summary> <param name="context">The marshalling context.</param> <param name="ns">The namespace description.</param> <param name="feature">The feature description.</param> <param name="value">The actual feature value.</param> <example><paramref name="value"/> is "New York". <paramref name="feature"/> Name is "Location". Result is "LocationNew_York".</example> public void <API key>(<API key> context, Namespace ns, Feature feature, string value) { Contract.Requires(context != null); Contract.Requires(ns != null); Contract.Requires(feature != null); if (string.IsNullOrWhiteSpace(value)) return; // safe escape spaces value = feature.Name + value.Replace(' ', '_'); var featureHash = context.VW.HashFeature(value, ns.NamespaceHash); context.NamespaceBuilder.AddFeature(featureHash, 1f); context.AppendStringExample(feature.Dictify, " {0}", value); } <summary> Marshals the supplied string into VW native space, by splitting the word by white space. </summary> <param name="context">The marshalling context.</param> <param name="ns">The namespace description.</param> <param name="feature">The feature description.</param> <param name="value">The actual feature value.</param> <example><paramref name="value"/> is "New York". Result is "New York", corresponding to 2 featuers in VW native space.</example> public void <API key>(<API key> context, Namespace ns, Feature feature, string value) { if (string.IsNullOrWhiteSpace(value)) return; var words = value.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); foreach (var s in words) { var featureHash = context.VW.HashFeature(s, ns.NamespaceHash); context.NamespaceBuilder.AddFeature(featureHash, 1f); } if (context.StringExample == null) { return; } foreach (var s in words) { context.AppendStringExample(feature.Dictify, " {0}", s); } } <summary> Transfers feature data to native space. </summary> <typeparam name="TKey"></typeparam> <typeparam name="TValue"></typeparam> <param name="context">The marshalling context.</param> <param name="ns">The namespace description.</param> <param name="feature">The feature description.</param> <param name="value">The actual feature value.</param> public void MarshalFeature<TKey, TValue>(<API key> context, Namespace ns, Feature feature, IEnumerable<KeyValuePair<TKey, TValue>> value) { Contract.Requires(context != null); Contract.Requires(ns != null); Contract.Requires(feature != null); if (value == null) { return; } foreach (var kvp in value) { context.NamespaceBuilder.AddFeature( context.VW.HashFeature(Convert.ToString(kvp.Key), ns.NamespaceHash), Convert.ToSingle(kvp.Value, CultureInfo.InvariantCulture)); } if (context.StringExample == null) { return; } foreach (var kvp in value) { context.AppendStringExample( feature.Dictify, " {0}:" + (context.VW.Settings.<API key> ? "{1}" : "{1:E20}"), Convert.ToString(kvp.Key), Convert.ToSingle(kvp.Value, CultureInfo.InvariantCulture)); } } <summary> </summary> <param name="context">The marshalling context.</param> <param name="ns">The namespace description.</param> <param name="feature">The feature description.</param> <param name="value">The actual feature value.</param> public void MarshalFeature(<API key> context, Namespace ns, Feature feature, IDictionary value) { Contract.Requires(context != null); Contract.Requires(ns != null); Contract.Requires(feature != null); if (value == null) { return; } foreach (DictionaryEntry item in value) { context.NamespaceBuilder.AddFeature( context.VW.HashFeature(Convert.ToString(item.Key), ns.NamespaceHash), Convert.ToSingle(item.Value, CultureInfo.InvariantCulture)); } if (context.StringExample == null) { return; } foreach (DictionaryEntry item in value) { context.AppendStringExample( feature.Dictify, " {0}:" + (context.VW.Settings.<API key> ? "{1}" : "{1:E20}"), Convert.ToString(item.Key), Convert.ToSingle(item.Value, CultureInfo.InvariantCulture)); } } <summary> </summary> <param name="context">The marshalling context.</param> <param name="ns">The namespace description.</param> <param name="feature">The feature description.</param> <param name="value">The actual feature value.</param> public void MarshalFeature(<API key> context, Namespace ns, Feature feature, IEnumerable<string> value) { Contract.Requires(context != null); Contract.Requires(ns != null); Contract.Requires(feature != null); if (value == null) { return; } foreach (var item in value) { context.NamespaceBuilder.AddFeature(context.VW.HashFeature(item.Replace(' ', '_'), ns.NamespaceHash), 1f); } if (context.StringExample == null) { return; } foreach (var item in value) { context.AppendStringExample(feature.Dictify, " {0}", item); } } <summary> </summary> <param name="context">The marshalling context.</param> <param name="ns">The namespace description.</param> <param name="featureVisits"></param> public int MarshalNamespace(<API key> context, Namespace ns, Action featureVisits) { try { // the namespace is only added on dispose, to be able to check if at least a single feature has been added context.NamespaceBuilder = context.ExampleBuilder.AddNamespace(ns.FeatureGroup); var position = 0; var stringExample = context.StringExample; if (context.StringExample != null) { position = stringExample.Append(ns.NamespaceString).Length; } featureVisits(); if (context.StringExample != null) { if (position == stringExample.Length) { // no features added, remove namespace stringExample.Length = position - ns.NamespaceString.Length; } } return (int)context.NamespaceBuilder.FeatureCount; } finally { if (context.NamespaceBuilder != null) { context.NamespaceBuilder.Dispose(); context.NamespaceBuilder = null; } } } <summary> </summary> <param name="context">The marshalling context.</param> <param name="label"></param> public void MarshalLabel(<API key> context, ILabel label) { if (label == null) return; context.ExampleBuilder.ApplyLabel(label); // prefix with label if (context.StringExample != null) context.StringLabel = label.ToString(); } <summary> </summary> <param name="context">The marshalling context.</param> <param name="label"></param> public void MarshalLabel(<API key> context, string label) { if (label == null) return; context.ExampleBuilder.ApplyLabel(new StringLabel(label)); context.StringLabel = label; } } }
#include "src/heap/list.h" #include "testing/gtest-support.h" namespace v8 { namespace internal { namespace heap { class TestChunk { public: heap::ListNode<TestChunk>& list_node() { return list_node_; } const heap::ListNode<TestChunk>& list_node() const { return list_node_; } heap::ListNode<TestChunk> list_node_; }; TEST(List, <API key>) { List<TestChunk> list; EXPECT_TRUE(list.Empty()); TestChunk t1; list.PushBack(&t1); EXPECT_FALSE(list.Empty()); EXPECT_TRUE(list.Contains(&t1)); list.Remove(&t1); EXPECT_TRUE(list.Empty()); } TEST(List, <API key>) { List<TestChunk> list; EXPECT_TRUE(list.Empty()); TestChunk t1; list.PushFront(&t1); EXPECT_FALSE(list.Empty()); list.Remove(&t1); EXPECT_TRUE(list.Empty()); } TEST(List, <API key>) { List<TestChunk> list; EXPECT_TRUE(list.Empty()); const int kSize = 10; TestChunk chunks[kSize]; for (int i = 0; i < kSize; i++) { list.PushBack(&chunks[i]); EXPECT_EQ(list.back(), &chunks[i]); } for (int i = kSize - 1; i > 0; i list.Remove(&chunks[i]); EXPECT_EQ(list.back(), &chunks[i - 1]); } list.Remove(&chunks[0]); EXPECT_TRUE(list.Empty()); } TEST(List, <API key>) { List<TestChunk> list; EXPECT_TRUE(list.Empty()); const int kSize = 10; TestChunk chunks[kSize]; for (int i = 0; i < kSize; i++) { list.PushFront(&chunks[i]); EXPECT_EQ(list.front(), &chunks[i]); } for (int i = kSize - 1; i > 0; i list.Remove(&chunks[i]); EXPECT_EQ(list.front(), &chunks[i - 1]); } list.Remove(&chunks[0]); EXPECT_TRUE(list.Empty()); } TEST(List, <API key>) { List<TestChunk> list; EXPECT_TRUE(list.Empty()); const int kSize = 10; TestChunk chunks[kSize]; for (int i = 0; i < kSize; i++) { list.PushBack(&chunks[i]); EXPECT_EQ(list.back(), &chunks[i]); } int i, j; for (i = kSize / 2 - 1, j = kSize / 2; i >= 0; i list.Remove(&chunks[i]); list.Remove(&chunks[j]); } EXPECT_TRUE(list.Empty()); } } // namespace heap } // namespace internal } // namespace v8