answer
stringlengths
15
1.25M
#include "chrome/browser/chromeos/bluetooth/bluetooth_adapter.h" #include "base/bind.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/values.h" #include "chrome/browser/chromeos/bluetooth/bluetooth_device.h" #include "chromeos/dbus/<API key>.h" #include "chromeos/dbus/<API key>.h" #include "chromeos/dbus/<API key>.h" #include "chromeos/dbus/<API key>.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "dbus/object_path.h" namespace { // Shared default adapter instance, we don't want to keep this class around // if nobody is using it so use a WeakPtr and create the object when needed; // since Google C++ Style (and clang's static analyzer) forbids us having // exit-time destructors we use a leaky lazy instance for it. base::LazyInstance<base::WeakPtr<chromeos::BluetoothAdapter> >::Leaky default_adapter = <API key>; } // namespace namespace chromeos { BluetoothAdapter::BluetoothAdapter() : weak_ptr_factory_(this), track_default_(false), powered_(false), discovering_(false) { DBusThreadManager::Get()-><API key>()-> AddObserver(this); DBusThreadManager::Get()-><API key>()-> AddObserver(this); DBusThreadManager::Get()-><API key>()-> AddObserver(this); } BluetoothAdapter::~BluetoothAdapter() { DBusThreadManager::Get()-><API key>()-> RemoveObserver(this); DBusThreadManager::Get()-><API key>()-> RemoveObserver(this); DBusThreadManager::Get()-><API key>()-> RemoveObserver(this); STLDeleteValues(&devices_); } void BluetoothAdapter::AddObserver(Observer* observer) { DCHECK(observer); observers_.AddObserver(observer); } void BluetoothAdapter::RemoveObserver(Observer* observer) { DCHECK(observer); observers_.RemoveObserver(observer); } bool BluetoothAdapter::IsPresent() const { return !object_path_.value().empty(); } bool BluetoothAdapter::IsPowered() const { return powered_; } void BluetoothAdapter::SetPowered(bool powered, const base::Closure& callback, const ErrorCallback& error_callback) { DBusThreadManager::Get()-><API key>()-> GetProperties(object_path_)->powered.Set( powered, base::Bind(&BluetoothAdapter::OnSetPowered, weak_ptr_factory_.GetWeakPtr(), callback, error_callback)); } bool BluetoothAdapter::IsDiscovering() const { return discovering_; } void BluetoothAdapter::SetDiscovering(bool discovering, const base::Closure& callback, const ErrorCallback& error_callback) { if (discovering) { DBusThreadManager::Get()-><API key>()-> StartDiscovery(object_path_, base::Bind(&BluetoothAdapter::OnStartDiscovery, weak_ptr_factory_.GetWeakPtr(), callback, error_callback)); } else { DBusThreadManager::Get()-><API key>()-> StopDiscovery(object_path_, base::Bind(&BluetoothAdapter::OnStopDiscovery, weak_ptr_factory_.GetWeakPtr(), callback, error_callback)); } } BluetoothAdapter::DeviceList BluetoothAdapter::GetDevices() { ConstDeviceList const_devices = const_cast<const BluetoothAdapter *>(this)->GetDevices(); DeviceList devices; for (ConstDeviceList::const_iterator i = const_devices.begin(); i != const_devices.end(); ++i) devices.push_back(const_cast<BluetoothDevice *>(*i)); return devices; } BluetoothAdapter::ConstDeviceList BluetoothAdapter::GetDevices() const { ConstDeviceList devices; for (DevicesMap::const_iterator iter = devices_.begin(); iter != devices_.end(); ++iter) devices.push_back(iter->second); return devices; } BluetoothDevice* BluetoothAdapter::GetDevice(const std::string& address) { return const_cast<BluetoothDevice *>( const_cast<const BluetoothAdapter *>(this)->GetDevice(address)); } const BluetoothDevice* BluetoothAdapter::GetDevice( const std::string& address) const { DevicesMap::const_iterator iter = devices_.find(address); if (iter != devices_.end()) return iter->second; return NULL; } void BluetoothAdapter::<API key>( const <API key>& callback, const ErrorCallback& error_callback) { DBusThreadManager::Get()-><API key>()-> ReadLocalData(object_path_, base::Bind(&BluetoothAdapter::OnReadLocalData, weak_ptr_factory_.GetWeakPtr(), callback, error_callback)); } void BluetoothAdapter::TrackDefaultAdapter() { DVLOG(1) << "Tracking default adapter"; track_default_ = true; DBusThreadManager::Get()-><API key>()-> DefaultAdapter(base::Bind(&BluetoothAdapter::AdapterCallback, weak_ptr_factory_.GetWeakPtr())); } void BluetoothAdapter::FindAdapter(const std::string& address) { DVLOG(1) << "Using adapter " << address; track_default_ = false; DBusThreadManager::Get()-><API key>()-> FindAdapter(address, base::Bind(&BluetoothAdapter::AdapterCallback, weak_ptr_factory_.GetWeakPtr())); } void BluetoothAdapter::AdapterCallback(const dbus::ObjectPath& adapter_path, bool success) { if (success) { ChangeAdapter(adapter_path); } else if (!object_path_.value().empty()) { RemoveAdapter(); } } void BluetoothAdapter::<API key>( const dbus::ObjectPath& adapter_path) { if (track_default_) ChangeAdapter(adapter_path); } void BluetoothAdapter::AdapterRemoved(const dbus::ObjectPath& adapter_path) { if (adapter_path == object_path_) RemoveAdapter(); } void BluetoothAdapter::ChangeAdapter(const dbus::ObjectPath& adapter_path) { if (adapter_path == object_path_) return; // Determine whether this is a change of adapter or gaining an adapter, // remember for later so we can send the right notification. const bool new_adapter = object_path_.value().empty(); if (new_adapter) { DVLOG(1) << "Adapter path initialized to " << adapter_path.value(); } else { DVLOG(1) << "Adapter path changed from " << object_path_.value() << " to " << adapter_path.value(); // Invalidate the devices list, since the property update does not // remove them. ClearDevices(); } object_path_ = adapter_path; // Update properties to their new values. <API key>::Properties* properties = DBusThreadManager::Get()-><API key>()-> GetProperties(object_path_); address_ = properties->address.value(); PoweredChanged(properties->powered.value()); DiscoveringChanged(properties->discovering.value()); DevicesChanged(properties->devices.value()); // Notify observers if we did not have an adapter before, the case of // moving from one to another is hidden from layers above. if (new_adapter) FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, <API key>(this, true)); } void BluetoothAdapter::RemoveAdapter() { DVLOG(1) << "Adapter lost."; PoweredChanged(false); DiscoveringChanged(false); ClearDevices(); object_path_ = dbus::ObjectPath(""); address_.clear(); FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, <API key>(this, false)); } void BluetoothAdapter::OnSetPowered(const base::Closure& callback, const ErrorCallback& error_callback, bool success) { if (success) callback.Run(); else error_callback.Run(); } void BluetoothAdapter::PoweredChanged(bool powered) { if (powered == powered_) return; powered_ = powered; FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, <API key>(this, powered_)); } void BluetoothAdapter::OnStartDiscovery(const base::Closure& callback, const ErrorCallback& error_callback, const dbus::ObjectPath& adapter_path, bool success) { if (success) { DVLOG(1) << object_path_.value() << ": started discovery."; // Clear devices found in previous discovery attempts <API key>(); callback.Run(); } else { // TODO(keybuk): in future, don't run the callback if the error was just // that we were already discovering. error_callback.Run(); } } void BluetoothAdapter::OnStopDiscovery(const base::Closure& callback, const ErrorCallback& error_callback, const dbus::ObjectPath& adapter_path, bool success) { if (success) { DVLOG(1) << object_path_.value() << ": stopped discovery."; callback.Run(); // Leave found devices available for perusing. } else { // TODO(keybuk): in future, don't run the callback if the error was just // that we weren't discovering. error_callback.Run(); } } void BluetoothAdapter::DiscoveringChanged(bool discovering) { if (discovering == discovering_) return; discovering_ = discovering; FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, <API key>(this, discovering_)); } void BluetoothAdapter::OnReadLocalData( const <API key>& callback, const ErrorCallback& error_callback, const <API key>& data, bool success) { if (success) callback.Run(data); else error_callback.Run(); } void BluetoothAdapter::<API key>( const dbus::ObjectPath& adapter_path, const std::string& property_name) { if (adapter_path != object_path_) return; <API key>::Properties* properties = DBusThreadManager::Get()-><API key>()-> GetProperties(object_path_); if (property_name == properties->powered.name()) { PoweredChanged(properties->powered.value()); } else if (property_name == properties->discovering.name()) { DiscoveringChanged(properties->discovering.value()); } else if (property_name == properties->devices.name()) { DevicesChanged(properties->devices.value()); } } void BluetoothAdapter::<API key>( const dbus::ObjectPath& device_path, const std::string& property_name) { UpdateDevice(device_path); } void BluetoothAdapter::UpdateDevice(const dbus::ObjectPath& device_path) { <API key>::Properties* properties = DBusThreadManager::Get()-><API key>()-> GetProperties(device_path); // When we first see a device, we may not know the address yet and need to // wait for the <API key> signal before adding the device. const std::string address = properties->address.value(); if (address.empty()) return; // The device may be already known to us, either because this is an update // to properties, or the device going from discovered to connected and // pairing gaining an object path in the process. In any case, we want // to update the existing object, not create a new one. DevicesMap::iterator iter = devices_.find(address); BluetoothDevice* device; const bool update_device = (iter != devices_.end()); if (update_device) { device = iter->second; } else { device = BluetoothDevice::Create(this); devices_[address] = device; } const bool was_paired = device->IsPaired(); if (!was_paired) { DVLOG(1) << "Assigned object path " << device_path.value() << " to device " << address; device->SetObjectPath(device_path); } device->Update(properties, true); // Don't send a duplicate added event for supported devices that were // previously visible or for already paired devices, send a changed // event instead. We always send one event or the other since we always // inform observers about paired devices whether or not they're supported. if (update_device && (device->IsSupported() || was_paired)) { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceChanged(this, device)); } else { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceAdded(this, device)); } } void BluetoothAdapter::ClearDevices() { DevicesMap replace; devices_.swap(replace); for (DevicesMap::iterator iter = replace.begin(); iter != replace.end(); ++iter) { BluetoothDevice* device = iter->second; if (device->IsSupported() || device->IsPaired()) FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceRemoved(this, device)); delete device; } } void BluetoothAdapter::DeviceCreated(const dbus::ObjectPath& adapter_path, const dbus::ObjectPath& device_path) { if (adapter_path != object_path_) return; UpdateDevice(device_path); } void BluetoothAdapter::DeviceRemoved(const dbus::ObjectPath& adapter_path, const dbus::ObjectPath& device_path) { if (adapter_path != object_path_) return; DevicesMap::iterator iter = devices_.begin(); while (iter != devices_.end()) { BluetoothDevice* device = iter->second; DevicesMap::iterator temp = iter; ++iter; if (device->object_path_ != device_path) continue; // DeviceRemoved can also be called to indicate a device that is visible // during discovery has disconnected, but it is still visible to the // adapter, so don't remove in that case and only clear the object path. if (!device->IsVisible()) { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceRemoved(this, device)); DVLOG(1) << "Removed device " << device->address(); delete device; devices_.erase(temp); } else { DVLOG(1) << "Removed object path from device " << device->address(); device->RemoveObjectPath(); // If the device is not supported then we want to act as if it was // removed, even though it is still visible to the adapter. if (!device->IsSupported()) { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceRemoved(this, device)); } else { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceChanged(this, device)); } } } } void BluetoothAdapter::DevicesChanged( const std::vector<dbus::ObjectPath>& devices) { for (std::vector<dbus::ObjectPath>::const_iterator iter = devices.begin(); iter != devices.end(); ++iter) UpdateDevice(*iter); } void BluetoothAdapter::<API key>() { DevicesMap::iterator iter = devices_.begin(); while (iter != devices_.end()) { BluetoothDevice* device = iter->second; DevicesMap::iterator temp = iter; ++iter; if (!device->IsPaired()) { if (device->IsSupported()) FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceRemoved(this, device)); delete device; devices_.erase(temp); } } } void BluetoothAdapter::DeviceFound( const dbus::ObjectPath& adapter_path, const std::string& address, const <API key>::Properties& properties) { if (adapter_path != object_path_) return; // DeviceFound can also be called to indicate that a device we've // paired with is now visible to the adapter during discovery, in which // case we want to update the existing object, not create a new one. BluetoothDevice* device; DevicesMap::iterator iter = devices_.find(address); const bool update_device = (iter != devices_.end()); if (update_device) { device = iter->second; } else { device = BluetoothDevice::Create(this); devices_[address] = device; } DVLOG(1) << "Device " << address << " is visible to the adapter"; device->SetVisible(true); device->Update(&properties, false); // Don't send a duplicated added event for duplicate signals for supported // devices that were previously visible (should never happen) or for already // paired devices, send a changed event instead. We do not inform observers // if we find or update an unconnected and unsupported device. if (update_device && (device->IsSupported() || device->IsPaired())) { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceChanged(this, device)); } else if (device->IsSupported()) { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceAdded(this, device)); } } void BluetoothAdapter::DeviceDisappeared(const dbus::ObjectPath& adapter_path, const std::string& address) { if (adapter_path != object_path_) return; DevicesMap::iterator iter = devices_.find(address); if (iter == devices_.end()) return; BluetoothDevice* device = iter->second; // DeviceDisappeared can also be called to indicate that a device we've // paired with is no longer visible to the adapter, so don't remove // in that case and only clear the visible flag. if (!device->IsPaired()) { if (device->IsSupported()) FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceRemoved(this, device)); DVLOG(1) << "Discovered device " << device->address() << " is no longer visible to the adapter"; delete device; devices_.erase(iter); } else { DVLOG(1) << "Paired device " << device->address() << " is no longer visible to the adapter"; device->SetVisible(false); FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceChanged(this, device)); } } // static scoped_refptr<BluetoothAdapter> BluetoothAdapter::DefaultAdapter() { if (!default_adapter.Get().get()) { BluetoothAdapter* new_adapter = new BluetoothAdapter; default_adapter.Get() = new_adapter->weak_ptr_factory_.GetWeakPtr(); default_adapter.Get()->TrackDefaultAdapter(); } return scoped_refptr<BluetoothAdapter>(default_adapter.Get()); } // static BluetoothAdapter* BluetoothAdapter::Create(const std::string& address) { BluetoothAdapter* adapter = new BluetoothAdapter; adapter->FindAdapter(address); return adapter; } } // namespace chromeos
/* this ALWAYS GENERATED file contains the IIDs and CLSIDs */ /* link this file in with the server and any clients */ /* at Mon Dec 01 09:02:10 2008 */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ #ifdef __cplusplus extern "C"{ #endif #include <rpc.h> #include <rpcndr.h> #ifdef _MIDL_USE_GUIDDEF_ #ifndef INITGUID #define INITGUID #include <guiddef.h> #undef INITGUID #else #include <guiddef.h> #endif #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) #else // !_MIDL_USE_GUIDDEF_ #ifndef __IID_DEFINED__ #define __IID_DEFINED__ typedef struct _IID { unsigned long x; unsigned short s1; unsigned short s2; unsigned char c[8]; } IID; #endif // __IID_DEFINED__ #ifndef CLSID_DEFINED #define CLSID_DEFINED typedef IID CLSID; #endif // CLSID_DEFINED #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #endif !_MIDL_USE_GUIDDEF_ MIDL_DEFINE_GUID(IID, IID_IAccessible2,0xE89F726E,0xC4F4,0x4c19,0xBB,0x19,0xB6,0x47,0xD7,0xFA,0x84,0x78); #undef MIDL_DEFINE_GUID #ifdef __cplusplus } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Inbox2.Platform.Channels.Entities { [Serializable] [DataContract] public enum ProfileType { [EnumMember(Value = "1")] Default = 0, [EnumMember(Value = "2")] Social = 10, } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Class Simpletools\Page\Layout</title> <link rel="stylesheet" href="resources/style.css?<SHA1-like>"> </head> <body> <div id="left"> <div id="menu"> <a href="index.html" title="Overview"><span>Overview</span></a> <div id="groups"> <h3>Namespaces</h3> <ul> <li class="active"> <a href="<API key>.html"> Simpletools<span></span> </a> <ul> <li> <a href="<API key>.Autoload.html"> Autoload </a> </li> <li> <a href="<API key>.Config.html"> Config </a> </li> <li> <a href="<API key>.Db.html"> Db<span></span> </a> <ul> <li> <a href="<API key>.Db.Mysql.html"> Mysql </a> </li> </ul></li> <li> <a href="<API key>.Event.html"> Event </a> </li> <li> <a href="<API key>.Http.html"> Http </a> </li> <li> <a href="<API key>.Mvc.html"> Mvc </a> </li> <li class="active"> <a href="<API key>.Page.html"> Page </a> </li> <li> <a href="<API key>.Store.html"> Store </a> </li> </ul></li> </ul> </div> <hr> <div id="elements"> <h3>Classes</h3> <ul> <li class="active"><a href="class-Simpletools.Page.Layout.html">Layout</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <form id="search"> <input type="hidden" name="cx" value=""> <input type="hidden" name="ie" value="UTF-8"> <input type="text" name="q" class="text" placeholder="Search"> </form> <div id="navigation"> <ul> <li> <a href="index.html" title="Overview"><span>Overview</span></a> </li> <li> <a href="<API key>.Page.html" title="Summary of Simpletools\Page"><span>Namespace</span></a> </li> <li class="active"> <span>Class</span> </li> </ul> <ul> </ul> <ul> </ul> </div> <div id="content" class="class"> <h1>Class Layout</h1> <div class="info"> <b>Namespace:</b> <a href="<API key>.html">Simpletools</a>\<a href="<API key>.Page.html">Page</a><br> <b>Located at</b> <a href="<API key>.Page.Layout.html#44-413" title="Go to source code">Simpletools/Page/Layout.php</a> <br> </div> <table class="summary methods" id="methods"> <caption>Methods summary</caption> <tr data-order="__construct" id="___construct"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href=" <code><a href="<API key>.Page.Layout.html#67-89" title="Go to source code">__construct</a>( <span>array <var>$settings</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="settings" id="_settings"> <td class="attributes"><code> public static &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_settings">#</a> <code><a href="<API key>.Page.Layout.html#91-104" title="Go to source code">settings</a>( <span>array <var>$settings</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="getInstance" id="_getInstance"> <td class="attributes"><code> public static &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_getInstance">#</a> <code><a href="<API key>.Page.Layout.html#112-125" title="Go to source code">getInstance</a>( <span> <var>$settings</var> = <span class="php-keyword1">null</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="setLayout" id="_setLayout"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_setLayout">#</a> <code><a href="<API key>.Page.Layout.html#127-135" title="Go to source code">setLayout</a>( <span> <var>$layDir</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="registerLayouts" id="_registerLayouts"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_registerLayouts">#</a> <code><a href="<API key>.Page.Layout.html#137-147" title="Go to source code">registerLayouts</a>( <span>array <var>$layouts</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="start" id="_start"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_start">#</a> <code><a href="<API key>.Page.Layout.html#149-152" title="Go to source code">start</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="startBuffer" id="_startBuffer"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_startBuffer">#</a> <code><a href="<API key>.Page.Layout.html#154-159" title="Go to source code">startBuffer</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="clearBuffer" id="_clearBuffer"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_clearBuffer">#</a> <code><a href="<API key>.Page.Layout.html#161-164" title="Go to source code">clearBuffer</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="render" id="_render"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_render">#</a> <code><a href="<API key>.Page.Layout.html#166-195" title="Go to source code">render</a>( <span> <var>$minify</var> = <span class="php-keyword1">false</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="layout" id="_layout"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_layout">#</a> <code><a href="<API key>.Page.Layout.html#197-200" title="Go to source code">layout</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayContent" id="_displayContent"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayContent">#</a> <code><a href="<API key>.Page.Layout.html#202-205" title="Go to source code">displayContent</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="disable" id="_disable"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_disable">#</a> <code><a href="<API key>.Page.Layout.html#207-213" title="Go to source code">disable</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="set" id="_set"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_set">#</a> <code><a href="<API key>.Page.Layout.html#215-223" title="Go to source code">set</a>( <span> <var>$layout</var> = <span class="php-quote">'default'</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="enable" id="_enable"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_enable">#</a> <code><a href="<API key>.Page.Layout.html#225-235" title="Go to source code">enable</a>( <span> <var>$layout</var> = <span class="php-quote">'default'</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="setTitle" id="_setTitle"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_setTitle">#</a> <code><a href="<API key>.Page.Layout.html#244-248" title="Go to source code">setTitle</a>( <span> <var>$title</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="<API key>" id="<API key>"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#<API key>">#</a> <code><a href="<API key>.Page.Layout.html#250-254" title="Go to source code"><API key></a>( <span> <var>$title</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayTitle" id="_displayTitle"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayTitle">#</a> <code><a href="<API key>.Page.Layout.html#256-259" title="Go to source code">displayTitle</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="setDescription" id="_setDescription"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_setDescription">#</a> <code><a href="<API key>.Page.Layout.html#261-265" title="Go to source code">setDescription</a>( <span> <var>$description</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayDescription" id="_displayDescription"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayDescription">#</a> <code><a href="<API key>.Page.Layout.html#267-270" title="Go to source code">displayDescription</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addInternalCss" id="_addInternalCss"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addInternalCss">#</a> <code><a href="<API key>.Page.Layout.html#272-276" title="Go to source code">addInternalCss</a>( <span> <var>$style</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayInternalCss" id="_displayInternalCss"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayInternalCss">#</a> <code><a href="<API key>.Page.Layout.html#278-288" title="Go to source code">displayInternalCss</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="clearInternalCss" id="_clearInternalCss"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_clearInternalCss">#</a> <code><a href="<API key>.Page.Layout.html#290-294" title="Go to source code">clearInternalCss</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addExternalCss" id="_addExternalCss"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addExternalCss">#</a> <code><a href="<API key>.Page.Layout.html#296-306" title="Go to source code">addExternalCss</a>( <span> <var>$href</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addExternalCss_" id="_addExternalCss_"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addExternalCss_">#</a> <code><a href="<API key>.Page.Layout.html#308-312" title="Go to source code">addExternalCss_</a>( <span> <var>$href</var></span>, <span> <var>$media</var> = <span class="php-quote">'screen'</span></span>, <span> <var>$rel</var> = <span class="php-quote">'stylesheet'</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="clearExternalCss" id="_clearExternalCss"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_clearExternalCss">#</a> <code><a href="<API key>.Page.Layout.html#314-318" title="Go to source code">clearExternalCss</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayExternalCss" id="_displayExternalCss"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayExternalCss">#</a> <code><a href="<API key>.Page.Layout.html#320-323" title="Go to source code">displayExternalCss</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addMetaTag" id="_addMetaTag"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addMetaTag">#</a> <code><a href="<API key>.Page.Layout.html#325-330" title="Go to source code">addMetaTag</a>( <span> <var>$name</var></span>, <span> <var>$content</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayMetaTags" id="_displayMetaTags"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayMetaTags">#</a> <code><a href="<API key>.Page.Layout.html#332-344" title="Go to source code">displayMetaTags</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addHeadLink" id="_addHeadLink"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addHeadLink">#</a> <code><a href="<API key>.Page.Layout.html#346-357" title="Go to source code">addHeadLink</a>( <span>array <var>$options</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayHeadLinks" id="_displayHeadLinks"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayHeadLinks">#</a> <code><a href="<API key>.Page.Layout.html#359-362" title="Go to source code">displayHeadLinks</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addExternalJs" id="_addExternalJs"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addExternalJs">#</a> <code><a href="<API key>.Page.Layout.html#364-374" title="Go to source code">addExternalJs</a>( <span> <var>$href</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="clearExternalJs" id="_clearExternalJs"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_clearExternalJs">#</a> <code><a href="<API key>.Page.Layout.html#376-380" title="Go to source code">clearExternalJs</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayExternalJs" id="_displayExternalJs"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayExternalJs">#</a> <code><a href="<API key>.Page.Layout.html#382-385" title="Go to source code">displayExternalJs</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addInternalJs" id="_addInternalJs"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addInternalJs">#</a> <code><a href="<API key>.Page.Layout.html#387-391" title="Go to source code">addInternalJs</a>( <span> <var>$source</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="clearInternalJs" id="_clearInternalJs"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_clearInternalJs">#</a> <code><a href="<API key>.Page.Layout.html#393-397" title="Go to source code">clearInternalJs</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayInternalJs" id="_displayInternalJs"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayInternalJs">#</a> <code><a href="<API key>.Page.Layout.html#399-411" title="Go to source code">displayInternalJs</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> </table> <table class="summary properties" id="properties"> <caption>Properties summary</caption> <tr data-order="content" id="$content"> <td class="attributes"><code> public string </code></td> <td class="name"> <a href="<API key>.Page.Layout.html#52" title="Go to source code"><var>$content</var></a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </td> <td class="value"> <div> <a href="#$content" class="anchor">#</a> <code><span class="php-quote">''</span></code> </div> </td> </tr> <tr data-order="description" id="$description"> <td class="attributes"><code> public </code></td> <td class="name"> <a href="<API key>.Page.Layout.html#57" title="Go to source code"><var>$description</var></a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </td> <td class="value"> <div> <a href="#$description" class="anchor">#</a> <code><span class="php-keyword1">null</span></code> </div> </td> </tr> <tr data-order="title" id="$title"> <td class="attributes"><code> public </code></td> <td class="name"> <a href="<API key>.Page.Layout.html#58" title="Go to source code"><var>$title</var></a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </td> <td class="value"> <div> <a href="#$title" class="anchor">#</a> <code><span class="php-keyword1">null</span></code> </div> </td> </tr> <tr data-order="_layouts" id="$_layouts"> <td class="attributes"><code> protected array </code></td> <td class="name"> <a href="<API key>.Page.Layout.html#62" title="Go to source code"><var>$_layouts</var></a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </td> <td class="value"> <div> <a href="#$_layouts" class="anchor">#</a> <code><span class="php-keyword1">array</span>()</code> </div> </td> </tr> <tr data-order="_currentLayout" id="$_currentLayout"> <td class="attributes"><code> protected string </code></td> <td class="name"> <a href="<API key>.Page.Layout.html#63" title="Go to source code"><var>$_currentLayout</var></a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </td> <td class="value"> <div> <a href="#$_currentLayout" class="anchor">#</a> <code><span class="php-quote">'default'</span></code> </div> </td> </tr> </table> </div> <div id="footer"> API documentation generated by <a href="http://apigen.org">ApiGen</a> </div> </div> </div> <script src="resources/combined.js"></script> <script src="elementlist.js"></script> </body> </html>
#ifndef <API key> #define <API key> #include <nt2/gallery/functions/parter.hpp> #endif
// Use of this source code is governed by a BSD-style package ppc64 import ( "cmd/compile/internal/gc" "cmd/internal/obj" "cmd/internal/obj/ppc64" ) const ( LeftRdwr uint32 = gc.LeftRead | gc.LeftWrite RightRdwr uint32 = gc.RightRead | gc.RightWrite ) // This table gives the basic information about instruction // generated by the compiler and processed in the optimizer. // See opt.h for bit definitions. // Instructions not generated need not be listed. // As an exception to that rule, we typically write down all the // size variants of an operation even if we just use a subset. // The table is formatted for 8-space tabs. var progtable = [ppc64.ALAST]obj.ProgInfo{ obj.ATYPE: {Flags: gc.Pseudo | gc.Skip}, obj.ATEXT: {Flags: gc.Pseudo}, obj.AFUNCDATA: {Flags: gc.Pseudo}, obj.APCDATA: {Flags: gc.Pseudo}, obj.AUNDEF: {Flags: gc.Break}, obj.AUSEFIELD: {Flags: gc.OK}, obj.ACHECKNIL: {Flags: gc.LeftRead}, obj.AVARDEF: {Flags: gc.Pseudo | gc.RightWrite}, obj.AVARKILL: {Flags: gc.Pseudo | gc.RightWrite}, obj.AVARLIVE: {Flags: gc.Pseudo | gc.LeftRead}, // NOP is an internal no-op that also stands // for USED and SET annotations, not the Power opcode. obj.ANOP: {Flags: gc.LeftRead | gc.RightWrite}, // Integer ppc64.AADD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ASUB: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ANEG: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AAND: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AOR: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AXOR: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AMULLD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AMULLW: {Flags: gc.SizeL | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AMULHD: {Flags: gc.SizeL | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AMULHDU: {Flags: gc.SizeL | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ADIVD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ADIVDU: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ASLD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ASRD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ASRAD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ACMP: {Flags: gc.SizeQ | gc.LeftRead | gc.RightRead}, ppc64.ACMPU: {Flags: gc.SizeQ | gc.LeftRead | gc.RightRead}, ppc64.ATD: {Flags: gc.SizeQ | gc.RightRead}, // Floating point. ppc64.AFADD: {Flags: gc.SizeD | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFADDS: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFSUB: {Flags: gc.SizeD | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFSUBS: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFMUL: {Flags: gc.SizeD | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFMULS: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFDIV: {Flags: gc.SizeD | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFDIVS: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFCTIDZ: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFCFID: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFCMPU: {Flags: gc.SizeD | gc.LeftRead | gc.RightRead}, ppc64.AFRSP: {Flags: gc.SizeD | gc.LeftRead | gc.RightWrite | gc.Conv}, // Moves ppc64.AMOVB: {Flags: gc.SizeB | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AMOVBU: {Flags: gc.SizeB | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv | gc.PostInc}, ppc64.AMOVBZ: {Flags: gc.SizeB | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AMOVH: {Flags: gc.SizeW | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AMOVHU: {Flags: gc.SizeW | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv | gc.PostInc}, ppc64.AMOVHZ: {Flags: gc.SizeW | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AMOVW: {Flags: gc.SizeL | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, // there is no AMOVWU. ppc64.AMOVWZU: {Flags: gc.SizeL | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv | gc.PostInc}, ppc64.AMOVWZ: {Flags: gc.SizeL | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AMOVD: {Flags: gc.SizeQ | gc.LeftRead | gc.RightWrite | gc.Move}, ppc64.AMOVDU: {Flags: gc.SizeQ | gc.LeftRead | gc.RightWrite | gc.Move | gc.PostInc}, ppc64.AFMOVS: {Flags: gc.SizeF | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AFMOVD: {Flags: gc.SizeD | gc.LeftRead | gc.RightWrite | gc.Move}, // Jumps ppc64.ABR: {Flags: gc.Jump | gc.Break}, ppc64.ABL: {Flags: gc.Call}, ppc64.ABEQ: {Flags: gc.Cjmp}, ppc64.ABNE: {Flags: gc.Cjmp}, ppc64.ABGE: {Flags: gc.Cjmp}, ppc64.ABLT: {Flags: gc.Cjmp}, ppc64.ABGT: {Flags: gc.Cjmp}, ppc64.ABLE: {Flags: gc.Cjmp}, obj.ARET: {Flags: gc.Break}, obj.ADUFFZERO: {Flags: gc.Call}, obj.ADUFFCOPY: {Flags: gc.Call}, } var <API key> int func initproginfo() { var addvariant = []int{V_CC, V_V, V_CC | V_V} if <API key> != 0 { return } <API key> = 1 // Perform one-time expansion of instructions in progtable to // their CC, V, and VCC variants var as2 int var i int var variant int for as := int(0); as < len(progtable); as++ { if progtable[as].Flags == 0 { continue } variant = as2variant(as) for i = 0; i < len(addvariant); i++ { as2 = variant2as(as, variant|addvariant[i]) if as2 != 0 && progtable[as2].Flags == 0 { progtable[as2] = progtable[as] } } } } func proginfo(p *obj.Prog) { initproginfo() info := &p.Info *info = progtable[p.As] if info.Flags == 0 { gc.Fatalf("proginfo: unknown instruction %v", p) } if (info.Flags&gc.RegRead != 0) && p.Reg == 0 { info.Flags &^= gc.RegRead info.Flags |= gc.RightRead /*CanRegRead |*/ } if (p.From.Type == obj.TYPE_MEM || p.From.Type == obj.TYPE_ADDR) && p.From.Reg != 0 { info.Regindex |= RtoB(int(p.From.Reg)) if info.Flags&gc.PostInc != 0 { info.Regset |= RtoB(int(p.From.Reg)) } } if (p.To.Type == obj.TYPE_MEM || p.To.Type == obj.TYPE_ADDR) && p.To.Reg != 0 { info.Regindex |= RtoB(int(p.To.Reg)) if info.Flags&gc.PostInc != 0 { info.Regset |= RtoB(int(p.To.Reg)) } } if p.From.Type == obj.TYPE_ADDR && p.From.Sym != nil && (info.Flags&gc.LeftRead != 0) { info.Flags &^= gc.LeftRead info.Flags |= gc.LeftAddr } if p.As == obj.ADUFFZERO { info.Reguse |= 1<<0 | RtoB(ppc64.REG_R3) info.Regset |= RtoB(ppc64.REG_R3) } if p.As == obj.ADUFFCOPY { // TODO(austin) Revisit when duffcopy is implemented info.Reguse |= RtoB(ppc64.REG_R3) | RtoB(ppc64.REG_R4) | RtoB(ppc64.REG_R5) info.Regset |= RtoB(ppc64.REG_R3) | RtoB(ppc64.REG_R4) } } // Instruction variants table. Initially this contains entries only // for the "base" form of each instruction. On the first call to // as2variant or variant2as, we'll add the variants to the table. var varianttable = [ppc64.ALAST][4]int{ ppc64.AADD: {ppc64.AADD, ppc64.AADDCC, ppc64.AADDV, ppc64.AADDVCC}, ppc64.AADDC: {ppc64.AADDC, ppc64.AADDCCC, ppc64.AADDCV, ppc64.AADDCVCC}, ppc64.AADDE: {ppc64.AADDE, ppc64.AADDECC, ppc64.AADDEV, ppc64.AADDEVCC}, ppc64.AADDME: {ppc64.AADDME, ppc64.AADDMECC, ppc64.AADDMEV, ppc64.AADDMEVCC}, ppc64.AADDZE: {ppc64.AADDZE, ppc64.AADDZECC, ppc64.AADDZEV, ppc64.AADDZEVCC}, ppc64.AAND: {ppc64.AAND, ppc64.AANDCC, 0, 0}, ppc64.AANDN: {ppc64.AANDN, ppc64.AANDNCC, 0, 0}, ppc64.ACNTLZD: {ppc64.ACNTLZD, ppc64.ACNTLZDCC, 0, 0}, ppc64.ACNTLZW: {ppc64.ACNTLZW, ppc64.ACNTLZWCC, 0, 0}, ppc64.ADIVD: {ppc64.ADIVD, ppc64.ADIVDCC, ppc64.ADIVDV, ppc64.ADIVDVCC}, ppc64.ADIVDU: {ppc64.ADIVDU, ppc64.ADIVDUCC, ppc64.ADIVDUV, ppc64.ADIVDUVCC}, ppc64.ADIVW: {ppc64.ADIVW, ppc64.ADIVWCC, ppc64.ADIVWV, ppc64.ADIVWVCC}, ppc64.ADIVWU: {ppc64.ADIVWU, ppc64.ADIVWUCC, ppc64.ADIVWUV, ppc64.ADIVWUVCC}, ppc64.AEQV: {ppc64.AEQV, ppc64.AEQVCC, 0, 0}, ppc64.AEXTSB: {ppc64.AEXTSB, ppc64.AEXTSBCC, 0, 0}, ppc64.AEXTSH: {ppc64.AEXTSH, ppc64.AEXTSHCC, 0, 0}, ppc64.AEXTSW: {ppc64.AEXTSW, ppc64.AEXTSWCC, 0, 0}, ppc64.AFABS: {ppc64.AFABS, ppc64.AFABSCC, 0, 0}, ppc64.AFADD: {ppc64.AFADD, ppc64.AFADDCC, 0, 0}, ppc64.AFADDS: {ppc64.AFADDS, ppc64.AFADDSCC, 0, 0}, ppc64.AFCFID: {ppc64.AFCFID, ppc64.AFCFIDCC, 0, 0}, ppc64.AFCTID: {ppc64.AFCTID, ppc64.AFCTIDCC, 0, 0}, ppc64.AFCTIDZ: {ppc64.AFCTIDZ, ppc64.AFCTIDZCC, 0, 0}, ppc64.AFCTIW: {ppc64.AFCTIW, ppc64.AFCTIWCC, 0, 0}, ppc64.AFCTIWZ: {ppc64.AFCTIWZ, ppc64.AFCTIWZCC, 0, 0}, ppc64.AFDIV: {ppc64.AFDIV, ppc64.AFDIVCC, 0, 0}, ppc64.AFDIVS: {ppc64.AFDIVS, ppc64.AFDIVSCC, 0, 0}, ppc64.AFMADD: {ppc64.AFMADD, ppc64.AFMADDCC, 0, 0}, ppc64.AFMADDS: {ppc64.AFMADDS, ppc64.AFMADDSCC, 0, 0}, ppc64.AFMOVD: {ppc64.AFMOVD, ppc64.AFMOVDCC, 0, 0}, ppc64.AFMSUB: {ppc64.AFMSUB, ppc64.AFMSUBCC, 0, 0}, ppc64.AFMSUBS: {ppc64.AFMSUBS, ppc64.AFMSUBSCC, 0, 0}, ppc64.AFMUL: {ppc64.AFMUL, ppc64.AFMULCC, 0, 0}, ppc64.AFMULS: {ppc64.AFMULS, ppc64.AFMULSCC, 0, 0}, ppc64.AFNABS: {ppc64.AFNABS, ppc64.AFNABSCC, 0, 0}, ppc64.AFNEG: {ppc64.AFNEG, ppc64.AFNEGCC, 0, 0}, ppc64.AFNMADD: {ppc64.AFNMADD, ppc64.AFNMADDCC, 0, 0}, ppc64.AFNMADDS: {ppc64.AFNMADDS, ppc64.AFNMADDSCC, 0, 0}, ppc64.AFNMSUB: {ppc64.AFNMSUB, ppc64.AFNMSUBCC, 0, 0}, ppc64.AFNMSUBS: {ppc64.AFNMSUBS, ppc64.AFNMSUBSCC, 0, 0}, ppc64.AFRES: {ppc64.AFRES, ppc64.AFRESCC, 0, 0}, ppc64.AFRSP: {ppc64.AFRSP, ppc64.AFRSPCC, 0, 0}, ppc64.AFRSQRTE: {ppc64.AFRSQRTE, ppc64.AFRSQRTECC, 0, 0}, ppc64.AFSEL: {ppc64.AFSEL, ppc64.AFSELCC, 0, 0}, ppc64.AFSQRT: {ppc64.AFSQRT, ppc64.AFSQRTCC, 0, 0}, ppc64.AFSQRTS: {ppc64.AFSQRTS, ppc64.AFSQRTSCC, 0, 0}, ppc64.AFSUB: {ppc64.AFSUB, ppc64.AFSUBCC, 0, 0}, ppc64.AFSUBS: {ppc64.AFSUBS, ppc64.AFSUBSCC, 0, 0}, ppc64.AMTFSB0: {ppc64.AMTFSB0, ppc64.AMTFSB0CC, 0, 0}, ppc64.AMTFSB1: {ppc64.AMTFSB1, ppc64.AMTFSB1CC, 0, 0}, ppc64.AMULHD: {ppc64.AMULHD, ppc64.AMULHDCC, 0, 0}, ppc64.AMULHDU: {ppc64.AMULHDU, ppc64.AMULHDUCC, 0, 0}, ppc64.AMULHW: {ppc64.AMULHW, ppc64.AMULHWCC, 0, 0}, ppc64.AMULHWU: {ppc64.AMULHWU, ppc64.AMULHWUCC, 0, 0}, ppc64.AMULLD: {ppc64.AMULLD, ppc64.AMULLDCC, ppc64.AMULLDV, ppc64.AMULLDVCC}, ppc64.AMULLW: {ppc64.AMULLW, ppc64.AMULLWCC, ppc64.AMULLWV, ppc64.AMULLWVCC}, ppc64.ANAND: {ppc64.ANAND, ppc64.ANANDCC, 0, 0}, ppc64.ANEG: {ppc64.ANEG, ppc64.ANEGCC, ppc64.ANEGV, ppc64.ANEGVCC}, ppc64.ANOR: {ppc64.ANOR, ppc64.ANORCC, 0, 0}, ppc64.AOR: {ppc64.AOR, ppc64.AORCC, 0, 0}, ppc64.AORN: {ppc64.AORN, ppc64.AORNCC, 0, 0}, ppc64.AREM: {ppc64.AREM, ppc64.AREMCC, ppc64.AREMV, ppc64.AREMVCC}, ppc64.AREMD: {ppc64.AREMD, ppc64.AREMDCC, ppc64.AREMDV, ppc64.AREMDVCC}, ppc64.AREMDU: {ppc64.AREMDU, ppc64.AREMDUCC, ppc64.AREMDUV, ppc64.AREMDUVCC}, ppc64.AREMU: {ppc64.AREMU, ppc64.AREMUCC, ppc64.AREMUV, ppc64.AREMUVCC}, ppc64.ARLDC: {ppc64.ARLDC, ppc64.ARLDCCC, 0, 0}, ppc64.ARLDCL: {ppc64.ARLDCL, ppc64.ARLDCLCC, 0, 0}, ppc64.ARLDCR: {ppc64.ARLDCR, ppc64.ARLDCRCC, 0, 0}, ppc64.ARLDMI: {ppc64.ARLDMI, ppc64.ARLDMICC, 0, 0}, ppc64.ARLWMI: {ppc64.ARLWMI, ppc64.ARLWMICC, 0, 0}, ppc64.ARLWNM: {ppc64.ARLWNM, ppc64.ARLWNMCC, 0, 0}, ppc64.ASLD: {ppc64.ASLD, ppc64.ASLDCC, 0, 0}, ppc64.ASLW: {ppc64.ASLW, ppc64.ASLWCC, 0, 0}, ppc64.ASRAD: {ppc64.ASRAD, ppc64.ASRADCC, 0, 0}, ppc64.ASRAW: {ppc64.ASRAW, ppc64.ASRAWCC, 0, 0}, ppc64.ASRD: {ppc64.ASRD, ppc64.ASRDCC, 0, 0}, ppc64.ASRW: {ppc64.ASRW, ppc64.ASRWCC, 0, 0}, ppc64.ASUB: {ppc64.ASUB, ppc64.ASUBCC, ppc64.ASUBV, ppc64.ASUBVCC}, ppc64.ASUBC: {ppc64.ASUBC, ppc64.ASUBCCC, ppc64.ASUBCV, ppc64.ASUBCVCC}, ppc64.ASUBE: {ppc64.ASUBE, ppc64.ASUBECC, ppc64.ASUBEV, ppc64.ASUBEVCC}, ppc64.ASUBME: {ppc64.ASUBME, ppc64.ASUBMECC, ppc64.ASUBMEV, ppc64.ASUBMEVCC}, ppc64.ASUBZE: {ppc64.ASUBZE, ppc64.ASUBZECC, ppc64.ASUBZEV, ppc64.ASUBZEVCC}, ppc64.AXOR: {ppc64.AXOR, ppc64.AXORCC, 0, 0}, } var <API key> int func initvariants() { if <API key> != 0 { return } <API key> = 1 var j int for i := int(0); i < len(varianttable); i++ { if varianttable[i][0] == 0 { // Instruction has no variants varianttable[i][0] = i continue } // Copy base form to other variants if varianttable[i][0] == i { for j = 0; j < len(varianttable[i]); j++ { varianttable[varianttable[i][j]] = varianttable[i] } } } } // as2variant returns the variant (V_*) flags of instruction as. func as2variant(as int) int { initvariants() for i := int(0); i < len(varianttable[as]); i++ { if varianttable[as][i] == as { return i } } gc.Fatalf("as2variant: instruction %v is not a variant of itself", obj.Aconv(as)) return 0 } // variant2as returns the instruction as with the given variant (V_*) flags. // If no such variant exists, this returns 0. func variant2as(as int, flags int) int { initvariants() return varianttable[as][flags] }
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.cpp Label Definition File: <API key>.label.xml Template File: sources-sink-04.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sink: loop * BadSink : Copy int array to data using a loop * Flow Variant: 04 Control flow: if(STATIC_CONST_TRUE) and if(STATIC_CONST_FALSE) * * */ #include "std_testcase.h" /* The two variables below are declared "const", so a tool should be able to identify that reads of these will always return their initialized values. */ static const int STATIC_CONST_TRUE = 1; /* true */ static const int STATIC_CONST_FALSE = 0; /* false */ namespace <API key> { #ifndef OMITBAD void bad() { int * data; data = NULL; if(STATIC_CONST_TRUE) { /* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = new int[50]; } { int source[100] = {0}; /* fill with 0's */ { size_t i; /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ for (i = 0; i < 100; i++) { data[i] = source[i]; } printIntLine(data[0]); delete [] data; } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the STATIC_CONST_TRUE to STATIC_CONST_FALSE */ static void goodG2B1() { int * data; data = NULL; if(STATIC_CONST_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = new int[100]; } { int source[100] = {0}; /* fill with 0's */ { size_t i; /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ for (i = 0; i < 100; i++) { data[i] = source[i]; } printIntLine(data[0]); delete [] data; } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { int * data; data = NULL; if(STATIC_CONST_TRUE) { /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = new int[100]; } { int source[100] = {0}; /* fill with 0's */ { size_t i; /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ for (i = 0; i < 100; i++) { data[i] = source[i]; } printIntLine(data[0]); delete [] data; } } } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace <API key>; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
using System; using System.Collections; namespace MyGeneration.CodeSmithConversion.Template { public enum CstTokenType { Code = 0, <API key>, RunAtServerCode, Literal, Comment, EscapedStartTag, EscapedEndTag } <summary> Summary description for CstToken. </summary> public class CstToken { private string text; private CstTokenType tokenType = CstTokenType.Literal; public CstToken(CstTokenType tokenType, string text) { this.tokenType = tokenType; this.text = text; } public string Text { get { return text; } set { text = value; } } public CstTokenType TokenType { get { return tokenType; } set { tokenType = value; } } } }
<div> <a href="#" title="Click or press enter to display help" class="dropdown standalone-help" data-toggle="reset-page-help" tab-index="0"> <span class="icon-circle"><i class="fa fa-info"></i></span> </a> </div> <div class="dropdown-pane" id="reset-page-help" data-dropdown data-hover="true" data-hover-pane="true" data-auto-focus="true"> <p>If you cannot complete the password reset form, please bring University-issued photo identification to the Bruin OnLine Help Desk located in Suite 124, Kerckhoff Hall. If you are not able to visit the Help Desk, please fax in a completed copy of the <a href="/files/service_request.pdf">UCLA Logon Service Request Form</a>, with all required supporting documentation.</p> </div>
/* * @description Expression is always true via if (unsigned int >= 0) * * */ #include "std_testcase.h" #ifndef OMITBAD void <API key>() { /* Ensure (0 <= intBad < UINT_MAX) and that uIntBad is pseudo-random */ unsigned int uIntBad = (unsigned int)(rand() * 2); /* FLAW: This expression is always true */ if (uIntBad >= 0) { printLine("Always prints"); } } #endif /* OMITBAD */ #ifndef OMITGOOD static void good1() { int intGood = rand(); /* FIX: Possibly evaluate to true */ if (intGood > (RAND_MAX / 2)) { printLine("Sometimes prints"); } } void <API key>() { good1(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); <API key>(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); <API key>(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
#ifndef <API key> #define <API key> #pragma once #include "base/compiler_specific.h" #include "chrome/browser/ui/webui/options/options_ui.h" namespace chromeos { // ChromeOS handler for "Stats/crash reporting to Google" option of the Advanced // settings page. This handler does only ChromeOS-specific actions while default // code is in Chrome's <API key> // (chrome/browser/webui/<API key>.cc). class StatsOptionsHandler : public <API key> { public: StatsOptionsHandler(); // <API key> implementation. virtual void GetLocalizedValues( base::DictionaryValue* localized_strings) OVERRIDE; virtual void Initialize() OVERRIDE; // WebUIMessageHandler implementation. virtual void RegisterMessages() OVERRIDE; private: void <API key>(const base::ListValue* args); <API key>(StatsOptionsHandler); }; } // namespace chromeos #endif // <API key>
ENV['RAILS_ENV'] ||= 'test' if ENV['TRAVIS'] require 'coveralls' Coveralls.wear!('rails') SimpleCov.start do add_filter '.bundle' add_filter 'spec' end end require 'spec_helper' require File.expand_path('../../config/environment', __FILE__) require 'rspec/rails' require 'rspec/its' require 'shoulda/matchers' require 'capybara/poltergeist' Capybara.javascript_driver = :poltergeist Capybara.default_wait_time = 30 Rails.logger.level = 4 # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. Dir[Rails.root.join('spec/support*.rb')].each { |f| require f } # Checks for pending migrations before tests are run. ActiveRecord::Migration.<API key>! RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods config.include Features::SessionHelpers, type: :feature config.include Features::FormHelpers, type: :feature config.include Features::ScheduleHelpers, type: :feature config.include Features::PhoneHelpers, type: :feature config.include Features::ContactHelpers, type: :feature config.include Requests::RequestHelpers, type: :request config.include DefaultHeaders, type: :request config.include MailerMacros # rspec-rails 3+ will no longer automatically infer an example group's spec # type from the file location. You can explicitly opt-in to this feature by # uncommenting the setting below. config.<API key>! # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/support/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.<API key> = false # require '<API key>' end
'use strict'; jest.unmock('everyObject'); var everyObject = require('everyObject'); describe('everyObject', function() { var mockObject; var mockCallback; beforeEach(() => { mockObject = {foo: 1, bar: 2, baz: 3}; mockCallback = jest.fn(); }); it('handles null', () => { everyObject(null, mockCallback); expect(mockCallback).not.toBeCalled(); }); it('returns true if all properties pass the test', () => { mockCallback.mockImplementation(() => true); var result = everyObject(mockObject, mockCallback); expect(result).toBeTruthy(); expect(mockCallback.mock.calls).toEqual([ [1, 'foo', mockObject], [2, 'bar', mockObject], [3, 'baz', mockObject] ]); }); it('returns false if any of the properties fail the test', () => { mockCallback.mockImplementation(() => false); var result = everyObject(mockObject, mockCallback); expect(result).toBeFalsy(); expect(mockCallback).toBeCalled(); }); it('returns immediately upon finding a property that fails the test', () => { mockCallback.mockImplementation(() => false); var result = everyObject(mockObject, mockCallback); expect(result).toBeFalsy(); expect(mockCallback.mock.calls.length).toEqual(1); }); });
#ifndef <API key> #define <API key> #include <stddef.h> #include "base/memory/weak_ptr.h" #include "components/omnibox/browser/<API key>.h" #include "components/omnibox/browser/omnibox_popup_view.h" #include "components/prefs/<API key>.h" #include "ui/base/metadata/<API key>.h" #include "ui/base/<API key>.h" #include "ui/gfx/font_list.h" #include "ui/gfx/image/image.h" #include "ui/views/view.h" #include "ui/views/widget/widget_observer.h" struct AutocompleteMatch; class LocationBarView; class OmniboxEditModel; class OmniboxResultView; class OmniboxViewViews; class <API key>; // A view representing the contents of the autocomplete popup. class <API key> : public views::View, public OmniboxPopupView, public views::WidgetObserver { public: METADATA_HEADER(<API key>); <API key>(OmniboxViewViews* omnibox_view, OmniboxEditModel* edit_model, LocationBarView* location_bar_view); <API key>(const <API key>&) = delete; <API key>& operator=(const <API key>&) = delete; ~<API key>() override; // Opens a match from the list specified by |index| with the type of tab or // window specified by |disposition|. void OpenMatch(<API key> disposition, base::TimeTicks <API key>); void OpenMatch(size_t index, <API key> disposition, base::TimeTicks <API key>); // Returns the icon that should be displayed next to |match|. If the icon is // available as a vector icon, it will be |vector_icon_color|. gfx::Image GetMatchIcon(const AutocompleteMatch& match, SkColor vector_icon_color) const; // Sets the line specified by |index| as selected and, if |index| is // different than the previous index, sets the line state to NORMAL. virtual void SetSelectedIndex(size_t index); // Returns the selected line. // Note: This and `SetSelectedIndex` above are used by property // metadata and must follow the metadata conventions. virtual size_t GetSelectedIndex() const; // Returns current popup selection (includes line index). virtual <API key> GetSelection() const; // Called by the active result view to inform model (due to mouse event). void UnselectButton(); // Gets the OmniboxResultView for match |i|. OmniboxResultView* result_view_at(size_t i); // Currently selected OmniboxResultView, or nullptr if nothing is selected. OmniboxResultView* <API key>(); // Returns whether we're in experimental keyword mode and the input gives // sufficient confidence that the user wants keyword mode. bool <API key>(); // OmniboxPopupView: bool IsOpen() const override; void InvalidateLine(size_t line) override; void OnSelectionChanged(<API key> old_selection, <API key> new_selection) override; void <API key>() override; void <API key>(size_t line) override; void OnMatchIconUpdated(size_t match_index) override; void OnDragCanceled() override; // views::View: bool OnMouseDragged(const ui::MouseEvent& event) override; void OnGestureEvent(ui::GestureEvent* event) override; void <API key>(ui::AXNodeData* node_data) override; // views::WidgetObserver: void <API key>(views::Widget* widget, const gfx::Rect& new_bounds) override; void <API key>(View* descendant_view); private: friend class <API key>; friend class <API key>; class <API key>; // Returns the target popup bounds in screen coordinates based on the bounds // of |location_bar_view_|. gfx::Rect GetTargetBounds() const; // Returns true if the model has a match at the specified index. bool HasMatchAt(size_t index) const; // Returns the match at the specified index within the model. const AutocompleteMatch& GetMatchAtIndex(size_t index) const; // Find the index of the match under the given |point|, specified in window // coordinates. Returns <API key>::kNoMatch if there isn't a match // at the specified point. size_t GetIndexForPoint(const gfx::Point& point); // Update which result views are visible when the group visibility changes. void <API key>(); // Gets the pref service for this view. May return nullptr in tests. PrefService* GetPrefService() const; // The popup that contains this view. We create this, but it deletes itself // when its window is destroyed. This is a WeakPtr because it's possible for // the OS to destroy the window and thus delete this object before we're // deleted, or without our knowledge. base::WeakPtr<<API key>> popup_; // The edit view that invokes us. OmniboxViewViews* omnibox_view_; // The location bar view that owns |omnibox_view_|. May be nullptr in tests. LocationBarView* location_bar_view_; // The child WebView for the suggestions. This only exists if the // omnibox::kWebUIOmniboxPopup flag is on. <API key>* webui_view_ = nullptr; // A pref change registrar for toggling result view visibility. PrefChangeRegistrar <API key>; OmniboxEditModel* edit_model_; }; #endif // <API key>
<!DOCTYPE html> <html dir="ltr" lang="pl"> <head> <title>Foreign Function Interface - Rubinius</title> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta content='pl' http-equiv='content-language'> <meta content='Rubinius is an implementation of the Ruby programming language. The Rubinius bytecode virtual machine is written in C++. The bytecode compiler is written in pure Ruby. The vast majority of the core library is also written in Ruby, with some supporting primitives that interact with the VM directly.' name='description'> <link href='/' rel='home'> <link href='/' rel='start'> <link href='/doc/pl/systems/primitives' rel='prev' title='Primitives'> <link href='/doc/pl/systems/concurrency' rel='next' title='Współbieżność'> <script src="/javascripts/jquery-1.3.2.js"></script> <script src="/javascripts/paging_keys.js"></script> <script src="/javascripts/application.js"></script> <style>article, aside, dialog, figure, footer, header, hgroup, menu, nav, section { display: block; }</style> <link href="/stylesheets/blueprint/screen.css" media="screen" rel="stylesheet" /> <link href="/stylesheets/application.css" media="screen" rel="stylesheet" /> <link href="/stylesheets/blueprint/print.css" media="print" rel="stylesheet" /> <!--[if IE]><link href="/stylesheets/blueprint/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]--> <!--[if IE]><link href="/stylesheets/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]--> <link href="/stylesheets/pygments.css" media="screen" rel="stylesheet" /> </head> <body> <div class='container'> <div class='span-21 doc_menu'> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a id="blog" href="/blog">Blog</a></li> <li><a id="documentation" href="/doc/en">Documentation</a></li> <li><a href="/projects">Projects</a></li> <li><a href="/roadmap">Roadmap</a></li> <li><a href="/releases">Releases</a></li> </ul> </nav> </header> </div> <div class='span-3 last'> <div id='version'> <a href="/releases/1.2.4">1.2.4</a> </div> </div> </div> <div class="container languages"> <nav> <span class="label">Język:</span> <ul> <li><a href="/doc/de/systems/ffi/" >de</a></li> <li><a href="/doc/en/systems/ffi/" >en</a></li> <li><a href="/doc/es/systems/ffi/" >es</a></li> <li><a href="/doc/fr/systems/ffi/" >fr</a></li> <li><a href="/doc/ja/systems/ffi/" >ja</a></li> <li><a href="/doc/pl/systems/ffi/" class="current" >pl</a></li> <li><a href="/doc/pt-br/systems/ffi/" >pt-br</a></li> <li><a href="/doc/ru/systems/ffi/" >ru</a></li> </ul> </nav> </div> <div class="container doc_page_nav"> <span class="label">Wstecz:</span> <a href="/doc/pl/systems/primitives">Primitives</a> <span class="label">Do góry:</span> <a href="/doc/pl/">Spis treści</a> <span class="label">Dalej:</span> <a href="/doc/pl/systems/concurrency">Współbieżność</a> </div> <div class="container documentation"> <h2>Foreign Function Interface</h2> <div class="review"> <p>This topic has missing or partial documentation. Please help us improve it.</p> <p> See <a href="/doc/pl/how-to/write-documentation">How-To - Write Documentation</a> </p> </div> </div> <div class="container doc_page_nav"> <span class="label">Wstecz:</span> <a href="/doc/pl/systems/primitives">Primitives</a> <span class="label">Do góry:</span> <a href="/doc/pl/">Spis treści</a> <span class="label">Dalej:</span> <a href="/doc/pl/systems/concurrency">Współbieżność</a> </div> <div class="container"> <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = 'rubinius'; var disqus_identifier = '/doc/pl/systems/ffi/'; var disqus_url = 'http://rubini.us/doc/pl/systems/ffi/'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; (document.<API key>('head')[0] || document.<API key>('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> <footer> <div class='container'> <nav> <ul> <li><a rel="external" href="http://twitter.com/rubinius">Follow Rubinius on Twitter</a></li> <li><a rel="external" href="http://github.com/rubinius/rubinius">Fork Rubinius on github</a></li> <li><a rel="external" href="http://engineyard.com">An Engine Yard project</a></li> </ul> </nav> </div> </footer> <script> var _gaq=[['_setAccount','UA-12328521-1'],['_trackPageview']]; (function(d,t){var g=d.createElement(t),s=d.<API key>(t)[0];g.async=1; g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js'; s.parentNode.insertBefore(g,s)}(document,'script')); </script> </body> </html>
#include "UmbrellaProtocol.h" #include <folly/Bits.h> #include "mcrouter/lib/McReply.h" #include "mcrouter/lib/McRequest.h" #include "mcrouter/lib/mc/umbrella.h" #ifndef <API key> #include "mcrouter/lib/mc/mc_fbtrace_info.h" #endif static_assert( mc_nops == 27, "If you add a new mc_op, make sure to update lib/mc/umbrella_conv.h"); static_assert( UM_NOPS == 28, "If you add a new mc_op, make sure to update lib/mc/umbrella_conv.h"); static_assert( mc_nres == 31, "If you add a new mc_res, make sure to update lib/mc/umbrella_conv.h"); namespace facebook { namespace memcache { UmbrellaParseStatus umbrellaParseHeader(const uint8_t* buf, size_t nbuf, UmbrellaMessageInfo& infoOut) { if (nbuf < sizeof(entry_list_msg_t)) { return UmbrellaParseStatus::NOT_ENOUGH_DATA; } entry_list_msg_t* header = (entry_list_msg_t*) buf; if (header->msg_header.magic_byte != <API key>) { return UmbrellaParseStatus::MESSAGE_PARSE_ERROR; } infoOut.version = static_cast<UmbrellaVersion>(header->msg_header.version); if (infoOut.version == UmbrellaVersion::BASIC) { /* Basic version layout: }0NNSSSS, <um_elist_entry_t>*nentries, body Where N is nentries and S is message size, both big endian */ size_t messageSize = folly::Endian::big<uint32_t>(header->total_size); uint16_t nentries = folly::Endian::big<uint16_t>(header->nentries); infoOut.headerSize = sizeof(entry_list_msg_t) + sizeof(um_elist_entry_t) * nentries; if (infoOut.headerSize > messageSize) { return UmbrellaParseStatus::MESSAGE_PARSE_ERROR; } infoOut.bodySize = messageSize - infoOut.headerSize; } else if (infoOut.version == UmbrellaVersion::TYPED_REQUEST) { /* Typed request layout: }1TTSSSSFFFFRRRR, body Where T is type ID, S is message size, F is flags and R is reqid (all little-endian) */ size_t messageSize = folly::Endian::little<uint32_t>(header->total_size); infoOut.typeId = folly::Endian::little<uint16_t>(header->nentries); infoOut.headerSize = sizeof(entry_list_msg_t) + sizeof(uint32_t) + sizeof(uint32_t); if (infoOut.headerSize > messageSize) { return UmbrellaParseStatus::MESSAGE_PARSE_ERROR; } infoOut.bodySize = messageSize - infoOut.headerSize; } else { return UmbrellaParseStatus::MESSAGE_PARSE_ERROR; } return UmbrellaParseStatus::OK; } uint64_t <API key>(const uint8_t* header, size_t nheader) { auto msg = reinterpret_cast<const entry_list_msg_t*>(header); size_t nentries = folly::Endian::big((uint16_t)msg->nentries); if (reinterpret_cast<const uint8_t*>(&msg->entries[nentries]) != header + nheader) { throw std::runtime_error("Invalid number of entries"); } for (size_t i = 0; i < nentries; ++i) { auto& entry = msg->entries[i]; size_t tag = folly::Endian::big((uint16_t)entry.tag); if (tag == msg_reqid) { uint64_t val = folly::Endian::big((uint64_t)entry.data.val); if (val == 0) { throw std::runtime_error("invalid reqid"); } return val; } } throw std::runtime_error("missing reqid"); } McRequest <API key>(const folly::IOBuf& source, const uint8_t* header, size_t nheader, const uint8_t* body, size_t nbody, mc_op_t& opOut, uint64_t& reqidOut) { McRequest req; opOut = mc_op_unknown; reqidOut = 0; auto msg = reinterpret_cast<const entry_list_msg_t*>(header); size_t nentries = folly::Endian::big((uint16_t)msg->nentries); if (reinterpret_cast<const uint8_t*>(&msg->entries[nentries]) != header + nheader) { throw std::runtime_error("Invalid number of entries"); } for (size_t i = 0; i < nentries; ++i) { auto& entry = msg->entries[i]; size_t tag = folly::Endian::big((uint16_t)entry.tag); size_t val = folly::Endian::big((uint64_t)entry.data.val); switch (tag) { case msg_op: if (val >= UM_NOPS) { throw std::runtime_error("op out of range"); } opOut = static_cast<mc_op_t>(umbrella_op_to_mc[val]); break; case msg_reqid: if (val == 0) { throw std::runtime_error("invalid reqid"); } reqidOut = val; break; case msg_flags: req.setFlags(val); break; case msg_exptime: req.setExptime(val); break; case msg_delta: req.setDelta(val); break; case msg_cas: req.setCas(val); break; case msg_lease_id: req.setLeaseToken(val); break; case msg_key: if (!req.setKeyFrom( source, body + folly::Endian::big((uint32_t)entry.data.str.offset), folly::Endian::big((uint32_t)entry.data.str.len) - 1)) { throw std::runtime_error("Key: invalid offset/length"); } break; case msg_value: if (!req.setValueFrom( source, body + folly::Endian::big((uint32_t)entry.data.str.offset), folly::Endian::big((uint32_t)entry.data.str.len) - 1)) { throw std::runtime_error("Value: invalid offset/length"); } break; #ifndef <API key> case msg_fbtrace: { auto off = folly::Endian::big((uint32_t)entry.data.str.offset); auto len = folly::Endian::big((uint32_t)entry.data.str.len) - 1; if (len > FBTRACE_METADATA_SZ) { throw std::runtime_error("Fbtrace metadata too large"); } if (off + len > nbody || off + len < off) { throw std::runtime_error("Fbtrace metadata field invalid"); } auto fbtraceInfo = new_mc_fbtrace_info(0); memcpy(fbtraceInfo->metadata, body + off, len); req.setFbtraceInfo(fbtraceInfo); break; } #endif default: /* Ignore unknown tags silently */ break; } } if (opOut == mc_op_unknown) { throw std::runtime_error("Request missing operation"); } if (!reqidOut) { throw std::runtime_error("Request missing reqid"); } return req; } <API key>::<API key>() { /* These will not change from message to message */ msg_.msg_header.magic_byte = <API key>; msg_.msg_header.version = <API key>; iovs_[0].iov_base = &msg_; iovs_[0].iov_len = sizeof(msg_); iovs_[1].iov_base = entries_; } void <API key>::clear() { nEntries_ = nStrings_ = offset_ = 0; error_ = false; } bool <API key>::prepare(const McReply& reply, mc_op_t op, uint64_t reqid, struct iovec*& iovOut, size_t& niovOut) { niovOut = 0; appendInt(I32, msg_op, umbrella_op_from_mc[op]); appendInt(U64, msg_reqid, reqid); appendInt(I32, msg_result, <API key>[reply.result()]); if (reply.<API key>()) { appendInt(I32, msg_err_code, reply.<API key>()); } if (reply.flags()) { appendInt(U64, msg_flags, reply.flags()); } if (reply.exptime()) { appendInt(U64, msg_exptime, reply.exptime()); } if (reply.delta()) { appendInt(U64, msg_delta, reply.delta()); } if (reply.leaseToken()) { appendInt(U64, msg_lease_id, reply.leaseToken()); } if (reply.cas()) { appendInt(U64, msg_cas, reply.cas()); } if (reply.number()) { appendInt(U64, msg_number, reply.number()); } /* TODO: if we intend to pass chained IOBufs as values, we can optimize this to write multiple iovs directly */ if (reply.hasValue()) { auto valueRange = reply.valueRangeSlow(); appendString(msg_value, reinterpret_cast<const uint8_t*>(valueRange.begin()), valueRange.size()); } /* NOTE: this check must come after all append*() calls */ if (error_) { return false; } niovOut = finalizeMessage(); iovOut = iovs_; return true; } void <API key>::appendInt( entry_type_t type, int32_t tag, uint64_t val) { if (nEntries_ >= kInlineEntries) { error_ = true; return; } um_elist_entry_t& entry = entries_[nEntries_++]; entry.type = folly::Endian::big((uint16_t)type); entry.tag = folly::Endian::big((uint16_t)tag); entry.data.val = folly::Endian::big((uint64_t)val); } void <API key>::appendString( int32_t tag, const uint8_t* data, size_t len, entry_type_t type) { if (nStrings_ >= kInlineStrings) { error_ = true; return; } strings_[nStrings_++] = folly::StringPiece((const char*)data, len); um_elist_entry_t& entry = entries_[nEntries_++]; entry.type = folly::Endian::big((uint16_t)type); entry.tag = folly::Endian::big((uint16_t)tag); entry.data.str.offset = folly::Endian::big((uint32_t)offset_); entry.data.str.len = folly::Endian::big((uint32_t)(len + 1)); offset_ += len + 1; } size_t <API key>::finalizeMessage() { static char nul = '\0'; size_t size = sizeof(entry_list_msg_t) + sizeof(um_elist_entry_t) * nEntries_ + offset_; msg_.total_size = folly::Endian::big((uint32_t)size); msg_.nentries = folly::Endian::big((uint16_t)nEntries_); iovs_[1].iov_len = sizeof(um_elist_entry_t) * nEntries_; size_t niovOut = 2; for (size_t i = 0; i < nStrings_; i++) { iovs_[niovOut].iov_base = (char *)strings_[i].begin(); iovs_[niovOut].iov_len = strings_[i].size(); niovOut++; iovs_[niovOut].iov_base = &nul; iovs_[niovOut].iov_len = 1; niovOut++; } return niovOut; } }}
// This software is a modification of: /*! @file priority_deque.h // priority_deque.hpp provides the class priority_deque as a thin wrapper // around the functions provided by interval_heap.hpp. // @remark Exception-safety: If the means of movement -- move, copy, or swap, // depending on exception specifications -- do not throw, the guarantee is as // strong as that of the action on the underlying container. (Unless otherwise // specified) // @note Providing a stronger guarantee is impractical. */ #pragma once #include <nvbio/basic/types.h> #include <nvbio/basic/interval_heap.h> // Default comparison (std::less) #include <functional> // Default container (std::vector) #include <vector> namespace nvbio { \page <API key> Priority Deques This module implements a priority deque adaptor, allowing to push/pop from both ends of the container: - priority_deque \section ExampleSection Example \code // build a simple priority_deque over 4 integers typedef vector_view<uint32*> vector_type; typedef priority_deque<uint32, vector_type> deque_type; uint32 deque_storage[4] = { 5, 3, 8, 1 } // construct the deque deque_type deque( vector_type( 4u, deque_storage ) ); // pop from both ends printf( "%u\n", deque.top() ); deque.pop_top(); printf( "%u\n", deque.bottom() ); deque.pop_bottom(); printf( "%u\n", deque.top() ); deque.pop_top(); // perhaps push one more item deque.push( 7 ); // and keep popping printf( "%u\n", deque.bottom() ); deque.pop_bottom(); printf( "%u\n", deque.bottom() ); deque.pop_bottom(); \endcode @addtogroup Basic @{ @defgroup PriorityDeques Priority Deques This module implements a priority deque adaptor, allowing to push/pop from both ends of the container. @{ //! @brief Efficient double-ended priority queue. template <typename Type, typename Sequence =std::vector<Type>, typename Compare =::std::less<typename Sequence::value_type> > class priority_deque; //! @brief Swaps the elements of two priority deques. template <typename Type, typename Sequence, typename Compare> void swap (priority_deque<Type, Sequence, Compare>& deque1, priority_deque<Type, Sequence, Compare>& deque2); template <typename Type, typename Sequence, typename Compare> class priority_deque { public: //! @details Underlying container type. typedef Sequence container_type; typedef typename container_type::value_type value_type; typedef Compare value_compare; //! @details STL Container specifies that this is an unsigned integral type. typedef typename container_type::size_type size_type; //! @details May be used to examine, but not modify, an element in the deque. typedef typename container_type::const_reference const_reference; typedef typename container_type::reference reference; typedef typename container_type::pointer pointer; typedef pointer const_pointer; //! @details May be used to examine, but not modify, elements in the deque. typedef typename container_type::const_iterator const_iterator; typedef const_iterator iterator; //! @details STL Container specifies that this is a signed integral type. typedef typename container_type::difference_type difference_type; enum Constructed { CONSTRUCTED }; //! @brief Constructs a new priority deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE explicit priority_deque (const Compare& =Compare(), const Sequence& =Sequence()); template <typename InputIterator> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE priority_deque (InputIterator first, InputIterator last, const Compare& =Compare(), const Sequence& =Sequence()); O(1) Creates a new priority deque from an already heapified container NVBIO_FORCEINLINE NVBIO_HOST_DEVICE priority_deque(const Sequence& seq, const bool constructed = false); O(1) Creates a new priority deque from an already heapified container NVBIO_FORCEINLINE NVBIO_HOST_DEVICE priority_deque(const Sequence& seq, const Constructed flag) : sequence_(seq) {} //! @brief Copies an element into the priority deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void push (const value_type&); //! @brief Accesses a maximal element in the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_reference maximum (void) const; //! @brief Accesses a minimal element in the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_reference minimum (void) const; //! @details Identical to std::priority_queue top(). @see @a maximum NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_reference top (void) const { return maximum(); }; //! @details Identical to std::priority_queue top(). @see @a maximum NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_reference bottom (void) const { return bottom(); }; //! @brief Removes a maximal element from the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void pop_top (void); //! @brief Removes a minimal element from the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void pop_bottom (void); //! @details Identical to std::priority_queue pop(). @see @a pop_maximum NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void pop (void) { pop_top(); }; //! @brief Returns true if the priority deque is empty, false if it is not. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE bool empty (void) const {return sequence_.empty();}; //! @brief Returns the number of elements in the priority deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE size_type size (void) const {return sequence_.size(); }; //! @brief Returns the maximum number of elements that can be contained. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE size_type max_size (void) const {return sequence_.max_size();}; //! @brief Removes all elements from the priority deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void clear (void) { sequence_.clear(); }; //! @brief Moves the elements from this deque into another, and vice-versa. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void swap (priority_deque<Type, Sequence,Compare>&); //! @brief Merges a sequence of elements into the priority deque. template <typename InputIterator> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void merge (InputIterator first, InputIterator last); //! @brief Merges a container's elements into the priority deque. template <typename SourceContainer> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void merge (const SourceContainer& source) { merge(source.begin(), source.end()); } //! @brief Returns a const iterator at the beginning of the sequence. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_iterator begin (void) const {return sequence_.begin();}; //! @brief Returns a const iterator past the end of the sequence. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_iterator end (void) const { return sequence_.end(); }; //! @brief Modifies a specified element of the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void update (const_iterator, const value_type&); //! @brief Removes a specified element from the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void erase (const_iterator); // size() has constant complexity static const bool constant_time_size = true; // priority deque does not have ordered iterators static const bool <API key> = false; // priority deque is efficiently mergable static const bool is_mergable = true; // priority deque does not have a stable heap order static const bool is_stable = false; // priority deque does not have a reserve() member static const bool has_reserve = false; protected: NVBIO_FORCEINLINE NVBIO_HOST_DEVICE container_type& sequence (void) { return sequence_; }; NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const container_type& sequence (void) const { return sequence_; }; NVBIO_FORCEINLINE NVBIO_HOST_DEVICE value_compare& compare (void) { return compare_; }; NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const value_compare& compare (void) const { return compare_; }; private: Sequence sequence_; Compare compare_; }; /** @param comp Comparison class. // @param seq Container class. // @post Deque contains copies of all elements from @a sequence. // // @remark Complexity: O(n) */ template <typename T, typename S, typename C> priority_deque<T, S, C>::priority_deque (const C& comp, const S& seq) : sequence_(seq), compare_(comp) { heap::make_interval_heap(sequence_.begin(), sequence_.end(), compare_); } template <typename T, typename S, typename C> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE priority_deque<T, S, C>::priority_deque(const S& seq, const bool constructed) : sequence_(seq) { if (!constructed) heap::make_interval_heap(sequence_.begin(), sequence_.end(), compare_); } /** @param first,last Range of elements. // @param comp Instance of comparison class. // @param seq Instance of container class. // @post Deque contains copies of all elements in @a sequence (if specified) // and in the range [ @a first, @a last). // // @remark Complexity: O(n) */ template <typename T, typename S, typename C> template <typename InputIterator> priority_deque<T, S, C>::priority_deque (InputIterator first,InputIterator last, const C& comp, const S& seq) : sequence_(seq), compare_(comp) { sequence_.insert(sequence_.end(), first, last); heap::make_interval_heap(sequence_.begin(), sequence_.end(), compare_); } /** @param value Element to add the the priority deque. // @post Priority deque contains @a value or a copy of @a value. // @post All iterators and references are invalidated. // // @remark Complexity: O(log n) */ template <typename T, typename Sequence, typename Compare> void priority_deque<T, Sequence, Compare>::push (const value_type& value) { sequence_.push_back(value); heap::push_interval_heap(sequence_.begin(), sequence_.end(), compare_); } /** @return Const reference to a maximal element in the priority deque. // @pre Priority deque contains one or more elements. // @see minimum, pop_maximum // // @remark Complexity: O(1) */ template <typename T, typename Sequence, typename Compare> typename priority_deque<T, Sequence, Compare>::const_reference priority_deque<T, Sequence, Compare>::maximum (void) const { <API key>(!empty(), "Empty priority deque has no maximal element. Reference undefined."); const_iterator it = sequence_.begin() + 1; return (it == sequence_.end()) ? sequence_.front() : *it; } /** @return Const reference to a minimal element in the priority deque. // @pre Priority deque contains one or more elements. // @see maximum, pop_minimum // // @remark Complexity: O(1) */ template <typename T, typename Sequence, typename Compare> typename priority_deque<T, Sequence, Compare>::const_reference priority_deque<T, Sequence, Compare>::minimum (void) const { <API key>(!empty(), "Empty priority deque has no minimal element. Reference undefined."); return sequence_.front(); } /** @pre Priority deque contains one or more elements. // @post A maximal element has been removed from the priority deque. // @post All iterators and references are invalidated. // @see maximum, pop, pop_minimum // // @remark Complexity: O(log n) */ template <typename T, typename Sequence, typename Compare> void priority_deque<T, Sequence, Compare>::pop_bottom (void) { <API key>(!empty(), "Empty priority deque has no maximal element. Removal impossible."); heap::<API key>(sequence_.begin(), sequence_.end(), compare_); sequence_.pop_back(); } /** @pre Priority deque contains one or more elements. // @post A minimal element has been removed from the priority deque. // @post All iterators and references are invalidated. // @see minimum, pop_maximum // // @remark Complexity: O(log n) */ template <typename T, typename Sequence, typename Compare> void priority_deque<T, Sequence, Compare>::pop_top (void) { <API key>(!empty(), "Empty priority deque has no minimal element. Removal undefined."); heap::<API key>(sequence_.begin(), sequence_.end(), compare_); sequence_.pop_back(); } /** @param first,last Input iterators bounding the range [ @a first, @a last) // @post Priority deque contains its original elements, and copies of those in // the range. // @post All iterators and references are invalidated. // // @remark Complexity: O(n) // @remark Exception safety: Basic. */ template <typename T, typename S, typename C> template <typename InputIterator> void priority_deque<T, S, C>::merge (InputIterator first, InputIterator last) { sequence_.insert(sequence_.end(), first, last); heap::make_interval_heap(sequence_.begin(), sequence_.end(), compare_); } /** @param other Priority deque with which to swap. // @post Deque contains the elements from @a source, and @a source contains the // elements from this deque. // @post All iterators and references are invalidated. // @note Sequence containers are required to have swap functions. // @remark Complexity: O(1) */ template <typename T, typename S, typename C> void priority_deque<T, S, C>::swap (priority_deque<T, S, C>& other) { sequence_.swap(other.sequence_); } /** @relates priority_deque // @param deque1,deque2 Priority deques. // @post @a deque1 contains the elements originally in @a deque2, and @a deque2 // contains the elements originally in @a deque1 // @post All iterators and references are invalidated. // // @remark Complexity: O(1) */ template <typename T, typename S, typename C> void swap (priority_deque<T, S, C>& deque1, priority_deque<T, S, C>& deque2) { deque1.swap(deque2); } /** @param random_it A valid iterator in the range [begin, end). // @param value The new value. // @pre Priority deque contains one or more elements. // @post The element at @a random_it is set to @a value. // @post All iterators and references are invalidated. // @see erase // // Elements within the deque may be unordered. // @remark Complexity: O(log n) // @remark Exception safety: Basic. Exceptions won't lose elements, but may // corrupt the heap. */ template <typename T, typename S, typename C> void priority_deque<T, S, C>::update (const_iterator random_it, const value_type& value) { const difference_type index = random_it - begin(); <API key>((0 <= index) && (index < end() - begin()), "Iterator out of bounds; can't set element."); // Providing the strong guarantee would require saving a copy. *(sequence_.begin() + index) = value; heap::<API key>(sequence_.begin(),sequence_.end(),index,compare_); } /** @param random_it An iterator in the range [begin, end) // @pre Priority deque contains one or more elements. // @post The deque no longer contains the element previously at @a random_it. // @post All iterators and references are invalidated. // @see set // @remark Complexity: O(log n) */ template <typename T, typename Sequence, typename Compare> void priority_deque<T, Sequence, Compare>::erase (const_iterator random_it) { const difference_type index = random_it - begin(); <API key>((0 <= index) && (index < end() - begin()), "Iterator out of bounds; can't erase element."); heap::pop_interval_heap(sequence_.begin(), sequence_.end(),index,compare_); sequence_.pop_back(); } @} PriorityDeques @} Basic } // namespace nvbio
<?php /** * @namespace */ namespace Zend\Mail; use Zend\Validator\Hostname as HostnameValidator, Zend\Validator, Zend\Mail\Protocol; abstract class AbstractProtocol { /** * Mail default EOL string */ const EOL = "\r\n"; /** * Default timeout in seconds for initiating session */ const TIMEOUT_CONNECTION = 30; /** * Maximum of the transaction log * @var integer */ protected $_maximumLog = 64; /** * Hostname or IP address of remote server * @var string */ protected $_host; /** * Port number of connection * @var integer */ protected $_port; /** * Instance of Zend\Validator\ValidatorChain to check hostnames * @var \Zend\Validator\ValidatorChain */ protected $_validHost; /** * Socket connection resource * @var resource */ protected $_socket; /** * Last request sent to server * @var string */ protected $_request; /** * Array of server responses to last request * @var array */ protected $_response; /** * String template for parsing server responses using sscanf (default: 3 digit code and response string) * @var resource * @deprecated Since 1.10.3 */ protected $_template = '%d%s'; /** * Log of mail requests and server responses for a session * @var array */ private $_log = array(); /** * Constructor. * * @param string $host OPTIONAL Hostname of remote connection (default: 127.0.0.1) * @param integer $port OPTIONAL Port number (default: null) * @throws \Zend\Mail\Protocol\Exception * @return void */ public function __construct($host = '127.0.0.1', $port = null) { $this->_validHost = new Validator\ValidatorChain(); $this->_validHost->addValidator(new HostnameValidator(HostnameValidator::ALLOW_ALL)); if (!$this->_validHost->isValid($host)) { throw new Protocol\Exception\RuntimeException(implode(', ', $this->_validHost->getMessages())); } $this->_host = $host; $this->_port = $port; } /** * Class destructor to cleanup open resources * * @return void */ public function __destruct() { $this->_disconnect(); } /** * Set the maximum log size * * @param integer $maximumLog Maximum log size * @return void */ public function setMaximumLog($maximumLog) { $this->_maximumLog = (int) $maximumLog; } /** * Get the maximum log size * * @return int the maximum log size */ public function getMaximumLog() { return $this->_maximumLog; } /** * Create a connection to the remote host * * Concrete adapters for this class will implement their own unique connect scripts, using the _connect() method to create the socket resource. */ abstract public function connect(); /** * Retrieve the last client request * * @return string */ public function getRequest() { return $this->_request; } /** * Retrieve the last server response * * @return array */ public function getResponse() { return $this->_response; } /** * Retrieve the transaction log * * @return string */ public function getLog() { return implode('', $this->_log); } /** * Reset the transaction log * * @return void */ public function resetLog() { $this->_log = array(); } /** * Add the transaction log * * @param string new transaction * @return void */ protected function _addLog($value) { if ($this->_maximumLog >= 0 && count($this->_log) >= $this->_maximumLog) { array_shift($this->_log); } $this->_log[] = $value; } /** * Connect to the server using the supplied transport and target * * An example $remote string may be 'tcp://mail.example.com:25' or 'ssh://hostname.com:2222' * * @param string $remote Remote * @throws \Zend\Mail\Protocol\Exception * @return boolean */ protected function _connect($remote) { $errorNum = 0; $errorStr = ''; // open connection $this->_socket = @<API key>($remote, $errorNum, $errorStr, self::TIMEOUT_CONNECTION); if ($this->_socket === false) { if ($errorNum == 0) { $errorStr = 'Could not open socket'; } throw new Protocol\Exception\RuntimeException($errorStr); } if (($result = stream_set_timeout($this->_socket, self::TIMEOUT_CONNECTION)) === false) { throw new Protocol\Exception\RuntimeException('Could not set stream timeout'); } return $result; } /** * Disconnect from remote host and free resource * * @return void */ protected function _disconnect() { if (is_resource($this->_socket)) { fclose($this->_socket); } } /** * Send the given request followed by a LINEEND to the server. * * @param string $request * @throws \Zend\Mail\Protocol\Exception * @return integer|boolean Number of bytes written to remote host */ protected function _send($request) { if (!is_resource($this->_socket)) { throw new Protocol\Exception\RuntimeException('No connection has been established to ' . $this->_host); } $this->_request = $request; $result = fwrite($this->_socket, $request . self::EOL); // Save request to internal log $this->_addLog($request . self::EOL); if ($result === false) { throw new Protocol\Exception\RuntimeException('Could not send request to ' . $this->_host); } return $result; } /** * Get a line from the stream. * * @var integer $timeout Per-request timeout value if applicable * @throws \Zend\Mail\Protocol\Exception * @return string */ protected function _receive($timeout = null) { if (!is_resource($this->_socket)) { throw new Protocol\Exception\RuntimeException('No connection has been established to ' . $this->_host); } // Adapters may wish to supply per-commend timeouts according to appropriate RFC if ($timeout !== null) { stream_set_timeout($this->_socket, $timeout); } // Retrieve response $reponse = fgets($this->_socket, 1024); // Save request to internal log $this->_addLog($reponse); // Check meta data to ensure connection is still valid $info = <API key>($this->_socket); if (!empty($info['timed_out'])) { throw new Protocol\Exception\RuntimeException($this->_host . ' has timed out'); } if ($reponse === false) { throw new Protocol\Exception\RuntimeException('Could not read from ' . $this->_host); } return $reponse; } /** * Parse server response for successful codes * * Read the response from the stream and check for expected return code. * Throws a <API key> if an unexpected code is returned. * * @param string|array $code One or more codes that indicate a successful response * @throws \Zend\Mail\Protocol\Exception * @return string Last line of response string */ protected function _expect($code, $timeout = null) { $this->_response = array(); $cmd = ''; $more = ''; $msg = ''; $errMsg = ''; if (!is_array($code)) { $code = array($code); } do { $this->_response[] = $result = $this->_receive($timeout); list($cmd, $more, $msg) = preg_split('/([\s-]+)/', $result, 2, <API key>); if ($errMsg !== '') { $errMsg .= ' ' . $msg; } elseif ($cmd === null || !in_array($cmd, $code)) { $errMsg = $msg; } } while (strpos($more, '-') === 0); // The '-' message prefix indicates an information string instead of a response string. if ($errMsg !== '') { throw new Protocol\Exception\RuntimeException($errMsg); } return $msg; } }
package com.groupon.mapreduce.mongo.in; import com.groupon.mapreduce.mongo.WritableBSONObject; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import java.io.IOException; import java.util.Iterator; /** * This reads Mongo Records from an Extent and returns Hadoop Records as WritableBSONObjects. The key * returned to the Mapper is the _id field from the Mongo Record as Text. */ public class MongoRecordReader extends RecordReader<Text, WritableBSONObject> { private Record current = null; private Iterator<Record> iterator = null; private FileSystem fs; @Override public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, <API key> { MongoInputSplit mongoInputSplit = (MongoInputSplit) inputSplit; fs = ((MongoInputSplit) inputSplit).getExtent().getPath().getFileSystem(taskAttemptContext.getConfiguration()); iterator = mongoInputSplit.getExtent().iterator(fs); } @Override public boolean nextKeyValue() throws IOException, <API key> { if (!iterator.hasNext()) return false; current = iterator.next(); return true; } @Override public Text getCurrentKey() throws IOException, <API key> { return new Text(current.getId(fs)); } @Override public WritableBSONObject getCurrentValue() throws IOException, <API key> { return new WritableBSONObject(current.getContent(fs)); } @Override public float getProgress() throws IOException, <API key> { if (!iterator.hasNext()) return 1.0f; return 0.0f; } @Override public void close() throws IOException { } }
import numpy as np from Coupling import Coupling class <API key>(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def impedance_to(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)
@font-face { font-family: 'OpenSans'; src: url('<API key>.eot'); src: url('<API key>.eot?#iefix') format('embedded-opentype'), url('<API key>.woff') format('woff'), url('<API key>.ttf') format('truetype'), url('<API key>.svg#OpenSansLight') format('svg'); font-weight: lighter; font-weight: 300; font-style: normal; } @font-face { font-family: 'OpenSans'; src: url('<API key>.eot'); src: url('<API key>.eot?#iefix') format('embedded-opentype'), url('<API key>.woff') format('woff'), url('<API key>.ttf') format('truetype'), url('<API key>.svg#OpenSansLightItalic') format('svg'); font-weight: lighter; font-weight: 300; font-style: italic; } @font-face { font-family: 'OpenSans'; src: url('<API key>.eot'); src: url('<API key>.eot?#iefix') format('embedded-opentype'), url('<API key>.woff') format('woff'), url('<API key>.ttf') format('truetype'), url('<API key>.svg#OpenSansRegular') format('svg'); font-weight: normal; font-weight: 400; font-style: normal; } @font-face { font-family: 'OpenSans'; src: url('<API key>.eot'); src: url('<API key>.eot?#iefix') format('embedded-opentype'), url('<API key>.woff') format('woff'), url('<API key>.ttf') format('truetype'), url('<API key>.svg#OpenSansItalic') format('svg'); font-weight: normal; font-weight: 400; font-style: italic; } @font-face { font-family: 'OpenSans'; src: url('<API key>.eot'); src: url('<API key>.eot?#iefix') format('embedded-opentype'), url('<API key>.woff') format('woff'), url('<API key>.ttf') format('truetype'), url('<API key>.svg#OpenSansSemibold') format('svg'); font-weight: bold; font-weight: 700; font-style: normal; } @font-face { font-family: 'OpenSans'; src: url('<API key>.eot'); src: url('<API key>.eot?#iefix') format('embedded-opentype'), url('<API key>.woff') format('woff'), url('<API key>.ttf') format('truetype'), url('<API key>.svg#<API key>') format('svg'); font-weight: bold; font-weight: 700; font-style: italic; } @font-face { font-family: 'OpenSans'; src: url('<API key>.eot'); src: url('<API key>.eot?#iefix') format('embedded-opentype'), url('<API key>.woff') format('woff'), url('<API key>.ttf') format('truetype'), url('<API key>.svg#OpenSansBold') format('svg'); font-weight: bolder; font-weight: 700; font-style: normal; } @font-face { font-family: 'OpenSans'; src: url('<API key>.eot'); src: url('<API key>.eot?#iefix') format('embedded-opentype'), url('<API key>.woff') format('woff'), url('<API key>.ttf') format('truetype'), url('<API key>.svg#OpenSansBoldItalic') format('svg'); font-weight: bolder; font-weight: 700; font-style: italic; }
#include "Stencil1D.h" int cncMain(int argc, char *argv[]) { CNC_REQUIRE(argc == 4, "Usage: %s NUM_TILES TILE_SIZE NUM_TIMESTEPS\n", argv[0]); // Create a new graph context Stencil1DCtx *context = Stencil1D_create(); // initialize graph context parameters context->numTiles = atoi(argv[1]); context->tileSize = atoi(argv[2]); context->lastTimestep = atoi(argv[3]); // Launch the graph for execution Stencil1D_launch(NULL, context); // Exit when the graph execution completes <API key>(context); return 0; }
#include "ui/base/clipboard/test/test_clipboard.h" #include <stddef.h> #include <memory> #include <utility> #include "base/containers/contains.h" #include "base/memory/ptr_util.h" #include "base/notreached.h" #include "base/numerics/safe_conversions.h" #include "base/strings/<API key>.h" #include "build/build_config.h" #include "build/buildflag.h" #include "build/<API key>.h" #include "build/chromeos_buildflags.h" #include "skia/ext/skia_utils_base.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/clipboard_constants.h" #include "ui/base/clipboard/clipboard_monitor.h" #include "ui/base/clipboard/custom_data_helper.h" #include "ui/base/<API key>/<API key>.h" #include "ui/base/<API key>/<API key>.h" #include "ui/gfx/codec/png_codec.h" namespace ui { namespace { bool IsReadAllowed(const <API key>* src, const <API key>* dst) { auto* policy_controller = <API key>::Get(); if (!policy_controller) return true; return policy_controller-><API key>(src, dst, absl::nullopt); } } // namespace TestClipboard::TestClipboard() : <API key>(ClipboardBuffer::kCopyPaste) {} TestClipboard::~TestClipboard() = default; TestClipboard* TestClipboard::<API key>() { base::AutoLock lock(Clipboard::ClipboardMapLock()); auto* clipboard = new TestClipboard; (*Clipboard::ClipboardMapPtr())[base::PlatformThread::CurrentId()] = base::WrapUnique(clipboard); return clipboard; } void TestClipboard::SetLastModifiedTime(const base::Time& time) { last_modified_time_ = time; } void TestClipboard::OnPreShutdown() {} <API key>* TestClipboard::GetSource(ClipboardBuffer buffer) const { return GetStore(buffer).GetDataSource(); } const <API key>& TestClipboard::GetSequenceNumber( ClipboardBuffer buffer) const { return GetStore(buffer).sequence_number; } bool TestClipboard::IsFormatAvailable( const ClipboardFormatType& format, ClipboardBuffer buffer, const ui::<API key>* data_dst) const { if (!IsReadAllowed(GetStore(buffer).data_src.get(), data_dst)) return false; #if defined(OS_LINUX) || defined(OS_CHROMEOS) // The linux clipboard treats the presence of text on the clipboard // as the url format being available. if (format == ClipboardFormatType::UrlType()) return IsFormatAvailable(ClipboardFormatType::PlainTextType(), buffer, data_dst); #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) const DataStore& store = GetStore(buffer); if (format == ClipboardFormatType::FilenamesType()) return !store.filenames.empty(); // Chrome can retrieve an image from the clipboard as either a bitmap or PNG. if (format == ClipboardFormatType::PngType() || format == ClipboardFormatType::BitmapType()) { return base::Contains(store.data, ClipboardFormatType::PngType()) || base::Contains(store.data, ClipboardFormatType::BitmapType()); } return base::Contains(store.data, format); } void TestClipboard::Clear(ClipboardBuffer buffer) { GetStore(buffer).Clear(); } std::vector<std::u16string> TestClipboard::GetStandardFormats( ClipboardBuffer buffer, const <API key>* data_dst) const { std::vector<std::u16string> types; const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return types; if (IsFormatAvailable(ClipboardFormatType::PlainTextType(), buffer, data_dst)) { types.push_back(base::UTF8ToUTF16(kMimeTypeText)); } if (IsFormatAvailable(ClipboardFormatType::HtmlType(), buffer, data_dst)) types.push_back(base::UTF8ToUTF16(kMimeTypeHTML)); if (IsFormatAvailable(ClipboardFormatType::SvgType(), buffer, data_dst)) types.push_back(base::UTF8ToUTF16(kMimeTypeSvg)); if (IsFormatAvailable(ClipboardFormatType::RtfType(), buffer, data_dst)) types.push_back(base::UTF8ToUTF16(kMimeTypeRTF)); if (IsFormatAvailable(ClipboardFormatType::PngType(), buffer, data_dst) || IsFormatAvailable(ClipboardFormatType::BitmapType(), buffer, data_dst)) types.push_back(base::UTF8ToUTF16(kMimeTypePNG)); if (IsFormatAvailable(ClipboardFormatType::FilenamesType(), buffer, data_dst)) types.push_back(base::UTF8ToUTF16(kMimeTypeURIList)); auto it = store.data.find(ClipboardFormatType::WebCustomDataType()); if (it != store.data.end()) ReadCustomDataTypes(it->second.c_str(), it->second.size(), &types); return types; } void TestClipboard::ReadAvailableTypes( ClipboardBuffer buffer, const <API key>* data_dst, std::vector<std::u16string>* types) const { DCHECK(types); types->clear(); if (!IsReadAllowed(GetStore(buffer).data_src.get(), data_dst)) return; *types = GetStandardFormats(buffer, data_dst); } void TestClipboard::ReadText(ClipboardBuffer buffer, const <API key>* data_dst, std::u16string* result) const { if (!IsReadAllowed(GetStore(buffer).data_src.get(), data_dst)) return; std::string result8; ReadAsciiText(buffer, data_dst, &result8); *result = base::UTF8ToUTF16(result8); } // TODO(crbug.com/1103215): |data_dst| should be supported. void TestClipboard::ReadAsciiText(ClipboardBuffer buffer, const <API key>* data_dst, std::string* result) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; result->clear(); auto it = store.data.find(ClipboardFormatType::PlainTextType()); if (it != store.data.end()) *result = it->second; } void TestClipboard::ReadHTML(ClipboardBuffer buffer, const <API key>* data_dst, std::u16string* markup, std::string* src_url, uint32_t* fragment_start, uint32_t* fragment_end) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; markup->clear(); src_url->clear(); auto it = store.data.find(ClipboardFormatType::HtmlType()); if (it != store.data.end()) *markup = base::UTF8ToUTF16(it->second); *src_url = store.html_src_url; *fragment_start = 0; *fragment_end = base::checked_cast<uint32_t>(markup->size()); } void TestClipboard::ReadSvg(ClipboardBuffer buffer, const <API key>* data_dst, std::u16string* result) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; result->clear(); auto it = store.data.find(ClipboardFormatType::SvgType()); if (it != store.data.end()) *result = base::UTF8ToUTF16(it->second); } void TestClipboard::ReadRTF(ClipboardBuffer buffer, const <API key>* data_dst, std::string* result) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; result->clear(); auto it = store.data.find(ClipboardFormatType::RtfType()); if (it != store.data.end()) *result = it->second; } void TestClipboard::ReadPng(ClipboardBuffer buffer, const <API key>* data_dst, ReadPngCallback callback) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) { std::move(callback).Run(std::vector<uint8_t>()); return; } std::move(callback).Run(store.png); } // TODO(crbug.com/1103215): |data_dst| should be supported. void TestClipboard::ReadCustomData(ClipboardBuffer buffer, const std::u16string& type, const <API key>* data_dst, std::u16string* result) const {} void TestClipboard::ReadFilenames(ClipboardBuffer buffer, const <API key>* data_dst, std::vector<ui::FileInfo>* result) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; *result = store.filenames; } // TODO(crbug.com/1103215): |data_dst| should be supported. void TestClipboard::ReadBookmark(const <API key>* data_dst, std::u16string* title, std::string* url) const { const DataStore& store = GetDefaultStore(); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; if (url) { auto it = store.data.find(ClipboardFormatType::UrlType()); if (it != store.data.end()) *url = it->second; } if (title) *title = base::UTF8ToUTF16(store.url_title); } void TestClipboard::ReadData(const ClipboardFormatType& format, const <API key>* data_dst, std::string* result) const { const DataStore& store = GetDefaultStore(); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; result->clear(); auto it = store.data.find(format); if (it != store.data.end()) *result = it->second; } base::Time TestClipboard::GetLastModifiedTime() const { return last_modified_time_; } void TestClipboard::<API key>() { last_modified_time_ = base::Time(); } #if defined(USE_OZONE) bool TestClipboard::<API key>() const { return true; } #endif // defined(USE_OZONE) void TestClipboard::<API key>( ClipboardBuffer buffer, const ObjectMap& objects, std::vector<Clipboard::<API key>> <API key>, std::unique_ptr<<API key>> data_src) { Clear(buffer); <API key> = buffer; <API key>(std::move(<API key>)); for (const auto& kv : objects) <API key>(kv.first, kv.second); <API key> = ClipboardBuffer::kCopyPaste; GetStore(buffer).SetDataSource(std::move(data_src)); } void TestClipboard::WriteText(const char* text_data, size_t text_len) { std::string text(text_data, text_len); GetDefaultStore().data[ClipboardFormatType::PlainTextType()] = text; #if defined(OS_WIN) // Create a dummy entry. GetDefaultStore().data[ClipboardFormatType::PlainTextAType()]; #endif if (<API key>(ClipboardBuffer::kSelection)) GetStore(ClipboardBuffer::kSelection) .data[ClipboardFormatType::PlainTextType()] = text; ClipboardMonitor::GetInstance()-><API key>(); } void TestClipboard::WriteHTML(const char* markup_data, size_t markup_len, const char* url_data, size_t url_len) { std::u16string markup; base::UTF8ToUTF16(markup_data, markup_len, &markup); GetDefaultStore().data[ClipboardFormatType::HtmlType()] = base::UTF16ToUTF8(markup); GetDefaultStore().html_src_url = std::string(url_data, url_len); } void TestClipboard::WriteSvg(const char* markup_data, size_t markup_len) { std::u16string markup; base::UTF8ToUTF16(markup_data, markup_len, &markup); GetDefaultStore().data[ClipboardFormatType::SvgType()] = base::UTF16ToUTF8(markup); } void TestClipboard::WriteRTF(const char* rtf_data, size_t data_len) { GetDefaultStore().data[ClipboardFormatType::RtfType()] = std::string(rtf_data, data_len); } void TestClipboard::WriteFilenames(std::vector<ui::FileInfo> filenames) { GetDefaultStore().filenames = std::move(filenames); } void TestClipboard::WriteBookmark(const char* title_data, size_t title_len, const char* url_data, size_t url_len) { GetDefaultStore().data[ClipboardFormatType::UrlType()] = std::string(url_data, url_len); #if !defined(OS_WIN) GetDefaultStore().url_title = std::string(title_data, title_len); #endif } void TestClipboard::WriteWebSmartPaste() { // Create a dummy entry. GetDefaultStore().data[ClipboardFormatType::<API key>()]; } void TestClipboard::WriteBitmap(const SkBitmap& bitmap) { // We expect callers to sanitize `bitmap` to be N32 color type, to avoid // out-of-bounds issues due to unexpected bits-per-pixel while copying the // bitmap's pixel buffer. This DCHECK is to help alert us if we've missed // something. DCHECK_EQ(bitmap.colorType(), kN32_SkColorType); // Create a dummy entry. GetDefaultStore().data[ClipboardFormatType::BitmapType()]; gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &GetDefaultStore().png); ClipboardMonitor::GetInstance()-><API key>(); } void TestClipboard::WriteData(const ClipboardFormatType& format, const char* data_data, size_t data_len) { GetDefaultStore().data[format] = std::string(data_data, data_len); } TestClipboard::DataStore::DataStore() = default; TestClipboard::DataStore::DataStore(const DataStore& other) { sequence_number = other.sequence_number; data = other.data; url_title = other.url_title; html_src_url = other.html_src_url; png = other.png; data_src = other.data_src ? std::make_unique<<API key>>( <API key>(*(other.data_src))) : nullptr; } TestClipboard::DataStore& TestClipboard::DataStore::operator=( const DataStore& other) { sequence_number = other.sequence_number; data = other.data; url_title = other.url_title; html_src_url = other.html_src_url; png = other.png; data_src = other.data_src ? std::make_unique<<API key>>( <API key>(*(other.data_src))) : nullptr; return *this; } TestClipboard::DataStore::~DataStore() = default; void TestClipboard::DataStore::Clear() { data.clear(); url_title.clear(); html_src_url.clear(); png.clear(); filenames.clear(); data_src.reset(); } void TestClipboard::DataStore::SetDataSource( std::unique_ptr<<API key>> new_data_src) { data_src = std::move(new_data_src); } <API key>* TestClipboard::DataStore::GetDataSource() const { return data_src.get(); } const TestClipboard::DataStore& TestClipboard::GetStore( ClipboardBuffer buffer) const { CHECK(<API key>(buffer)); return stores_[buffer]; } TestClipboard::DataStore& TestClipboard::GetStore(ClipboardBuffer buffer) { CHECK(<API key>(buffer)); DataStore& store = stores_[buffer]; store.sequence_number = <API key>(); return store; } const TestClipboard::DataStore& TestClipboard::GetDefaultStore() const { return GetStore(<API key>); } TestClipboard::DataStore& TestClipboard::GetDefaultStore() { return GetStore(<API key>); } } // namespace ui
''' The `Filter` hierarchy contains Transformer classes that take a `Stim` of one type as input and return a `Stim` of the same type as output (but with some changes to its data). ''' from .audio import (AudioTrimmingFilter, <API key>) from .base import <API key> from .image import (ImageCroppingFilter, ImageResizingFilter, PillowImageFilter) from .text import (WordStemmingFilter, TokenizingFilter, TokenRemovalFilter, <API key>, LowerCasingFilter) from .video import (FrameSamplingFilter, VideoTrimmingFilter) __all__ = [ 'AudioTrimmingFilter', '<API key>', '<API key>', 'ImageCroppingFilter', 'ImageResizingFilter', 'PillowImageFilter', 'WordStemmingFilter', 'TokenizingFilter', 'TokenRemovalFilter', '<API key>', 'LowerCasingFilter', 'FrameSamplingFilter', 'VideoTrimmingFilter' ]
package ch.epfl.yinyang package transformers import ch.epfl.yinyang._ import ch.epfl.yinyang.transformers._ import scala.reflect.macros.blackbox.Context import language.experimental.macros import scala.collection.mutable import scala.collection.mutable.ArrayBuffer /** * Converts captured variables to holes, which will be passed to the generated * code at runtime as arguments to the apply method. Exposes all holes in the * holeTable, which maps from holeIds to symbolIds. * * Features covered are: * - identifiers -> `hole[T](classTag[T], holeId)` * - fields (TODO) * - no parameter methods (TODO) * - no parameter functions (TODO) */ trait HoleTransformation extends MacroModule with TransformationUtils { def holeMethod: String import c.universe._ /** SymbolIds indexed by holeIds. */ val holeTable = new ArrayBuffer[Int] object HoleTransformer { def apply(toHoles: List[Symbol] = Nil, className: String)(tree: Tree) = { val t = new HoleTransformer(toHoles map symbolId).transform(tree) log("holeTransformed (transforming " + toHoles + "): " + code(t), 2) log("holeTable (holeId -> symbolId): " + holeTable, 2) t } } /** * Transforms all identifiers with symbolIds in `toHoles` to * `hole[T](classTag[T], holeId)` and builds the holeTable mapping from * holeIds to symbolIds. */ class HoleTransformer(toHoles: List[Int]) extends Transformer { override def transform(tree: Tree): Tree = tree match { case i @ Ident(s) if toHoles contains symbolId(i.symbol) => { val index = { val sId = symbolId(i.symbol) if (holeTable.contains(sId)) holeTable.indexOf(sId) else { holeTable += symbolId(i.symbol) holeTable.size - 1 } } Apply( Select(This(typeNames.EMPTY), TermName(holeMethod)), List( TypeApply( Select(This(typeNames.EMPTY), TermName("runtimeType")), List(TypeTree(i.tpe.widen))), Literal(Constant(index)))) } case _ => super.transform(tree) } } }
# Makefile for Sphinx documentation # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean:
<?php /** * @namespace */ namespace Zend\Tool\Project\Provider; class Application extends AbstractProvider implements \Zend\Tool\Framework\Provider\Pretendable { protected $_specialties = array('ClassNamePrefix'); /** * * @param $classNamePrefix Prefix of classes * @param $force */ public function <API key>($classNamePrefix /* , $force = false */) { $profile = $this->_loadProfile(self::<API key>); $<API key> = $classNamePrefix; if (substr($classNamePrefix, -1) != '\\') { $classNamePrefix .= '\\'; } $configFileResource = $profile->search('<API key>'); $zc = $configFileResource->getAsZendConfig('production'); if ($zc->appnamespace == $classNamePrefix) { throw new \Zend\Tool\Project\Exception('The requested name ' . $classNamePrefix . ' is already the prefix.'); } // remove the old $configFileResource->removeStringItem('appnamespace', 'production'); $configFileResource->create(); // add the new $configFileResource->addStringItem('appnamespace', $classNamePrefix, 'production', true); $configFileResource->create(); // update the project profile $<API key> = $profile->search('<API key>'); $<API key>->setClassNamePrefix($classNamePrefix); $response = $this->_registry->getResponse(); if ($<API key> !== $classNamePrefix) { $response->appendContent( 'Note: the name provided "' . $<API key> . '" was' . ' altered to "' . $classNamePrefix . '" for correctness.', array('color' => 'yellow') ); } // note to the user $response->appendContent('Note: All existing models will need to be altered to this new namespace by hand', array('color' => 'yellow')); $response->appendContent('application.ini updated with new appnamespace ' . $classNamePrefix); // store profile $this->_storeProfile(); } }
#include "vp9/common/vp9_convolve.h" #include <assert.h> #include "./vpx_config.h" #include "./vp9_rtcd.h" #include "vp9/common/vp9_common.h" #include "vpx/vpx_integer.h" #include "vpx_ports/mem.h" #define VP9_FILTER_WEIGHT 128 #define VP9_FILTER_SHIFT 7 /* Assume a bank of 16 filters to choose from. There are two implementations * for filter wrapping behavior, since we want to be able to pick which filter * to start with. We could either: * * 1) make filter_ a pointer to the base of the filter array, and then add an * additional offset parameter, to choose the starting filter. * 2) use a pointer to 2 periods worth of filters, so that even if the original * phase offset is at 15/16, we'll have valid data to read. The filter * tables become [32][8], and the second half is duplicated. * 3) fix the alignment of the filter tables, so that we know the 0/16 is * always 256 byte aligned. * * Implementations 2 and 3 are likely preferable, as they avoid an extra 2 * parameters, and switching between them is trivial, with the * ALIGN_FILTERS_256 macro, below. */ #define ALIGN_FILTERS_256 1 static void convolve_horiz_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x0, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_x_base = filter_x0; #if ALIGN_FILTERS_256 filter_x_base = (const int16_t *)(((intptr_t)filter_x0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source line */ src -= taps / 2 - 1; for (y = 0; y < h; ++y) { /* Pointer to filter to use */ const int16_t *filter_x = filter_x0; /* Initial phase offset */ int x0_q4 = (filter_x - filter_x_base) / taps; int x_q4 = x0_q4; for (x = 0; x < w; ++x) { /* Per-pixel src offset */ int src_x = (x_q4 - x0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[src_x + k] * filter_x[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[x] = clip_pixel(sum >> VP9_FILTER_SHIFT); /* Adjust source and filter to use for the next pixel */ x_q4 += x_step_q4; filter_x = filter_x_base + (x_q4 & 0xf) * taps; } src += src_stride; dst += dst_stride; } } static void <API key>(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x0, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_x_base = filter_x0; #if ALIGN_FILTERS_256 filter_x_base = (const int16_t *)(((intptr_t)filter_x0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source line */ src -= taps / 2 - 1; for (y = 0; y < h; ++y) { /* Pointer to filter to use */ const int16_t *filter_x = filter_x0; /* Initial phase offset */ int x0_q4 = (filter_x - filter_x_base) / taps; int x_q4 = x0_q4; for (x = 0; x < w; ++x) { /* Per-pixel src offset */ int src_x = (x_q4 - x0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[src_x + k] * filter_x[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[x] = (dst[x] + clip_pixel(sum >> VP9_FILTER_SHIFT) + 1) >> 1; /* Adjust source and filter to use for the next pixel */ x_q4 += x_step_q4; filter_x = filter_x_base + (x_q4 & 0xf) * taps; } src += src_stride; dst += dst_stride; } } static void convolve_vert_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y0, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_y_base = filter_y0; #if ALIGN_FILTERS_256 filter_y_base = (const int16_t *)(((intptr_t)filter_y0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source column */ src -= src_stride * (taps / 2 - 1); for (x = 0; x < w; ++x) { /* Pointer to filter to use */ const int16_t *filter_y = filter_y0; /* Initial phase offset */ int y0_q4 = (filter_y - filter_y_base) / taps; int y_q4 = y0_q4; for (y = 0; y < h; ++y) { /* Per-pixel src offset */ int src_y = (y_q4 - y0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[(src_y + k) * src_stride] * filter_y[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[y * dst_stride] = clip_pixel(sum >> VP9_FILTER_SHIFT); /* Adjust source and filter to use for the next pixel */ y_q4 += y_step_q4; filter_y = filter_y_base + (y_q4 & 0xf) * taps; } ++src; ++dst; } } static void convolve_avg_vert_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y0, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_y_base = filter_y0; #if ALIGN_FILTERS_256 filter_y_base = (const int16_t *)(((intptr_t)filter_y0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source column */ src -= src_stride * (taps / 2 - 1); for (x = 0; x < w; ++x) { /* Pointer to filter to use */ const int16_t *filter_y = filter_y0; /* Initial phase offset */ int y0_q4 = (filter_y - filter_y_base) / taps; int y_q4 = y0_q4; for (y = 0; y < h; ++y) { /* Per-pixel src offset */ int src_y = (y_q4 - y0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[(src_y + k) * src_stride] * filter_y[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[y * dst_stride] = (dst[y * dst_stride] + clip_pixel(sum >> VP9_FILTER_SHIFT) + 1) >> 1; /* Adjust source and filter to use for the next pixel */ y_q4 += y_step_q4; filter_y = filter_y_base + (y_q4 & 0xf) * taps; } ++src; ++dst; } } static void convolve_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { /* Fixed size intermediate buffer places limits on parameters. * Maximum intermediate_height is 135, for y_step_q4 == 32, * h == 64, taps == 8. */ uint8_t temp[64 * 135]; int intermediate_height = ((h * y_step_q4) >> 4) + taps - 1; assert(w <= 64); assert(h <= 64); assert(taps <= 8); assert(y_step_q4 <= 32); if (intermediate_height < h) intermediate_height = h; convolve_horiz_c(src - src_stride * (taps / 2 - 1), src_stride, temp, 64, filter_x, x_step_q4, filter_y, y_step_q4, w, intermediate_height, taps); convolve_vert_c(temp + 64 * (taps / 2 - 1), 64, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, taps); } static void convolve_avg_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { /* Fixed size intermediate buffer places limits on parameters. * Maximum intermediate_height is 135, for y_step_q4 == 32, * h == 64, taps == 8. */ uint8_t temp[64 * 135]; int intermediate_height = ((h * y_step_q4) >> 4) + taps - 1; assert(w <= 64); assert(h <= 64); assert(taps <= 8); assert(y_step_q4 <= 32); if (intermediate_height < h) intermediate_height = h; convolve_horiz_c(src - src_stride * (taps / 2 - 1), src_stride, temp, 64, filter_x, x_step_q4, filter_y, y_step_q4, w, intermediate_height, taps); convolve_avg_vert_c(temp + 64 * (taps / 2 - 1), 64, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, taps); } void <API key>(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_horiz_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void <API key>(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { <API key>(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void <API key>(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_vert_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void <API key>(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_avg_vert_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_avg_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { /* Fixed size intermediate buffer places limits on parameters. */ <API key>(16, uint8_t, temp, 64 * 64); assert(w <= 64); assert(h <= 64); vp9_convolve8(src, src_stride, temp, 64, filter_x, x_step_q4, filter_y, y_step_q4, w, h); vp9_convolve_avg(temp, 64, dst, dst_stride, NULL, 0, /* These unused parameter should be removed! */ NULL, 0, /* These unused parameter should be removed! */ w, h); } void vp9_convolve_copy(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int filter_x_stride, const int16_t *filter_y, int filter_y_stride, int w, int h) { if (w == 16 && h == 16) { vp9_copy_mem16x16(src, src_stride, dst, dst_stride); } else if (w == 8 && h == 8) { vp9_copy_mem8x8(src, src_stride, dst, dst_stride); } else if (w == 8 && h == 4) { vp9_copy_mem8x4(src, src_stride, dst, dst_stride); } else { int r; for (r = h; r > 0; --r) { memcpy(dst, src, w); src += src_stride; dst += dst_stride; } } } void vp9_convolve_avg(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int filter_x_stride, const int16_t *filter_y, int filter_y_stride, int w, int h) { int x, y; for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { dst[x] = (dst[x] + src[x] + 1) >> 1; } src += src_stride; dst += dst_stride; } }
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='reddit_gold', description='reddit gold', version='0.1', author='Chad Birch', author_email='chad@reddit.com', packages=find_packages(), install_requires=[ 'r2', ], entry_points={ 'r2.plugin': ['gold = reddit_gold:Gold'] }, <API key>=True, zip_safe=False, )
<?php if (!($chan = $this->getChannel($chan_name))) { $bot->noticef($user, "Nobody is on channel %s.", $chan_name); return false; } if (!$chan->isOn($bot->getNumeric())) { $bot->noticef($user, 'I am not on %s.', $chan->getName()); return false; } $reason = assemble($pargs, 2); $users = $this-><API key>($chan_name); foreach ($users as $numeric => $chan_user) { if (!$chan_user->isBot() && $chan_user != $user) { $mask = $chan_user->getHostMask(); $ban = new DB_Ban($chan_reg->getId(), $user->getAccountId(), $mask); $ban->setReason($reason); $chan_reg->addBan($ban); $bot->mode($chan->getName(), "-o+b $numeric $mask"); $bot->kick($chan->getName(), $numeric, $reason); $chan->addBan($mask); } } $chan_reg->save();
# -*- coding: utf-8 -*- from django.contrib import admin from ionyweb.plugin_app.plugin_video.models import Plugin_Video admin.site.register(Plugin_Video)
// FnEncode.h // Character transcoding functions for filenames #ifndef EAIO_FNENCODE_H #define EAIO_FNENCODE_H #ifndef INCLUDED_eabase_H #include <EABase/eabase.h> #endif #include <EAIO/internal/Config.h> #ifndef EAIO_EASTREAM_H #include <EAIO/EAStream.h> // for kLengthNull #endif #ifndef EAIO_PATHSTRING_H #include <EAIO/PathString.h> // for ConvertPathUTF{8,16}ToUTF{8,16} #endif namespace EA { namespace IO { StrlcpyUTF16ToUTF8 Copies a UTF16 string to a UTF8 string, but otherwise acts similar to strlcpy except for the return value. Returns the strlen of the destination string. If destination pointer is NULL, returns the strlen of the would-be string. Specifying a source length of kLengthNull copies from the source string up to the first NULL character. EAIO_API size_t StrlcpyUTF16ToUTF8(char8_t* pDest, size_t nDestLength, const char16_t* pSrc, size_t nSrcLength = kLengthNull); StrlcpyUTF8ToUTF16 Copies a UTF8 string to a UTF16 string, but otherwise acts similar to strlcpy except for the return value. Returns the strlen of the destination string. If destination pointer is NULL, returns the strlen of the would-be string. Specifying a source length of kLengthNull copies from the source string up to the first NULL character. EAIO_API size_t StrlcpyUTF8ToUTF16(char16_t* pDest, size_t nDestLength, const char8_t* pSrc, size_t nSrcLength = kLengthNull); Convenient conversion functions used by EAFileUtil and EAFileNotification <API key> Expands the destination to the desired size and then performs a Strlcpy with UTF8->UTF16 conversion. Returns the number of characters written. EAIO_API uint32_t <API key>(Path::PathString16& dstPath16, const char8_t* pSrcPath8); <API key> Expands the destination to the desired size and then performs a Strlcpy with UTF16->UTF8 conversion. Returns the number of characters written. EAIO_API uint32_t <API key>(Path::PathString8& dstPath8, const char16_t* pSrcPath16); // String comparison, strlen, and strlcpy for this module, since we don't have // access to EACRT. EAIO_API bool StrEq16(const char16_t* str1, const char16_t* str2); EAIO_API size_t EAIOStrlen8(const char8_t* str); EAIO_API size_t EAIOStrlen16(const char16_t* str); EAIO_API size_t EAIOStrlcpy8(char8_t* pDestination, const char8_t* pSource, size_t nDestCapacity); EAIO_API size_t EAIOStrlcpy16(char16_t* pDestination, const char16_t* pSource, size_t nDestCapacity); } // namespace IO } // namespace EA #endif // EAIO_FNENCODE_H
package gov.hhs.fha.nhinc.docquery.nhin.proxy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.any; import gov.hhs.fha.nhinc.aspect.<API key>; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType; import gov.hhs.fha.nhinc.common.nhinccommon.<API key>; import gov.hhs.fha.nhinc.connectmgr.ConnectionManager; import gov.hhs.fha.nhinc.connectmgr.<API key>; import gov.hhs.fha.nhinc.docquery.aspect.<API key>; import gov.hhs.fha.nhinc.docquery.aspect.<API key>; import gov.hhs.fha.nhinc.messaging.client.CONNECTClient; import gov.hhs.fha.nhinc.messaging.service.port.<API key>; import gov.hhs.fha.nhinc.nhinclib.NhincConstants.UDDI_SPEC_VERSION; import ihe.iti.xds_b._2007.<API key>; import java.lang.reflect.Method; import javax.xml.ws.Service; import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Neil Webb */ @RunWith(JMock.class) public class <API key> { Mockery context = new JUnit4Mockery() { { setImposteriser(ClassImposteriser.INSTANCE); } }; final Service mockService = context.mock(Service.class); final <API key> mockPort = context.mock(<API key>.class); @SuppressWarnings("unchecked") private CONNECTClient<<API key>> client = mock(CONNECTClient.class); private <API key> cache = mock(<API key>.class); private AdhocQueryRequest request; private AssertionType assertion; @Test public void <API key>() throws Exception { Class<<API key>> clazz = <API key>.class; Method method = clazz.getMethod("<API key>", AdhocQueryRequest.class, AssertionType.class, <API key>.class); <API key> annotation = method.getAnnotation(<API key>.class); assertNotNull(annotation); assertEquals(<API key>.class, annotation.beforeBuilder()); assertEquals(<API key>.class, annotation.<API key>()); assertEquals("Document Query", annotation.serviceType()); assertEquals("", annotation.version()); } @Test public void testNoMtom() throws Exception { <API key> impl = getImpl(); <API key> target = getTarget("1.1"); impl.<API key>(request, assertion, target); verify(client, never()).enableMtom(); } @Test public void testUsingGuidance() throws Exception { <API key> impl = getImpl(); <API key> target = getTarget("1.1"); impl.<API key>(request, assertion, target); verify(cache).<API key>(any(String.class), any(String.class), any(UDDI_SPEC_VERSION.class)); } /** * @param hcidValue * @return */ private <API key> getTarget(String hcidValue) { <API key> target = new <API key>(); HomeCommunityType hcid = new HomeCommunityType(); hcid.setHomeCommunityId(hcidValue); target.setHomeCommunity(hcid); target.setUseSpecVersion("2.0"); return target; } /** * @return */ private <API key> getImpl() { return new <API key>() { /* * (non-Javadoc) * * @see * gov.hhs.fha.nhinc.docquery.nhin.proxy.<API key>#<API key>( * gov.hhs.fha.nhinc.messaging.service.port.<API key>, * gov.hhs.fha.nhinc.common.nhinccommon.AssertionType, java.lang.String, * gov.hhs.fha.nhinc.common.nhinccommon.<API key>) */ @Override public CONNECTClient<<API key>> <API key>( <API key><<API key>> portDescriptor, AssertionType assertion, String url, <API key> target) { return client; } /* (non-Javadoc) * @see gov.hhs.fha.nhinc.docquery.nhin.proxy.<API key>#getCMInstance() */ @Override protected ConnectionManager getCMInstance() { return cache; } }; } }
#ifndef <API key> #define <API key> #include "chrome/browser/views/tabs/<API key>.h" class <API key> : public <API key> { public: explicit <API key>(gfx::NativeView new_view); // Destroys the photo booth window. virtual ~<API key>(); // Replaces the view in the photo booth with the specified one. virtual void Replace(gfx::NativeView new_view); // Paints the current display image of the window into |canvas|, clipped to // |target_bounds|. virtual void <API key>(gfx::Canvas* canvas, const gfx::Rect& target_bounds); private: <API key>(<API key>); }; #endif // #ifndef <API key>
<?php namespace Zend\Form\Element; use Traversable; use Zend\Form\Element; use Zend\Form\ElementInterface; use Zend\Form\Exception; use Zend\Form\Fieldset; use Zend\Form\FieldsetInterface; use Zend\Form\FormInterface; use Zend\Stdlib\ArrayUtils; class Collection extends Fieldset { /** * Default template placeholder */ const <API key> = '__index__'; /** * Element used in the collection * * @var ElementInterface */ protected $targetElement; /** * Initial count of target element * * @var int */ protected $count = 1; /** * Are new elements allowed to be added dynamically ? * * @var bool */ protected $allowAdd = true; /** * Are existing elements allowed to be removed dynamically ? * * @var bool */ protected $allowRemove = true; /** * Is the template generated ? * * @var bool */ protected $<API key> = false; /** * Placeholder used in template content for making your life easier with JavaScript * * @var string */ protected $templatePlaceholder = self::<API key>; /** * Whether or not to create new objects during modify * * @var bool */ protected $createNewObjects = false; /** * Element used as a template * * @var ElementInterface|FieldsetInterface */ protected $templateElement; /** * The index of the last child element or fieldset * * @var int */ protected $lastChildIndex = -1; protected $<API key> = true; /** * Accepted options for Collection: * - target_element: an array or element used in the collection * - count: number of times the element is added initially * - allow_add: if set to true, elements can be added to the form dynamically (using JavaScript) * - allow_remove: if set to true, elements can be removed to the form * - <API key>: if set to true, a template is generated (inside a <span>) * - <API key>: placeholder used in the data template * * @param array|Traversable $options * @return Collection */ public function setOptions($options) { parent::setOptions($options); if (isset($options['target_element'])) { $this->setTargetElement($options['target_element']); } if (isset($options['count'])) { $this->setCount($options['count']); } if (isset($options['allow_add'])) { $this->setAllowAdd($options['allow_add']); } if (isset($options['allow_remove'])) { $this->setAllowRemove($options['allow_remove']); } if (isset($options['<API key>'])) { $this-><API key>($options['<API key>']); } if (isset($options['<API key>'])) { $this-><API key>($options['<API key>']); } if (isset($options['create_new_objects'])) { $this->setCreateNewObjects($options['create_new_objects']); } return $this; } /** * Checks if the object can be set in this fieldset * * @param object $object * @return bool */ public function allowObjectBinding($object) { return true; } /** * Set the object used by the hydrator * In this case the "object" is a collection of objects * * @param array|Traversable $object * @return Fieldset|FieldsetInterface * @throws Exception\<API key> */ public function setObject($object) { if (!is_array($object) && !$object instanceof Traversable) { throw new Exception\<API key>(sprintf( '%s expects an array or Traversable object argument; received "%s"', __METHOD__, (is_object($object) ? get_class($object) : gettype($object)) )); } $this->object = $object; $this->count = count($object) > $this->count ? count($object) : $this->count; return $this; } /** * Populate values * * @param array|Traversable $data * @throws \Zend\Form\Exception\<API key> * @throws \Zend\Form\Exception\DomainException * @return void */ public function populateValues($data) { if (!is_array($data) && !$data instanceof Traversable) { throw new Exception\<API key>(sprintf( '%s expects an array or Traversable set of data; received "%s"', __METHOD__, (is_object($data) ? get_class($data) : gettype($data)) )); } // Can't do anything with empty data if (empty($data)) { return; } if (!$this->allowRemove && count($data) < $this->count) { throw new Exception\DomainException(sprintf( 'There are fewer elements than specified in the collection (%s). Either set the allow_remove option ' . 'to true, or re-submit the form.', get_class($this) )); } // Check to see if elements have been replaced or removed foreach ($this->byName as $name => $elementOrFieldset) { if (isset($data[$name])) { continue; } if (!$this->allowRemove) { throw new Exception\DomainException(sprintf( 'Elements have been removed from the collection (%s) but the allow_remove option is not true.', get_class($this) )); } $this->remove($name); } foreach ($data as $key => $value) { if ($this->has($key)) { $elementOrFieldset = $this->get($key); } else { $elementOrFieldset = $this-><API key>($key); if ($key > $this->lastChildIndex) { $this->lastChildIndex = $key; } } if ($elementOrFieldset instanceof FieldsetInterface) { $elementOrFieldset->populateValues($value); } else { $elementOrFieldset->setAttribute('value', $value); } } if (!$this->createNewObjects()) { $this-><API key>(); } } /** * Checks if this fieldset can bind data * * @return bool */ public function allowValueBinding() { return true; } /** * Bind values to the object * * @param array $values * @return array|mixed|void */ public function bindValues(array $values = array()) { $collection = array(); foreach ($values as $name => $value) { $element = $this->get($name); if ($element instanceof FieldsetInterface) { $collection[] = $element->bindValues($value); } else { $collection[] = $value; } } return $collection; } /** * Set the initial count of target element * * @param $count * @return Collection */ public function setCount($count) { $this->count = $count > 0 ? $count : 0; return $this; } /** * Get the initial count of target element * * @return int */ public function getCount() { return $this->count; } /** * Set the target element * * @param ElementInterface|array|Traversable $elementOrFieldset * @return Collection * @throws \Zend\Form\Exception\<API key> */ public function setTargetElement($elementOrFieldset) { if (is_array($elementOrFieldset) || ($elementOrFieldset instanceof Traversable && !$elementOrFieldset instanceof ElementInterface) ) { $factory = $this->getFormFactory(); $elementOrFieldset = $factory->create($elementOrFieldset); } if (!$elementOrFieldset instanceof ElementInterface) { throw new Exception\<API key>(sprintf( '%s requires that $elementOrFieldset be an object implementing %s; received "%s"', __METHOD__, __NAMESPACE__ . '\ElementInterface', (is_object($elementOrFieldset) ? get_class($elementOrFieldset) : gettype($elementOrFieldset)) )); } $this->targetElement = $elementOrFieldset; return $this; } /** * Get target element * * @return ElementInterface|null */ public function getTargetElement() { return $this->targetElement; } /** * Get allow add * * @param bool $allowAdd * @return Collection */ public function setAllowAdd($allowAdd) { $this->allowAdd = (bool) $allowAdd; return $this; } /** * Get allow add * * @return bool */ public function allowAdd() { return $this->allowAdd; } /** * @param bool $allowRemove * @return Collection */ public function setAllowRemove($allowRemove) { $this->allowRemove = (bool) $allowRemove; return $this; } /** * @return bool */ public function allowRemove() { return $this->allowRemove; } /** * If set to true, a template prototype is automatically added to the form to ease the creation of dynamic elements through JavaScript * * @param bool $<API key> * @return Collection */ public function <API key>($<API key>) { $this-><API key> = (bool) $<API key>; return $this; } /** * Get if the collection should create a template * * @return bool */ public function <API key>() { return $this-><API key>; } /** * Set the placeholder used in the template generated to help create new elements in JavaScript * * @param string $templatePlaceholder * @return Collection */ public function <API key>($templatePlaceholder) { if (is_string($templatePlaceholder)) { $this->templatePlaceholder = $templatePlaceholder; } return $this; } /** * Get the template placeholder * * @return string */ public function <API key>() { return $this->templatePlaceholder; } /** * @param bool $createNewObjects * @return Collection */ public function setCreateNewObjects($createNewObjects) { $this->createNewObjects = (bool) $createNewObjects; return $this; } /** * @return bool */ public function createNewObjects() { return $this->createNewObjects; } /** * Get a template element used for rendering purposes only * * @return null|ElementInterface|FieldsetInterface */ public function getTemplateElement() { if ($this->templateElement === null) { $this->templateElement = $this-><API key>(); } return $this->templateElement; } /** * Prepare the collection by adding a dummy template element if the user want one * * @param FormInterface $form * @return mixed|void */ public function prepareElement(FormInterface $form) { if (true === $this-><API key>) { if ($this->targetElement !== null && $this->count > 0) { while ($this->count > $this->lastChildIndex + 1) { $this-><API key>(++$this->lastChildIndex); } } } // Create a template that will also be prepared if ($this-><API key>) { $templateElement = $this->getTemplateElement(); $this->add($templateElement); } parent::prepareElement($form); // The template element has been prepared, but we don't want it to be rendered nor validated, so remove it from the list if ($this-><API key>) { $this->remove($this->templatePlaceholder); } } /** * @return array * @throws \Zend\Form\Exception\<API key> * @throws \Zend\Stdlib\Exception\<API key> * @throws \Zend\Form\Exception\DomainException * @throws \Zend\Form\Exception\<API key> */ public function extract() { if ($this->object instanceof Traversable) { $this->object = ArrayUtils::iteratorToArray($this->object, false); } if (!is_array($this->object)) { return array(); } $values = array(); foreach ($this->object as $key => $value) { // If a hydrator is provided, our work here is done if ($this->hydrator) { $values[$key] = $this->hydrator->extract($value); continue; } // If the target element is a fieldset that can accept the provided value // we should clone it, inject the value and extract the data if ( $this->targetElement instanceof FieldsetInterface ) { if ( ! $this->targetElement->allowObjectBinding($value) ) { continue; } $targetElement = clone $this->targetElement; $targetElement->setObject($value); $values[$key] = $targetElement->extract(); if (!$this->createNewObjects() && $this->has($key)) { $this->get($key)->setObject($value); } continue; } // If the target element is a non-fieldset element, just use the value if ( $this->targetElement instanceof ElementInterface ) { $values[$key] = $value; if (!$this->createNewObjects() && $this->has($key)) { $this->get($key)->setValue($value); } continue; } } return $values; } /** * Create a new instance of the target element * * @return ElementInterface */ protected function <API key>() { return clone $this->targetElement; } /** * Add a new instance of the target element * * @param string $name * @return ElementInterface * @throws Exception\DomainException */ protected function <API key>($name) { $this-><API key> = false; $elementOrFieldset = $this-><API key>(); $elementOrFieldset->setName($name); $this->add($elementOrFieldset); if (!$this->allowAdd && $this->count() > $this->count) { throw new Exception\DomainException(sprintf( 'There are more elements than specified in the collection (%s). Either set the allow_add option ' . 'to true, or re-submit the form.', get_class($this) )); } return $elementOrFieldset; } /** * Create a dummy template element * * @return null|ElementInterface|FieldsetInterface */ protected function <API key>() { if (!$this-><API key>) { return null; } if ($this->templateElement) { return $this->templateElement; } $elementOrFieldset = $this-><API key>(); $elementOrFieldset->setName($this->templatePlaceholder); return $elementOrFieldset; } /** * Replaces the default template object of a sub element with the corresponding * real entity so that all properties are preserved. * * @return void */ protected function <API key>() { $fieldsets = $this->getFieldsets(); if (!count($fieldsets) || !$this->object) { return; } foreach ($fieldsets as $fieldset) { $i = $fieldset->getName(); if (isset($this->object[$i])) { $fieldset->setObject($this->object[$i]); } } } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.h Label Definition File: <API key>.label.xml Template File: sources-sinks-83.tmpl.h */ /* * @description * CWE: 415 Double Free * BadSource: Allocate data using new and Deallocae data using delete * GoodSource: Allocate data using new * Sinks: * GoodSink: do nothing * BadSink : Deallocate data using delete * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #include "std_testcase.h" #include <wchar.h> namespace <API key> { #ifndef OMITBAD class <API key> { public: <API key>(wchar_t * dataCopy); ~<API key>(); private: wchar_t * data; }; #endif /* OMITBAD */ #ifndef OMITGOOD class <API key> { public: <API key>(wchar_t * dataCopy); ~<API key>(); private: wchar_t * data; }; class <API key> { public: <API key>(wchar_t * dataCopy); ~<API key>(); private: wchar_t * data; }; #endif /* OMITGOOD */ }
*> \brief <b> ZCPOSV computes the solution to system of linear equations A * X = B for PO matrices</b> * * =========== DOCUMENTATION =========== * * Online html documentation available at * http: * *> \htmlonly *> Download ZCPOSV + dependencies *> <a href="http: *> [TGZ]</a> *> <a href="http: *> [ZIP]</a> *> <a href="http: *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE ZCPOSV( UPLO, N, NRHS, A, LDA, B, LDB, X, LDX, WORK, * SWORK, RWORK, ITER, INFO ) * * .. Scalar Arguments .. * CHARACTER UPLO * INTEGER INFO, ITER, LDA, LDB, LDX, N, NRHS * .. * .. Array Arguments .. * DOUBLE PRECISION RWORK( * ) * COMPLEX SWORK( * ) * COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( N, * ), * $ X( LDX, * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> ZCPOSV computes the solution to a complex system of linear equations *> A * X = B, *> where A is an N-by-N Hermitian positive definite matrix and X and B *> are N-by-NRHS matrices. *> *> ZCPOSV first attempts to factorize the matrix in COMPLEX and use this *> factorization within an iterative refinement procedure to produce a *> solution with COMPLEX*16 normwise backward error quality (see below). *> If the approach fails the method switches to a COMPLEX*16 *> factorization and solve. *> *> The iterative refinement is not going to be a winning strategy if *> the ratio COMPLEX performance over COMPLEX*16 performance is too *> small. A reasonable strategy should take the number of right-hand *> sides and the size of the matrix into account. This might be done *> with a call to ILAENV in the future. Up to now, we always try *> iterative refinement. *> *> The iterative refinement process is stopped if *> ITER > ITERMAX *> or for all the RHS we have: *> RNRM < SQRT(N)*XNRM*ANRM*EPS*BWDMAX *> where *> o ITER is the number of the current iteration in the iterative *> refinement process *> o RNRM is the infinity-norm of the residual *> o XNRM is the infinity-norm of the solution *> o ANRM is the <API key> of the matrix A *> o EPS is the machine epsilon returned by DLAMCH('Epsilon') *> The value ITERMAX and BWDMAX are fixed to 30 and 1.0D+00 *> respectively. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> = 'U': Upper triangle of A is stored; *> = 'L': Lower triangle of A is stored. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of linear equations, i.e., the order of the *> matrix A. N >= 0. *> \endverbatim *> *> \param[in] NRHS *> \verbatim *> NRHS is INTEGER *> The number of right hand sides, i.e., the number of columns *> of the matrix B. NRHS >= 0. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is COMPLEX*16 array, *> dimension (LDA,N) *> On entry, the Hermitian matrix A. If UPLO = 'U', the leading *> N-by-N upper triangular part of A contains the upper *> triangular part of the matrix A, and the strictly lower *> triangular part of A is not referenced. If UPLO = 'L', the *> leading N-by-N lower triangular part of A contains the lower *> triangular part of the matrix A, and the strictly upper *> triangular part of A is not referenced. *> *> Note that the imaginary parts of the diagonal *> elements need not be set and are assumed to be zero. *> *> On exit, if iterative refinement has been successfully used *> (INFO = 0 and ITER >= 0, see description below), then A is *> unchanged, if double precision factorization has been used *> (INFO = 0 and ITER < 0, see description below), then the *> array A contains the factor U or L from the Cholesky *> factorization A = U**H*U or A = L*L**H. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> The leading dimension of the array A. LDA >= max(1,N). *> \endverbatim *> *> \param[in] B *> \verbatim *> B is COMPLEX*16 array, dimension (LDB,NRHS) *> The N-by-NRHS right hand side matrix B. *> \endverbatim *> *> \param[in] LDB *> \verbatim *> LDB is INTEGER *> The leading dimension of the array B. LDB >= max(1,N). *> \endverbatim *> *> \param[out] X *> \verbatim *> X is COMPLEX*16 array, dimension (LDX,NRHS) *> If INFO = 0, the N-by-NRHS solution matrix X. *> \endverbatim *> *> \param[in] LDX *> \verbatim *> LDX is INTEGER *> The leading dimension of the array X. LDX >= max(1,N). *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is COMPLEX*16 array, dimension (N,NRHS) *> This array is used to hold the residual vectors. *> \endverbatim *> *> \param[out] SWORK *> \verbatim *> SWORK is COMPLEX array, dimension (N*(N+NRHS)) *> This array is used to use the single precision matrix and the *> right-hand sides or solutions in single precision. *> \endverbatim *> *> \param[out] RWORK *> \verbatim *> RWORK is DOUBLE PRECISION array, dimension (N) *> \endverbatim *> *> \param[out] ITER *> \verbatim *> ITER is INTEGER *> < 0: iterative refinement has failed, COMPLEX*16 *> factorization has been performed *> -1 : the routine fell back to full precision for *> implementation- or machine-specific reasons *> -2 : narrowing the precision induced an overflow, *> the routine fell back to full precision *> -3 : failure of CPOTRF *> -31: stop the iterative refinement after the 30th *> iterations *> > 0: iterative refinement has been successfully used. *> Returns the number of iterations *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -i, the i-th argument had an illegal value *> > 0: if INFO = i, the leading minor of order i of *> (COMPLEX*16) A is not positive definite, so the *> factorization could not be completed, and the solution *> has not been computed. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date June 2016 * *> \ingroup complex16POsolve * * ===================================================================== SUBROUTINE ZCPOSV( UPLO, N, NRHS, A, LDA, B, LDB, X, LDX, WORK, $ SWORK, RWORK, ITER, INFO ) * * -- LAPACK driver routine (version 3.8.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * June 2016 * * .. Scalar Arguments .. CHARACTER UPLO INTEGER INFO, ITER, LDA, LDB, LDX, N, NRHS * .. * .. Array Arguments .. DOUBLE PRECISION RWORK( * ) COMPLEX SWORK( * ) COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( N, * ), $ X( LDX, * ) * .. * * ===================================================================== * * .. Parameters .. LOGICAL DOITREF PARAMETER ( DOITREF = .TRUE. ) * INTEGER ITERMAX PARAMETER ( ITERMAX = 30 ) * DOUBLE PRECISION BWDMAX PARAMETER ( BWDMAX = 1.0E+00 ) * COMPLEX*16 NEGONE, ONE PARAMETER ( NEGONE = ( -1.0D+00, 0.0D+00 ), $ ONE = ( 1.0D+00, 0.0D+00 ) ) * * .. Local Scalars .. INTEGER I, IITER, PTSA, PTSX DOUBLE PRECISION ANRM, CTE, EPS, RNRM, XNRM COMPLEX*16 ZDUM * * .. External Subroutines .. EXTERNAL ZAXPY, ZHEMM, ZLACPY, ZLAT2C, ZLAG2C, CLAG2Z, $ CPOTRF, CPOTRS, XERBLA, ZPOTRF, ZPOTRS * .. * .. External Functions .. INTEGER IZAMAX DOUBLE PRECISION DLAMCH, ZLANHE LOGICAL LSAME EXTERNAL IZAMAX, DLAMCH, ZLANHE, LSAME * .. * .. Intrinsic Functions .. INTRINSIC ABS, DBLE, MAX, SQRT * .. Statement Functions .. DOUBLE PRECISION CABS1 * .. * .. Statement Function definitions .. CABS1( ZDUM ) = ABS( DBLE( ZDUM ) ) + ABS( DIMAG( ZDUM ) ) * .. * .. Executable Statements .. * INFO = 0 ITER = 0 * * Test the input parameters. * IF( .NOT.LSAME( UPLO, 'U' ) .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN INFO = -1 ELSE IF( N.LT.0 ) THEN INFO = -2 ELSE IF( NRHS.LT.0 ) THEN INFO = -3 ELSE IF( LDA.LT.MAX( 1, N ) ) THEN INFO = -5 ELSE IF( LDB.LT.MAX( 1, N ) ) THEN INFO = -7 ELSE IF( LDX.LT.MAX( 1, N ) ) THEN INFO = -9 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'ZCPOSV', -INFO ) RETURN END IF * * Quick return if (N.EQ.0). * IF( N.EQ.0 ) $ RETURN * * Skip single precision iterative refinement if a priori slower * than double precision factorization. * IF( .NOT.DOITREF ) THEN ITER = -1 GO TO 40 END IF * * Compute some constants. * ANRM = ZLANHE( 'I', UPLO, N, A, LDA, RWORK ) EPS = DLAMCH( 'Epsilon' ) CTE = ANRM*EPS*SQRT( DBLE( N ) )*BWDMAX * * Set the indices PTSA, PTSX for referencing SA and SX in SWORK. * PTSA = 1 PTSX = PTSA + N*N * * Convert B from double precision to single precision and store the * result in SX. * CALL ZLAG2C( N, NRHS, B, LDB, SWORK( PTSX ), N, INFO ) * IF( INFO.NE.0 ) THEN ITER = -2 GO TO 40 END IF * * Convert A from double precision to single precision and store the * result in SA. * CALL ZLAT2C( UPLO, N, A, LDA, SWORK( PTSA ), N, INFO ) * IF( INFO.NE.0 ) THEN ITER = -2 GO TO 40 END IF * * Compute the Cholesky factorization of SA. * CALL CPOTRF( UPLO, N, SWORK( PTSA ), N, INFO ) * IF( INFO.NE.0 ) THEN ITER = -3 GO TO 40 END IF * * Solve the system SA*SX = SB. * CALL CPOTRS( UPLO, N, NRHS, SWORK( PTSA ), N, SWORK( PTSX ), N, $ INFO ) * * Convert SX back to COMPLEX*16 * CALL CLAG2Z( N, NRHS, SWORK( PTSX ), N, X, LDX, INFO ) * * Compute R = B - AX (R is WORK). * CALL ZLACPY( 'All', N, NRHS, B, LDB, WORK, N ) * CALL ZHEMM( 'Left', UPLO, N, NRHS, NEGONE, A, LDA, X, LDX, ONE, $ WORK, N ) * * Check whether the NRHS normwise backward errors satisfy the * stopping criterion. If yes, set ITER=0 and return. * DO I = 1, NRHS XNRM = CABS1( X( IZAMAX( N, X( 1, I ), 1 ), I ) ) RNRM = CABS1( WORK( IZAMAX( N, WORK( 1, I ), 1 ), I ) ) IF( RNRM.GT.XNRM*CTE ) $ GO TO 10 END DO * * If we are here, the NRHS normwise backward errors satisfy the * stopping criterion. We are good to exit. * ITER = 0 RETURN * 10 CONTINUE * DO 30 IITER = 1, ITERMAX * * Convert R (in WORK) from double precision to single precision * and store the result in SX. * CALL ZLAG2C( N, NRHS, WORK, N, SWORK( PTSX ), N, INFO ) * IF( INFO.NE.0 ) THEN ITER = -2 GO TO 40 END IF * * Solve the system SA*SX = SR. * CALL CPOTRS( UPLO, N, NRHS, SWORK( PTSA ), N, SWORK( PTSX ), N, $ INFO ) * * Convert SX back to double precision and update the current * iterate. * CALL CLAG2Z( N, NRHS, SWORK( PTSX ), N, WORK, N, INFO ) * DO I = 1, NRHS CALL ZAXPY( N, ONE, WORK( 1, I ), 1, X( 1, I ), 1 ) END DO * * Compute R = B - AX (R is WORK). * CALL ZLACPY( 'All', N, NRHS, B, LDB, WORK, N ) * CALL ZHEMM( 'L', UPLO, N, NRHS, NEGONE, A, LDA, X, LDX, ONE, $ WORK, N ) * * Check whether the NRHS normwise backward errors satisfy the * stopping criterion. If yes, set ITER=IITER>0 and return. * DO I = 1, NRHS XNRM = CABS1( X( IZAMAX( N, X( 1, I ), 1 ), I ) ) RNRM = CABS1( WORK( IZAMAX( N, WORK( 1, I ), 1 ), I ) ) IF( RNRM.GT.XNRM*CTE ) $ GO TO 20 END DO * * If we are here, the NRHS normwise backward errors satisfy the * stopping criterion, we are good to exit. * ITER = IITER * RETURN * 20 CONTINUE * 30 CONTINUE * * If we are at this place of the code, this is because we have * performed ITER=ITERMAX iterations and never satisfied the * stopping criterion, set up the ITER flag accordingly and follow * up on double precision routine. * ITER = -ITERMAX - 1 * 40 CONTINUE * * Single-precision iterative refinement failed to converge to a * satisfactory solution, so we resort to double precision. * CALL ZPOTRF( UPLO, N, A, LDA, INFO ) * IF( INFO.NE.0 ) $ RETURN * CALL ZLACPY( 'All', N, NRHS, B, LDB, X, LDX ) CALL ZPOTRS( UPLO, N, NRHS, A, LDA, X, LDX, INFO ) * RETURN * * End of ZCPOSV. * END
/* The <sys/stat.h> header defines a struct that is used in the stat() and * fstat functions. The information in this struct comes from the i-node of * some file. These calls are the only approved way to inspect i-nodes. */ #ifndef _STAT_H #define _STAT_H struct stat { dev_t st_dev; /* major/minor device number */ ino_t st_ino; /* i-node number */ mode_t st_mode; /* file mode, protection bits, etc. */ short int st_nlink; /* # links; TEMPORARY HACK: should be nlink_t*/ uid_t st_uid; /* uid of the file's owner */ short int st_gid; /* gid; TEMPORARY HACK: should be gid_t */ dev_t st_rdev; off_t st_size; /* file size */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last data modification */ time_t st_ctime; /* time of last file status change */ }; /* Traditional mask definitions for st_mode. */ /* The ugly casts on only some of the definitions are to avoid suprising sign * extensions such as S_IFREG != (mode_t) S_IFREG when ints are 32 bits. */ #define S_IFMT ((mode_t) 0170000) /* type of file */ #define S_IFREG ((mode_t) 0100000) /* regular */ #define S_IFBLK 0060000 /* block special */ #define S_IFDIR 0040000 /* directory */ #define S_IFCHR 0020000 /* character special */ #define S_IFIFO 0010000 /* this is a FIFO */ #define S_ISUID 0004000 /* set user id on execution */ #define S_ISGID 0002000 /* set group id on execution */ /* next is reserved for future use */ #define S_ISVTX 01000 /* save swapped text even after use */ /* POSIX masks for st_mode. */ #define S_IRWXU 00700 #define S_IRUSR 00400 #define S_IWUSR 00200 #define S_IXUSR 00100 #define S_IRWXG 00070 #define S_IRGRP 00040 #define S_IWGRP 00020 #define S_IXGRP 00010 #define S_IRWXO 00007 #define S_IROTH 00004 #define S_IWOTH 00002 #define S_IXOTH 00001 /* The following macros test st_mode (from POSIX Sec. 5.6.1.1). */ #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) /* is a reg file */ #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) /* is a directory */ #define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR) /* is a char spec */ #define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK) /* is a block spec */ #define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO) /* is a pipe/FIFO */ /* Function Prototypes. */ #ifndef _ANSI_H #include <ansi.h> #endif _PROTOTYPE( int chmod, (const char *_path, Mode_t _mode) ); _PROTOTYPE( int fstat, (int _fildes, struct stat *_buf) ); _PROTOTYPE( int mkdir, (const char *_path, int _mode) ); _PROTOTYPE( int mkfifo, (const char *_path, int _mode) ); _PROTOTYPE( int stat , (const char *_path, struct stat *_buf) ); _PROTOTYPE( mode_t umask, (int _cmask) ); #endif /* _STAT_H */
using System; namespace CoAP { <summary> Represents an event when a response arrives for a request. </summary> public class ResponseEventArgs : EventArgs { private Response _response; <summary> </summary> public ResponseEventArgs(Response response) { _response = response; } <summary> Gets the incoming response. </summary> public Response Response { get { return _response; } } } }
#ifndef <API key> #define <API key> #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/threading/<API key>.h" #include "base/timer/timer.h" #include "cc/blink/<API key>.h" #include "mojo/services/html_viewer/blink_resource_map.h" #include "mojo/services/html_viewer/<API key>.h" #include "mojo/services/html_viewer/webthemeengine_impl.h" #include "third_party/WebKit/public/platform/Platform.h" #include "third_party/WebKit/public/platform/<API key>.h" namespace html_viewer { class BlinkPlatformImpl : public blink::Platform { public: explicit BlinkPlatformImpl(); virtual ~BlinkPlatformImpl(); // blink::Platform methods: virtual blink::WebMimeRegistry* mimeRegistry(); virtual blink::WebThemeEngine* themeEngine(); virtual blink::WebString defaultLocale(); virtual double currentTime(); virtual double <API key>(); virtual void <API key>( unsigned char* buffer, size_t length); virtual void <API key>(void (*func)()); virtual void <API key>(double interval_seconds); virtual void stopSharedTimer(); virtual void callOnMainThread(void (*func)(void*), void* context); virtual bool <API key>(); virtual blink::<API key>* compositorSupport(); virtual blink::WebURLLoader* createURLLoader(); virtual blink::WebSocketHandle* <API key>(); virtual blink::WebString userAgent(); virtual blink::WebData parseDataURL( const blink::WebURL& url, blink::WebString& mime_type, blink::WebString& charset); virtual blink::WebURLError cancelledError(const blink::WebURL& url) const; virtual blink::WebThread* createThread(const char* name); virtual blink::WebThread* currentThread(); virtual void yieldCurrentThread(); virtual blink::WebWaitableEvent* createWaitableEvent(); virtual blink::WebWaitableEvent* waitMultipleEvents( const blink::WebVector<blink::WebWaitableEvent*>& events); virtual blink::<API key>* scrollbarBehavior(); virtual const unsigned char* <API key>( const char* category_name); virtual blink::WebData loadResource(const char* name); private: void SuspendSharedTimer(); void ResumeSharedTimer(); void DoTimeout() { if (shared_timer_func_ && !<API key>) shared_timer_func_(); } static void <API key>(void*); base::MessageLoop* main_loop_; base::OneShotTimer<BlinkPlatformImpl> shared_timer_; void (*shared_timer_func_)(); double <API key>; bool <API key>; int <API key>; // counter base::ThreadLocalStorage::Slot <API key>; cc_blink::<API key> compositor_support_; WebThemeEngineImpl theme_engine_; WebMimeRegistryImpl mime_registry_; blink::<API key> scrollbar_behavior_; BlinkResourceMap blink_resource_map_; <API key>(BlinkPlatformImpl); }; } // namespace html_viewer #endif // <API key>
// This file contains the definition of DrawElement. #include "core/cross/precompile.h" #include "core/cross/draw_element.h" #include "core/cross/renderer.h" #include "core/cross/error.h" namespace o3d { O3D_DEFN_CLASS(DrawElement, ParamObject); const char* DrawElement::kMaterialParamName = O3D_STRING_CONSTANT("material"); ObjectBase::Ref DrawElement::Create(ServiceLocator* service_locator) { Renderer* renderer = service_locator->GetService<Renderer>(); if (NULL == renderer) { O3D_ERROR(service_locator) << "No Render Device Available"; return ObjectBase::Ref(); } return ObjectBase::Ref(renderer->CreateDrawElement()); } DrawElement::DrawElement(ServiceLocator* service_locator) : ParamObject(service_locator), owner_(NULL) { RegisterParamRef(kMaterialParamName, &material_param_ref_); } DrawElement::~DrawElement() { } void DrawElement::SetOwner(Element* new_owner) { // Hold a ref to ourselves so we make sure we don't get deleted while // as we remove ourself from our current owner. DrawElement::Ref temp(this); if (owner_ != NULL) { bool removed = owner_->RemoveDrawElement(this); DLOG_ASSERT(removed); } owner_ = new_owner; if (new_owner) { new_owner->AddDrawElement(this); } } } // namespace o3d
#include "content/browser/download/<API key>.h" #include <map> #include <queue> #include <utility> #include "base/bind.h" #include "base/files/file.h" #include "base/guid.h" #include "base/macros.h" #include "base/scoped_observer.h" #include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "content/browser/bad_message.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/<API key>.h" #include "content/common/frame_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/<API key>.h" #include "content/public/browser/web_contents.h" #include "content/public/common/<API key>.h" #include "net/base/mime_util.h" namespace content { // The class and all of its members live on the UI thread. Only static methods // are executed on other threads. class <API key>::Job : public <API key> { public: Job(int job_id, WebContents* web_contents, const <API key>& params, const <API key>& callback); ~Job() override; int id() const { return job_id_; } void set_browser_file(base::File file) { browser_file_ = std::move(file); } const <API key>& callback() const { return callback_; } // Indicates whether we expect a message from the |sender| at this time. // We expect only one message per frame - therefore calling this method // will always clear |<API key>|. bool <API key>(RenderFrameHostImpl* sender); // Handler for <API key> (a notification from the // renderer that the MHTML generation for previous frame has finished). // Returns |true| upon success; |false| otherwise. bool <API key>( const std::set<std::string>& <API key>); // Sends IPC to the renderer, asking for MHTML generation of the next frame. // Returns true if the message was sent successfully; false otherwise. bool <API key>(); // Indicates if more calls to <API key> are needed. bool IsDone() const { bool <API key> = <API key> != FrameTreeNode::<API key>; bool <API key> = <API key>.empty(); return !<API key> && <API key>; } // Close the file on the file thread and respond back on the UI thread with // file size. void CloseFile(base::Callback<void(int64_t file_size)> callback); // <API key>: void RenderProcessExited(RenderProcessHost* host, base::TerminationStatus status, int exit_code) override; void <API key>(RenderProcessHost* host) override; void MarkAsFinished(); private: static int64_t <API key>(base::File file); void AddFrame(RenderFrameHost* render_frame_host); // Creates a new map with values (content ids) the same as in // |<API key>| map, but with the keys translated from // frame_tree_node_id into a |site_instance|-specific routing_id. std::map<int, std::string> <API key>( SiteInstance* site_instance); // Id used to map renderer responses to jobs. // See also <API key>::id_to_job_ map. int job_id_; // User-configurable parameters. Includes the file location, binary encoding // choices, and whether to skip storing resources marked // Cache-Control: no-store. <API key> params_; // The IDs of frames that still need to be processed. std::queue<int> <API key>; // Identifies a frame to which we've sent <API key> but for // which we didn't yet process <API key> via // <API key>. int <API key>; // The handle to the file the MHTML is saved to for the browser process. base::File browser_file_; // Map from frames to content ids (see WebFrameSerializer::generateMHTMLParts // for more details about what "content ids" are and how they are used). std::map<int, std::string> <API key>; // MIME multipart boundary to use in the MHTML doc. std::string <API key>; // Digests of URIs of already generated MHTML parts. std::set<std::string> <API key>; std::string salt_; // The callback to call once generation is complete. const <API key> callback_; // Whether the job is finished (set to true only for the short duration of // time between <API key>::JobFinished is called and the job is // destroyed by <API key>::OnFileClosed). bool is_finished_; // RAII helper for registering this Job as a RenderProcessHost observer. ScopedObserver<RenderProcessHost, <API key>::Job> <API key>; <API key>(Job); }; <API key>::Job::Job(int job_id, WebContents* web_contents, const <API key>& params, const <API key>& callback) : job_id_(job_id), params_(params), <API key>(FrameTreeNode::<API key>), <API key>(net::<API key>()), salt_(base::GenerateGUID()), callback_(callback), is_finished_(false), <API key>(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); web_contents->ForEachFrame(base::Bind( &<API key>::Job::AddFrame, base::Unretained(this))); // Safe because ForEachFrame is synchronous. // Main frame needs to be processed first. DCHECK(!<API key>.empty()); DCHECK(FrameTreeNode::GloballyFindByID(<API key>.front()) ->parent() == nullptr); } <API key>::Job::~Job() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } std::map<int, std::string> <API key>::Job::<API key>( SiteInstance* site_instance) { std::map<int, std::string> result; for (const auto& it : <API key>) { int ftn_id = it.first; const std::string& content_id = it.second; FrameTreeNode* ftn = FrameTreeNode::GloballyFindByID(ftn_id); if (!ftn) continue; int routing_id = ftn->render_manager()-><API key>(site_instance); if (routing_id == MSG_ROUTING_NONE) continue; result[routing_id] = content_id; } return result; } bool <API key>::Job::<API key>() { DCHECK(browser_file_.IsValid()); DCHECK(!<API key>.empty()); <API key> ipc_params; ipc_params.job_id = job_id_; ipc_params.<API key> = <API key>; ipc_params.<API key> = params_.use_binary_encoding; ipc_params.<API key> = params_.<API key>; int frame_tree_node_id = <API key>.front(); <API key>.pop(); ipc_params.is_last_frame = <API key>.empty(); FrameTreeNode* ftn = FrameTreeNode::GloballyFindByID(frame_tree_node_id); if (!ftn) // The contents went away. return false; RenderFrameHost* rfh = ftn->current_frame_host(); // Get notified if the target of the IPC message dies between responding. <API key>.RemoveAll(); <API key>.Add(rfh->GetProcess()); // Tell the renderer to skip (= deduplicate) already covered MHTML parts. ipc_params.salt = salt_; ipc_params.<API key> = <API key>; ipc_params.destination_file = IPC::<API key>( browser_file_.GetPlatformFile(), false); // |close_source_handle|. ipc_params.<API key> = <API key>(rfh->GetSiteInstance()); // Send the IPC asking the renderer to serialize the frame. DCHECK_EQ(FrameTreeNode::<API key>, <API key>); <API key> = frame_tree_node_id; rfh->Send(new <API key>(rfh->GetRoutingID(), ipc_params)); return true; } void <API key>::Job::RenderProcessExited( RenderProcessHost* host, base::TerminationStatus status, int exit_code) { DCHECK_CURRENTLY_ON(BrowserThread::UI); <API key>::GetInstance()->RenderProcessExited(this); } void <API key>::Job::MarkAsFinished() { DCHECK(!is_finished_); is_finished_ = true; // Stopping RenderProcessExited notifications is needed to avoid calling <API key>.RemoveAll(); } void <API key>::Job::AddFrame(RenderFrameHost* render_frame_host) { auto* rfhi = static_cast<RenderFrameHostImpl*>(render_frame_host); int frame_tree_node_id = rfhi->frame_tree_node()->frame_tree_node_id(); <API key>.push(frame_tree_node_id); std::string guid = base::GenerateGUID(); std::string content_id = base::StringPrintf("<frame-%d-%s@mhtml.blink>", frame_tree_node_id, guid.c_str()); <API key>[frame_tree_node_id] = content_id; } void <API key>::Job::<API key>( RenderProcessHost* host) { DCHECK_CURRENTLY_ON(BrowserThread::UI); <API key>.Remove(host); } void <API key>::Job::CloseFile( base::Callback<void(int64_t)> callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!browser_file_.IsValid()) { callback.Run(-1); return; } BrowserThread::<API key>( BrowserThread::FILE, FROM_HERE, base::Bind(&<API key>::Job::<API key>, base::Passed(std::move(browser_file_))), callback); } bool <API key>::Job::<API key>( RenderFrameHostImpl* sender) { int sender_id = sender->frame_tree_node()->frame_tree_node_id(); if (sender_id != <API key>) return false; // We only expect one message per frame - let's make sure subsequent messages // from the same |sender| will be rejected. <API key> = FrameTreeNode::<API key>; return true; } bool <API key>::Job::<API key>( const std::set<std::string>& <API key>) { // Renderer should be deduping resources with the same uris. DCHECK_EQ(0u, base::STLSetIntersection<std::set<std::string>>( <API key>, <API key>).size()); <API key>.insert( <API key>.begin(), <API key>.end()); if (<API key>.empty()) return true; // Report success - all frames have been processed. return <API key>(); } // static int64_t <API key>::Job::<API key>(base::File file) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); DCHECK(file.IsValid()); int64_t file_size = file.GetLength(); file.Close(); return file_size; } <API key>* <API key>::GetInstance() { return base::Singleton<<API key>>::get(); } <API key>::<API key>() : next_job_id_(0) {} <API key>::~<API key>() { STLDeleteValues(&id_to_job_); } void <API key>::SaveMHTML(WebContents* web_contents, const <API key>& params, const <API key>& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); int job_id = NewJob(web_contents, params, callback); BrowserThread::<API key>( BrowserThread::FILE, FROM_HERE, base::Bind(&<API key>::CreateFile, params.file_path), base::Bind(&<API key>::OnFileAvailable, base::Unretained(this), // Safe b/c |this| is a singleton. job_id)); } void <API key>::<API key>( RenderFrameHostImpl* sender, int job_id, bool <API key>, const std::set<std::string>& <API key>) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Job* job = FindJob(job_id); if (!job || !job-><API key>(sender)) { NOTREACHED(); ReceivedBadMessage(sender->GetProcess(), bad_message::<API key>); return; } if (!<API key>) { JobFinished(job, JobStatus::FAILURE); return; } if (!job-><API key>( <API key>)) { JobFinished(job, JobStatus::FAILURE); return; } if (job->IsDone()) JobFinished(job, JobStatus::SUCCESS); } // static base::File <API key>::CreateFile(const base::FilePath& file_path) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); // SECURITY NOTE: A file descriptor to the file created below will be passed // to multiple renderer processes which (in out-of-process iframes mode) can // act on behalf of separate web principals. Therefore it is important to // only allow writing to the file and forbid reading from the file (as this // would allow reading content generated by other renderers / other web // principals). uint32_t file_flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; base::File browser_file(file_path, file_flags); if (!browser_file.IsValid()) { LOG(ERROR) << "Failed to create file to save MHTML at: " << file_path.value(); } return browser_file; } void <API key>::OnFileAvailable(int job_id, base::File browser_file) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Job* job = FindJob(job_id); DCHECK(job); if (!browser_file.IsValid()) { LOG(ERROR) << "Failed to create file"; JobFinished(job, JobStatus::FAILURE); return; } job->set_browser_file(std::move(browser_file)); if (!job-><API key>()) { JobFinished(job, JobStatus::FAILURE); } } void <API key>::JobFinished(Job* job, JobStatus job_status) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(job); job->MarkAsFinished(); job->CloseFile( base::Bind(&<API key>::OnFileClosed, base::Unretained(this), // Safe b/c |this| is a singleton. job->id(), job_status)); } void <API key>::OnFileClosed(int job_id, JobStatus job_status, int64_t file_size) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Job* job = FindJob(job_id); job->callback().Run(job_status == JobStatus::SUCCESS ? file_size : -1); id_to_job_.erase(job_id); delete job; } int <API key>::NewJob(WebContents* web_contents, const <API key>& params, const <API key>& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); int job_id = next_job_id_++; id_to_job_[job_id] = new Job(job_id, web_contents, params, callback); return job_id; } <API key>::Job* <API key>::FindJob(int job_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); IDToJobMap::iterator iter = id_to_job_.find(job_id); if (iter == id_to_job_.end()) { NOTREACHED(); return nullptr; } return iter->second; } void <API key>::RenderProcessExited(Job* job) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(job); JobFinished(job, JobStatus::FAILURE); } } // namespace content
package com.skcraft.plume.event.block; import com.google.common.base.Functions; import com.google.common.base.Predicate; import com.skcraft.plume.event.BulkEvent; import com.skcraft.plume.event.Cause; import com.skcraft.plume.event.DelegateEvent; import com.skcraft.plume.event.Result; import com.skcraft.plume.util.Location3i; import net.minecraft.world.World; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; abstract class BlockEvent extends DelegateEvent implements BulkEvent { private final World world; protected BlockEvent(Cause cause, World world) { super(cause); checkNotNull(world, "world"); this.world = world; } /** * Get the world. * * @return The world */ public World getWorld() { return world; } /** * Get a list of affected locations. * * @return A list of affected locations */ public abstract List<Location3i> getLocations(); /** * Filter the list of affected blocks with the given predicate. If the * predicate returns {@code false}, then the block is removed. * * @param predicate the predicate * @param cancelEventOnFalse true to cancel the event and clear the block * list once the predicate returns {@code false} * @return Whether one or more blocks were filtered out */ public boolean filterLocations(Predicate<Location3i> predicate, boolean cancelEventOnFalse) { return filter(getLocations(), Functions.<Location3i>identity(), predicate, cancelEventOnFalse); } @Override public Result getResult() { if (getLocations().isEmpty()) { return Result.DENY; } return super.getResult(); } @Override public Result getExplicitResult() { return super.getResult(); } }
class Blog < ActiveRecord::Base has_many :posts has_many :comments, :through => :posts attr_accessible :name, :subdomain searchable :include => { :posts => :author } do string :subdomain text :name end # Make sure that includes are added to with multiple searchable calls searchable(:include => :comments) {} end
<!doctype html> <html> <title>shrinkwrap</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../static/style.css"> <body> <div id="wrapper"> <h1><a href="../doc/shrinkwrap.html">shrinkwrap</a></h1> <p>Lock down dependency versions</p> <h2 id="SYNOPSIS">SYNOPSIS</h2> <pre><code>npm shrinkwrap</code></pre> <h2 id="DESCRIPTION">DESCRIPTION</h2> <p>This command locks down the versions of a package&#39;s dependencies so that you can control exactly which versions of each dependency will be used when your package is installed.</p> <p>By default, &quot;npm install&quot; recursively installs the target&#39;s dependencies (as specified in package.json), choosing the latest available version that satisfies the dependency&#39;s semver pattern. In some situations, particularly when shipping software where each change is tightly managed, it&#39;s desirable to fully specify each version of each dependency recursively so that subsequent builds and deploys do not inadvertently pick up newer versions of a dependency that satisfy the semver pattern. Specifying specific semver patterns in each dependency&#39;s package.json would facilitate this, but that&#39;s not always possible or desirable, as when another author owns the npm package. It&#39;s also possible to check dependencies directly into source control, but that may be undesirable for other reasons.</p> <p>As an example, consider package A:</p> <pre><code>{ &quot;name&quot;: &quot;A&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;dependencies&quot;: { &quot;B&quot;: &quot;&lt;0.1.0&quot; } }</code></pre> <p>package B:</p> <pre><code>{ &quot;name&quot;: &quot;B&quot;, &quot;version&quot;: &quot;0.0.1&quot;, &quot;dependencies&quot;: { &quot;C&quot;: &quot;&lt;0.1.0&quot; } }</code></pre> <p>and package C:</p> <pre><code>{ &quot;name&quot;: &quot;C, &quot;version&quot;: &quot;0.0.1&quot; }</code></pre> <p>If these are the only versions of A, B, and C available in the registry, then a normal &quot;npm install A&quot; will install:</p> <pre><code>A@0.1.0 `-- B@0.0.1 `-- C@0.0.1</code></pre> <p>However, if B@0.0.2 is published, then a fresh &quot;npm install A&quot; will install:</p> <pre><code>A@0.1.0 `-- B@0.0.2 `-- C@0.0.1</code></pre> <p>assuming the new version did not modify B&#39;s dependencies. Of course, the new version of B could include a new version of C and any number of new dependencies. If such changes are undesirable, the author of A could specify a dependency on B@0.0.1. However, if A&#39;s author and B&#39;s author are not the same person, there&#39;s no way for A&#39;s author to say that he or she does not want to pull in newly published versions of C when B hasn&#39;t changed at all.</p> <p>In this case, A&#39;s author can run</p> <pre><code>npm shrinkwrap</code></pre> <p>This generates npm-shrinkwrap.json, which will look something like this:</p> <pre><code>{ &quot;name&quot;: &quot;A&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;dependencies&quot;: { &quot;B&quot;: { &quot;version&quot;: &quot;0.0.1&quot;, &quot;dependencies&quot;: { &quot;C&quot;: { &quot;version&quot;: &quot;0.1.0&quot; } } } } }</code></pre> <p>The shrinkwrap command has locked down the dependencies based on what&#39;s currently installed in node_modules. When &quot;npm install&quot; installs a package with a npm-shrinkwrap.json file in the package root, the shrinkwrap file (rather than package.json files) completely drives the installation of that package and all of its dependencies (recursively). So now the author publishes A@0.1.0, and subsequent installs of this package will use B@0.0.1 and C@0.1.0, regardless the dependencies and versions listed in A&#39;s, B&#39;s, and C&#39;s package.json files.</p> <h3 id="<API key>">Using shrinkwrapped packages</h3> <p>Using a shrinkwrapped package is no different than using any other package: you can &quot;npm install&quot; it by hand, or add a dependency to your package.json file and &quot;npm install&quot; it.</p> <h3 id="<API key>">Building shrinkwrapped packages</h3> <p>To shrinkwrap an existing package:</p> <ol><li>Run &quot;npm install&quot; in the package root to install the current versions of all dependencies.</li><li>Validate that the package works as expected with these versions.</li><li>Run &quot;npm shrinkwrap&quot;, add npm-shrinkwrap.json to git, and publish your package.</li></ol> <p>To add or update a dependency in a shrinkwrapped package:</p> <ol><li>Run &quot;npm install&quot; in the package root to install the current versions of all dependencies.</li><li>Add or update dependencies. &quot;npm install&quot; each new or updated package individually and then update package.json. Note that they must be explicitly named in order to be installed: running <code>npm install</code> with no arguments will merely reproduce the existing shrinkwrap.</li><li>Validate that the package works as expected with the new dependencies.</li><li>Run &quot;npm shrinkwrap&quot;, commit the new npm-shrinkwrap.json, and publish your package.</li></ol> <p>You can use <a href="../doc/outdated.html">outdated(1)</a> to view dependencies with newer versions available.</p> <h3 id="Other-Notes">Other Notes</h3> <p>Since &quot;npm shrinkwrap&quot; uses the locally installed packages to construct the shrinkwrap file, devDependencies will be included if and only if you&#39;ve installed them already when you make the shrinkwrap.</p> <p>A shrinkwrap file must be consistent with the package&#39;s package.json file. &quot;npm shrinkwrap&quot; will fail if required dependencies are not already installed, since that would result in a shrinkwrap that wouldn&#39;t actually work. Similarly, the command will fail if there are extraneous packages (not referenced by package.json), since that would indicate that package.json is not correct.</p> <p>If shrinkwrapped package A depends on shrinkwrapped package B, B&#39;s shrinkwrap will not be used as part of the installation of A. However, because A&#39;s shrinkwrap is constructed from a valid installation of B and recursively specifies all dependencies, the contents of B&#39;s shrinkwrap will implicitly be included in A&#39;s shrinkwrap.</p> <h3 id="Caveats">Caveats</h3> <p>Shrinkwrap files only lock down package versions, not actual package contents. While discouraged, a package author can republish an existing version of a package, causing shrinkwrapped packages using that version to pick up different code than they were before. If you want to avoid any risk that a byzantine author replaces a package you&#39;re using with code that breaks your application, you could modify the shrinkwrap file to use git URL references rather than version numbers so that npm always fetches all packages from git.</p> <p>If you wish to lock down the specific bytes included in a package, for example to have 100% confidence in being able to reproduce a deployment or build, then you ought to check your dependencies into source control, or pursue some other mechanism that can verify contents rather than versions.</p> <h2 id="SEE-ALSO">SEE ALSO</h2> <ul><li><a href="../doc/install.html">install(1)</a></li><li><a href="../doc/json.html">json(1)</a></li><li><a href="../doc/list.html">list(1)</a></li></ul> </div> <p id="footer">shrinkwrap &mdash; npm@1.2.14</p> <script> ;(function () { var wrapper = document.getElementById("wrapper") var els = Array.prototype.slice.call(wrapper.<API key>("*"), 0) .filter(function (el) { return el.parentNode === wrapper && el.tagName.match(/H[1-6]/) && el.id }) var l = 2 , toc = document.createElement("ul") toc.innerHTML = els.map(function (el) { var i = el.tagName.charAt(1) , out = "" while (i > l) { out += "<ul>" l ++ } while (i < l) { out += "</ul>" l } out += "<li><a href='#" + el.id + "'>" + ( el.innerText || el.text || el.innerHTML) + "</a>" return out }).join("\n") toc.id = "toc" document.body.appendChild(toc) })() </script> </body></html>
from __future__ import unicode_literals __all__ = ( 'Key', 'Keys', ) class Key(object): def __init__(self, name): #: Descriptive way of writing keys in configuration files. e.g. <C-A> #: for ``Control-A``. self.name = name def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.name) class Keys(object): Escape = Key('<Escape>') ControlA = Key('<C-A>') ControlB = Key('<C-B>') ControlC = Key('<C-C>') ControlD = Key('<C-D>') ControlE = Key('<C-E>') ControlF = Key('<C-F>') ControlG = Key('<C-G>') ControlH = Key('<C-H>') ControlI = Key('<C-I>') # Tab ControlJ = Key('<C-J>') # Enter ControlK = Key('<C-K>') ControlL = Key('<C-L>') ControlM = Key('<C-M>') # Enter ControlN = Key('<C-N>') ControlO = Key('<C-O>') ControlP = Key('<C-P>') ControlQ = Key('<C-Q>') ControlR = Key('<C-R>') ControlS = Key('<C-S>') ControlT = Key('<C-T>') ControlU = Key('<C-U>') ControlV = Key('<C-V>') ControlW = Key('<C-W>') ControlX = Key('<C-X>') ControlY = Key('<C-Y>') ControlZ = Key('<C-Z>') ControlSpace = Key('<C-Space>') ControlBackslash = Key('<C-Backslash>') ControlSquareClose = Key('<C-SquareClose>') ControlCircumflex = Key('<C-Circumflex>') ControlUnderscore = Key('<C-Underscore>') ControlLeft = Key('<C-Left>') ControlRight = Key('<C-Right>') ControlUp = Key('<C-Up>') ControlDown = Key('<C-Down>') Up = Key('<Up>') Down = Key('<Down>') Right = Key('<Right>') Left = Key('<Left>') Home = Key('<Home>') End = Key('<End>') Delete = Key('<Delete>') ShiftDelete = Key('<ShiftDelete>') PageUp = Key('<PageUp>') PageDown = Key('<PageDown>') BackTab = Key('<BackTab>') # shift + tab Tab = ControlI Backspace = ControlH F1 = Key('<F1>') F2 = Key('<F2>') F3 = Key('<F3>') F4 = Key('<F4>') F5 = Key('<F5>') F6 = Key('<F6>') F7 = Key('<F7>') F8 = Key('<F8>') F9 = Key('<F9>') F10 = Key('<F10>') F11 = Key('<F11>') F12 = Key('<F12>') F13 = Key('<F13>') F14 = Key('<F14>') F15 = Key('<F15>') F16 = Key('<F16>') F17 = Key('<F17>') F18 = Key('<F18>') F19 = Key('<F19>') F20 = Key('<F20>') # Matches any key. Any = Key('<Any>') # Special CPRResponse = Key('<<API key>>')
package org.hisp.dhis.expression; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.hisp.dhis.analytics.DataType; import org.hisp.dhis.common.DimensionalItemId; import org.hisp.dhis.common.<API key>; import org.hisp.dhis.constant.Constant; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.indicator.Indicator; import org.hisp.dhis.indicator.IndicatorValue; import org.hisp.dhis.organisationunit.<API key>; import org.hisp.dhis.period.Period; /** * Expressions are mathematical formulas and can contain references to various * elements. * * @author Margrethe Store * @author Lars Helge Overland * @author Jim Grace */ public interface ExpressionService { String ID = ExpressionService.class.getName(); String DAYS_DESCRIPTION = "[Number of days]"; String SYMBOL_DAYS = "[days]"; String SYMBOL_WILDCARD = "*"; String UID_EXPRESSION = "[a-zA-Z]\\w{10}"; String INT_EXPRESSION = "^(0|-?[1-9]\\d*)$"; // Expression CRUD operations /** * Adds a new Expression to the database. * * @param expression The Expression to add. * @return The generated identifier for this Expression. */ long addExpression( Expression expression ); /** * Updates an Expression. * * @param expression The Expression to update. */ void updateExpression( Expression expression ); /** * Deletes an Expression from the database. * * @param expression the expression. */ void deleteExpression( Expression expression ); /** * Get the Expression with the given identifier. * * @param id The identifier. * @return an Expression with the given identifier. */ Expression getExpression( long id ); /** * Gets all Expressions. * * @return A list with all Expressions. */ List<Expression> getAllExpressions(); // Indicator expression logic /** * Returns all dimensional item objects which are present in numerator and * denominator of the given indicators, as a map from id to object. * * @param indicators the collection of indicators. * @return a map from dimensional item id to object. */ Map<DimensionalItemId, <API key>> <API key>( Collection<Indicator> indicators ); /** * Returns all <API key> in the numerator and denominator * expressions in the given Indicators. Returns an empty set if the given * indicators are null or empty. * * @param indicators the set of indicators. * @return a Set of <API key>. */ List<<API key>> <API key>( Collection<Indicator> indicators ); /** * Generates the calculated value for the given parameters based on the * values in the given maps. * * @param indicator the indicator for which to calculate the value. * @param periods a List of periods for which to calculate the value. * @param itemMap map of dimensional item id to object in expression. * @param valueMap the map of data values. * @param orgUnitCountMap the map of organisation unit group member counts. * @return the calculated value as a double. */ IndicatorValue <API key>( Indicator indicator, List<Period> periods, Map<DimensionalItemId, <API key>> itemMap, Map<<API key>, Object> valueMap, Map<String, Integer> orgUnitCountMap ); /** * Substitutes any constants and org unit group member counts in the * numerator and denominator on all indicators in the given collection. * * @param indicators the set of indicators. */ void <API key>( Collection<Indicator> indicators ); // Get information about the expression /** * Tests whether the expression is valid. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return the <API key> of the validation. */ <API key> expressionIsValid( String expression, ParseType parseType ); /** * Creates an expression description containing the names of the * <API key> from a numeric valued expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return An description containing <API key> names. */ String <API key>( String expression, ParseType parseType ); /** * Creates an expression description containing the names of the * <API key> from an expression string, for an expression that * will return the specified data type. * * @param expression the expression string. * @param parseType the type of expression to parse. * @param dataType the data type for the expression to return. * @return An description containing <API key> names. */ String <API key>( String expression, ParseType parseType, DataType dataType ); /** * Gets information we need from an expression string. * * @param params the expression parameters. * @return the expression information. */ ExpressionInfo getExpressionInfo( ExpressionParams params ); /** * From expression info, create a "base" expression parameters object with * certain metadata fields supplied that are needed for later evaluation. * <p> * Before evaluation, the caller will need to add to this "base" object * fields such as expression, parseType, dataType, valueMap, etc. * * @param info the expression information. * @return the expression parameters with metadata pre-filled. */ ExpressionParams <API key>( ExpressionInfo info ); /** * Returns UIDs of Data Elements and associated Option Combos (if any) found * in the Data Element Operands an expression. * <p/> * If the Data Element Operand consists of just a Data Element, or if the * Option Combo is a wildcard "*", returns just dataElementUID. * <p/> * If an Option Combo is present, returns dataElementUID.optionComboUID. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of data element identifiers. */ Set<String> <API key>( String expression, ParseType parseType ); /** * Returns all data elements found in the given expression string, including * those found in data element operands. Returns an empty set if the given * expression is null. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of data elements included in the expression string. */ Set<DataElement> <API key>( String expression, ParseType parseType ); /** * Returns all CategoryOptionCombo uids in the given expression string that * are used as a data element operand categoryOptionCombo or * <API key>. Returns an empty set if the expression is null. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of CategoryOptionCombo uids in the expression string. */ Set<String> <API key>( String expression, ParseType parseType ); /** * Returns all dimensional item object ids in the given expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of dimensional item object ids. */ Set<DimensionalItemId> <API key>( String expression, ParseType parseType ); /** * Returns set of all <API key> UIDs in the given expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return Map of UIDs to <API key> in the expression string. */ Set<String> <API key>( String expression, ParseType parseType ); // Compute the value of the expression /** * Generates the calculated value for an expression. * * @param params the expression parameters. * @return the calculated value. */ Object getExpressionValue( ExpressionParams params ); // Gets a (possibly cached) constant map /** * Gets the (possibly cached) constant map. * * @return the constant map. */ Map<String, Constant> getConstantMap(); }
{% extends "email/_notification.html" %} {% set replied_comment = notification.comment.parent_comment %} {% set replied_content = notification.comment.parent_comment.reply_content %} {% block headline %} <span><strong>Your thread</strong> received a <strong>reply</strong> from {% endblock %} {% block email_type %}thread reply notifications{% endblock %}
#include "<API key>.h" #include "<API key>.h" #include "../<API key>/<API key>.h" #include "../SettingsWidgets/<API key>.h" #include "mitkDataNode.h" #include "<API key>.h" #include <QTimer> #include <QSignalMapper> #include <QShortcut> <API key>::<API key>(QWidget* parent) : QWidget(parent), m_SettingsWidget(0), m_BaseNode(mitk::DataNode::New()), m_CurrentTabIndex(0), m_CurrentMaxStep(0), <API key>(false), m_ReadySignalMapper(new QSignalMapper(this)), <API key>(new QSignalMapper(this)), m_StdMultiWidget(0), <API key>(false), ui(new Ui::<API key>) { m_Parent = parent; ui->setupUi(this); // remove the default page ui->stepsToolBox->removeItem(0); //set shortcuts QShortcut *nextShortcut = new QShortcut(QKeySequence("F10"), parent); QShortcut *prevShortcut = new QShortcut(QKeySequence("F11"), parent); connect(nextShortcut, SIGNAL(activated()), this, SLOT(OnNextButtonClicked())); connect(prevShortcut, SIGNAL(activated()), this, SLOT(<API key>())); //connect other slots connect( ui->restartStepButton, SIGNAL(clicked()), this, SLOT(<API key>()) ); connect( ui->previousButton, SIGNAL(clicked()), this, SLOT(<API key>()) ); connect( ui->nextButton, SIGNAL(clicked()), this, SLOT(OnNextButtonClicked()) ); connect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); connect (ui->settingsButton, SIGNAL(clicked()), this, SLOT(<API key>()) ); connect( m_ReadySignalMapper, SIGNAL(mapped(int)), this, SLOT(OnStepReady(int)) ); connect( <API key>, SIGNAL(mapped(int)), this, SLOT(OnStepNoLongerReady(int)) ); ui->settingsFrameWidget->setHidden(true); } <API key>::~<API key>() { ui->stepsToolBox->blockSignals(true); for ( <API key>::iterator it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it ) { if ( (*it)-><API key>() > <API key>::State_Stopped ) { (*it)->StopStep(); } delete *it; } m_NavigationSteps.clear(); if ( m_SettingsNode.IsNotNull() && m_DataStorage.IsNotNull() ) { m_DataStorage->Remove(m_SettingsNode); } delete ui; } void <API key>::EnableInteraction(bool enable) { if (enable) { ui->restartStepButton->setEnabled(true); ui->previousButton->setEnabled(true); ui->nextButton->setEnabled(true); ui->stepsToolBox->setEnabled(true); } else { ui->restartStepButton->setEnabled(false); ui->previousButton->setEnabled(false); ui->nextButton->setEnabled(false); ui->stepsToolBox->setEnabled(false); } } void <API key>::SetDataStorage(itk::SmartPointer<mitk::DataStorage> dataStorage) { m_DataStorage = dataStorage; if ( dataStorage.IsNull() ) { mitkThrow() << "Data Storage must not be null for <API key>."; } // test if base node is already in the data storage and add it if not m_BaseNode = dataStorage->GetNamedNode(<API key>::DATANAME_BASENODE); if ( m_BaseNode.IsNull() ) { m_BaseNode = mitk::DataNode::New(); m_BaseNode->SetName(<API key>::DATANAME_BASENODE); dataStorage->Add(m_BaseNode); } // base node and image stream node may be the same node if ( strcmp(<API key>::DATANAME_BASENODE, <API key>::<API key>) != 0) { m_ImageStreamNode = dataStorage->GetNamedNode(<API key>::<API key>); if (m_ImageStreamNode.IsNull()) { // Create Node for US Stream m_ImageStreamNode = mitk::DataNode::New(); m_ImageStreamNode->SetName(<API key>::<API key>); dataStorage->Add(m_ImageStreamNode); } } else { m_ImageStreamNode = m_BaseNode; } m_SettingsNode = dataStorage->GetNamedDerivedNode(<API key>::DATANAME_SETTINGS, m_BaseNode); if ( m_SettingsNode.IsNull() ) { m_SettingsNode = mitk::DataNode::New(); m_SettingsNode->SetName(<API key>::DATANAME_SETTINGS); dataStorage->Add(m_SettingsNode, m_BaseNode); } if (m_SettingsWidget) { m_SettingsWidget->SetSettingsNode(m_SettingsNode); } } void <API key>::SetSettingsWidget(<API key>* settingsWidget) { // disconnect slots to settings widget if there was a widget before if ( m_SettingsWidget ) { disconnect( ui->settingsSaveButton, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnSave()) ); disconnect( ui-><API key>, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnCancel()) ); disconnect (m_SettingsWidget, SIGNAL(Saved()), this, SLOT(<API key>()) ); disconnect (m_SettingsWidget, SIGNAL(Canceled()), this, SLOT(<API key>()) ); disconnect (m_SettingsWidget, SIGNAL(SettingsChanged(itk::SmartPointer<mitk::DataNode>)), this, SLOT(OnSettingsChanged(itk::SmartPointer<mitk::DataNode>)) ); ui->settingsWidget->removeWidget(m_SettingsWidget); } m_SettingsWidget = settingsWidget; if ( m_SettingsWidget ) { m_SettingsWidget->LoadSettings(); connect( ui->settingsSaveButton, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnSave()) ); connect( ui-><API key>, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnCancel()) ); connect (m_SettingsWidget, SIGNAL(Saved()), this, SLOT(<API key>()) ); connect (m_SettingsWidget, SIGNAL(Canceled()), this, SLOT(<API key>()) ); connect (m_SettingsWidget, SIGNAL(SettingsChanged(itk::SmartPointer<mitk::DataNode>)), this, SLOT(OnSettingsChanged(itk::SmartPointer<mitk::DataNode>)) ); if ( m_SettingsNode.IsNotNull() ) { m_SettingsWidget->SetSettingsNode(m_SettingsNode, true); } ui->settingsWidget->addWidget(m_SettingsWidget); } ui->settingsButton->setEnabled(m_SettingsWidget != 0); } void <API key>::SetNavigationSteps(<API key> navigationSteps) { disconnect( this, SLOT(OnTabChanged(int)) ); for ( int n = ui->stepsToolBox->count()-1; n >= 0; --n ) { ui->stepsToolBox->removeItem(n); } connect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); m_NavigationSteps.clear(); m_NavigationSteps = navigationSteps; this-><API key>(); // notify all navigation step widgets about the current settings for (<API key> it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it) { (*it)->OnSettingsChanged(m_SettingsNode); } } void <API key>::<API key>() { MITK_INFO("<API key>") << "Resetting navigation process."; ui->stepsToolBox->blockSignals(true); for ( int n = 0; n <= m_CurrentMaxStep; ++n ) { m_NavigationSteps.at(n)->StopStep(); if ( n > 0 ) { ui->stepsToolBox->setItemEnabled(n, false); } } ui->stepsToolBox->blockSignals(false); m_CurrentMaxStep = 0; ui->stepsToolBox->setCurrentIndex(0); if ( m_NavigationSteps.size() > 0 ) { m_NavigationSteps.at(0)->ActivateStep(); } this-><API key>(); } void <API key>::<API key>() { if ( m_CombinedModality.IsNotNull() && !m_CombinedModality->GetIsFreezed() ) { m_CombinedModality->Modified(); m_CombinedModality->Update(); if ( <API key>.IsNotNull() ) { <API key>->Update(); } mitk::Image::Pointer image = m_CombinedModality->GetOutput(); // make sure that always the current image is set to the data node if ( image.IsNotNull() && m_ImageStreamNode->GetData() != image.GetPointer() && image->IsInitialized() ) { m_ImageStreamNode->SetData(image); <API key> = true; } } if ( m_CurrentTabIndex > 0 && static_cast<unsigned int>(m_CurrentTabIndex) < m_NavigationSteps.size() ) { m_NavigationSteps.at(m_CurrentTabIndex)->Update(); } } void <API key>::OnNextButtonClicked() { if (m_CombinedModality.IsNotNull() && m_CombinedModality->GetIsFreezed()) {return;} //no moving through steps when the modality is NULL or frozen int currentIndex = ui->stepsToolBox->currentIndex(); if (currentIndex >= m_CurrentMaxStep) { MITK_WARN << "Next button clicked though no next tab widget is available."; return; } ui->stepsToolBox->setCurrentIndex(++currentIndex); this-><API key>(); } void <API key>::<API key>() { if (m_CombinedModality.IsNotNull() && m_CombinedModality->GetIsFreezed()) {return;} //no moving through steps when the modality is NULL or frozen int currentIndex = ui->stepsToolBox->currentIndex(); if (currentIndex <= 0) { MITK_WARN << "Previous button clicked though no previous tab widget is available."; return; } ui->stepsToolBox->setCurrentIndex(--currentIndex); this-><API key>(); } void <API key>::<API key>() { MITK_INFO("<API key>") << "Restarting step " << m_CurrentTabIndex << " (" << m_NavigationSteps.at(m_CurrentTabIndex)->GetTitle().toStdString() << ")."; m_NavigationSteps.at(ui->stepsToolBox->currentIndex())->RestartStep(); m_NavigationSteps.at(ui->stepsToolBox->currentIndex())->ActivateStep(); } void <API key>::OnTabChanged(int index) { if ( index < 0 || index >= static_cast<int>(m_NavigationSteps.size()) ) { return; } else if ( m_CurrentTabIndex == index ) { // just activate the step if it is the same step againg m_NavigationSteps.at(index)->ActivateStep(); return; } MITK_INFO("<API key>") << "Activating navigation step " << index << " (" << m_NavigationSteps.at(index)->GetTitle().toStdString() <<")."; if (index > m_CurrentTabIndex) { this-><API key>(); // finish all previous steps to make sure that all data is valid for (int n = m_CurrentTabIndex; n < index; ++n) { m_NavigationSteps.at(n)->FinishStep(); } } // deactivate the previously active step if ( m_CurrentTabIndex > 0 && m_NavigationSteps.size() > static_cast<unsigned int>(m_CurrentTabIndex) ) { m_NavigationSteps.at(m_CurrentTabIndex)->DeactivateStep(); } // start step of the current tab if it wasn't started before if ( m_NavigationSteps.at(index)-><API key>() == <API key>::State_Stopped ) { m_NavigationSteps.at(index)->StartStep(); } m_NavigationSteps.at(index)->ActivateStep(); if (static_cast<unsigned int>(index) < m_NavigationSteps.size()) ui->restartStepButton->setEnabled(m_NavigationSteps.at(index)->GetIsRestartable()); this-><API key>(); m_CurrentTabIndex = index; emit <API key>(index); } void <API key>::<API key>() { this-><API key>(true); } void <API key>::<API key>() { this-><API key>(false); } void <API key>::<API key>(itk::SmartPointer<mitk::DataNode> dataNode) { if ( m_SettingsWidget ) m_SettingsWidget->SetSettingsNode(dataNode); } void <API key>::OnStepReady(int index) { if (m_CurrentMaxStep <= index) { m_CurrentMaxStep = index + 1; this-><API key>(); for (int n = 0; n <= m_CurrentMaxStep; ++n) { ui->stepsToolBox->setItemEnabled(n, true); } } emit <API key>(index, true); } void <API key>::OnStepNoLongerReady(int index) { if (m_CurrentMaxStep > index) { m_CurrentMaxStep = index; this-><API key>(); this-><API key>(); for (int n = m_CurrentMaxStep+1; n < ui->stepsToolBox->count(); ++n) { ui->stepsToolBox->setItemEnabled(n, false); m_NavigationSteps.at(n)->StopStep(); } } emit <API key>(index, false); } void <API key>::<API key>(itk::SmartPointer<mitk::USCombinedModality> combinedModality) { m_CombinedModality = combinedModality; <API key> = false; if ( combinedModality.IsNotNull() ) { if ( combinedModality-><API key>().IsNull() ) { MITK_WARN << "There is no navigation data source set for the given combined modality."; return; } this-><API key>(); } for (<API key> it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it) { (*it)->SetCombinedModality(combinedModality); } emit <API key>(combinedModality); } void <API key>::OnSettingsChanged(const mitk::DataNode::Pointer dataNode) { static bool methodEntered = false; if ( methodEntered ) { MITK_WARN("<API key>") << "Ignoring recursive call to 'OnSettingsChanged()'. " << "Make sure to no emit '<API key>' in an 'OnSettingsChanged()' method."; return; } methodEntered = true; std::string application; if ( dataNode->GetStringProperty("settings.application", application) ) { QString applicationQString = QString::fromStdString(application); if ( applicationQString != ui->titleLabel->text() ) { ui->titleLabel->setText(applicationQString); } } // notify all navigation step widgets about the changed settings for (<API key> it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it) { (*it)->OnSettingsChanged(dataNode); } emit <API key>(dataNode); methodEntered = false; } void <API key>::<API key>() { // do not listen for steps tool box signal during insertion of items into tool box disconnect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); m_CurrentMaxStep = 0; mitk::DataStorage::Pointer dataStorage = m_DataStorage; for (unsigned int n = 0; n < m_NavigationSteps.size(); ++n) { <API key>* curNavigationStep = m_NavigationSteps.at(n); curNavigationStep->SetDataStorage(dataStorage); connect( curNavigationStep, SIGNAL(<API key>()), m_ReadySignalMapper, SLOT(map())); connect( curNavigationStep, SIGNAL(<API key>()), <API key>, SLOT(map()) ); connect( curNavigationStep, SIGNAL(<API key>(itk::SmartPointer<mitk::USCombinedModality>)), this, SLOT(<API key>(itk::SmartPointer<mitk::USCombinedModality>)) ); connect( curNavigationStep, SIGNAL(<API key>(const itk::SmartPointer<mitk::DataNode>)), this, SIGNAL(<API key>(const itk::SmartPointer<mitk::DataNode>)) ); connect( curNavigationStep, SIGNAL(<API key>(itk::SmartPointer<mitk::DataNode>)), this, SLOT(<API key>(itk::SmartPointer<mitk::DataNode>)) ); m_ReadySignalMapper->setMapping(curNavigationStep, n); <API key>->setMapping(curNavigationStep, n); ui->stepsToolBox->insertItem(n, curNavigationStep, QString("Step ") + QString::number(n+1) + ": " + curNavigationStep->GetTitle()); if ( n > 0 ) { ui->stepsToolBox->setItemEnabled(n, false); } } ui->restartStepButton->setEnabled(m_NavigationSteps.at(0)->GetIsRestartable()); ui->stepsToolBox->setCurrentIndex(0); // activate the first navigation step widgets if ( ! m_NavigationSteps.empty() ) { m_NavigationSteps.at(0)->ActivateStep(); } // after filling the steps tool box the signal is interesting again connect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); this-><API key>(); } void <API key>::<API key>() { int currentIndex = ui->stepsToolBox->currentIndex(); ui->previousButton->setEnabled(currentIndex > 0); ui->nextButton->setEnabled(currentIndex < m_CurrentMaxStep); } void <API key>::<API key>() { if ( m_CombinedModality.IsNull() ) { return; } std::vector<mitk::<API key>::Pointer> filterList; mitk::<API key>::Pointer <API key> = m_CombinedModality-><API key>(); for (unsigned int n = 0; n <= m_CurrentMaxStep && n < m_NavigationSteps.size(); ++n) { <API key>::FilterVector filter = m_NavigationSteps.at(n)->GetFilter(); if ( ! filter.empty() ) { filterList.insert(filterList.end(), filter.begin(), filter.end()); } } if ( ! filterList.empty() ) { for (unsigned int n = 0; n < <API key>->GetNumberOfOutputs(); ++n) { filterList.at(0)->SetInput(n, <API key>->GetOutput(n)); } for (std::vector<mitk::<API key>::Pointer>::iterator it = filterList.begin()+1; it != filterList.end(); ++it) { std::vector<mitk::<API key>::Pointer>::iterator prevIt = it-1; for (unsigned int n = 0; n < (*prevIt)->GetNumberOfOutputs(); ++n) { (*it)->SetInput(n, (*prevIt)->GetOutput(n)); } } <API key> = filterList.at(filterList.size()-1); } else { <API key> = <API key>.GetPointer(); } } void <API key>::<API key>(bool visible) { ui->settingsFrameWidget->setVisible(visible); ui->stepsToolBox->setHidden(visible); ui->settingsButton->setHidden(visible); ui->restartStepButton->setHidden(visible); ui->previousButton->setHidden(visible); ui->nextButton->setHidden(visible); } void <API key>::<API key>() { int currentIndex = ui->stepsToolBox->currentIndex(); <API key>* curNavigationStep = m_NavigationSteps.at(currentIndex); curNavigationStep->FinishStep(); }
#include "chrome/browser/image_editor/screenshot_flow.h" #include <memory> #include "base/logging.h" #include "build/build_config.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/<API key>.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/compositor/paint_recorder.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/render_text.h" #include "ui/snapshot/snapshot.h" #include "ui/views/background.h" #if defined(OS_MAC) #include "chrome/browser/image_editor/event_capture_mac.h" #include "components/lens/lens_features.h" #include "content/public/browser/render_view_host.h" #include "ui/views/widget/widget.h" #endif #if defined(USE_AURA) #include "ui/aura/window.h" #include "ui/wm/core/window_util.h" #endif namespace image_editor { // Colors for semitransparent overlay. static constexpr SkColor <API key> = SkColorSetARGB(0x7F, 0x00, 0x00, 0x00); static constexpr SkColor <API key> = SkColorSetARGB(0x00, 0x00, 0x00, 0x00); static constexpr SkColor kColorSelectionRect = SkColorSetRGB(0xEE, 0xEE, 0xEE); // Minimum selection rect edge size to treat as a valid capture region. static constexpr int <API key> = 30; ScreenshotFlow::ScreenshotFlow(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), web_contents_(web_contents->GetWeakPtr()) { weak_this_ = weak_factory_.GetWeakPtr(); } ScreenshotFlow::~ScreenshotFlow() { RemoveUIOverlay(); } void ScreenshotFlow::<API key>() { if (<API key>) return; <API key> = std::make_unique<<API key>>( web_contents_.get(), this); <API key> = std::make_unique<ui::Layer>(ui::LayerType::LAYER_TEXTURED); <API key>->SetName("<API key>"); <API key>-><API key>(false); <API key>->set_delegate(this); #if defined(OS_MAC) gfx::Rect bounds = web_contents_->GetViewBounds(); const gfx::NativeView web_contents_view = web_contents_-><API key>(); views::Widget* widget = views::Widget::<API key>(web_contents_view); ui::Layer* content_layer = widget->GetLayer(); const gfx::Rect offset_bounds = widget-><API key>(); bounds.Offset(-offset_bounds.x(), -offset_bounds.y()); event_capture_mac_ = std::make_unique<EventCaptureMac>( this, web_contents_-><API key>()); #else const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); ui::Layer* content_layer = native_window->layer(); const gfx::Rect bounds = native_window->bounds(); // Capture mouse down and drag events on our window. native_window->AddPreTargetHandler(this); #endif content_layer->Add(<API key>.get()); content_layer->StackAtTop(<API key>.get()); <API key>->SetBounds(bounds); <API key>->SetVisible(true); SetCursor(ui::mojom::CursorType::kCross); // After setup is done, we should set the capture mode to active. capture_mode_ = CaptureMode::SELECTION_RECTANGLE; } void ScreenshotFlow::RemoveUIOverlay() { if (capture_mode_ == CaptureMode::NOT_CAPTURING) return; capture_mode_ = CaptureMode::NOT_CAPTURING; if (!web_contents_ || !<API key>) return; #if defined(OS_MAC) views::Widget* widget = views::Widget::<API key>( web_contents_-><API key>()); if (!widget) return; ui::Layer* content_layer = widget->GetLayer(); event_capture_mac_.reset(); #else const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); native_window-><API key>(this); ui::Layer* content_layer = native_window->layer(); #endif content_layer->Remove(<API key>.get()); <API key>->set_delegate(nullptr); <API key>.reset(); // Restore the cursor to pointer; there's no corresponding GetCursor() // to store the pre-capture-mode cursor, and the pointer will have moved // in the meantime. SetCursor(ui::mojom::CursorType::kPointer); } void ScreenshotFlow::Start(<API key> flow_callback) { flow_callback_ = std::move(flow_callback); <API key>(); RequestRepaint(gfx::Rect()); } void ScreenshotFlow::<API key>( <API key> flow_callback) { // Start and finish the capture process by screenshotting the full window. // There is no region selection step in this mode. flow_callback_ = std::move(flow_callback); <API key>(<API key>::SUCCESS, gfx::Rect(web_contents_->GetSize())); } void ScreenshotFlow::<API key>( <API key> result_code, gfx::Rect region) { if (region.IsEmpty()) { <API key>(result_code, gfx::Rect(), gfx::Image()); return; } gfx::Rect bounds = web_contents_->GetViewBounds(); #if defined(OS_MAC) const gfx::NativeView& native_view = web_contents_-><API key>(); gfx::Image img; bool rval = ui::GrabViewSnapshot(native_view, region, &img); // If |img| is empty, clients should treat it as a canceled action, but // we have a DCHECK for development as we expected this call to succeed. DCHECK(rval); <API key>(result_code, bounds, img); #else ui::<API key> screenshot_callback = base::BindOnce(&ScreenshotFlow::<API key>, weak_this_, result_code, bounds); const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); ui::<API key>(native_window, region, std::move(screenshot_callback)); #endif } void ScreenshotFlow::CancelCapture() { RemoveUIOverlay(); } void ScreenshotFlow::OnKeyEvent(ui::KeyEvent* event) { if (event->type() == ui::ET_KEY_PRESSED && event->key_code() == ui::VKEY_ESCAPE) { event->StopPropagation(); CompleteCapture(<API key>::USER_ESCAPE_EXIT, gfx::Rect()); } } void ScreenshotFlow::OnMouseEvent(ui::MouseEvent* event) { if (!event->IsLocatedEvent()) return; const ui::LocatedEvent* located_event = ui::LocatedEvent::FromIfValid(event); if (!located_event) return; gfx::Point location = located_event->location(); #if defined(OS_MAC) // Offset |location| be relative to the WebContents widget, vs the parent // window, recomputed rather than cached in case e.g. user disables // bookmarks bar from another window. gfx::Rect web_contents_bounds = web_contents_->GetViewBounds(); const gfx::NativeView web_contents_view = web_contents_-><API key>(); views::Widget* widget = views::Widget::<API key>(web_contents_view); const gfx::Rect widget_bounds = widget-><API key>(); location.set_x(location.x() + (widget_bounds.x() - web_contents_bounds.x())); location.set_y(location.y() + (widget_bounds.y() - web_contents_bounds.y())); // Don't capture clicks on browser ui outside the webcontents. if (location.x() < 0 || location.y() < 0 || location.x() > web_contents_bounds.width() || location.y() > web_contents_bounds.height()) { return; } #endif switch (event->type()) { case ui::ET_MOUSE_MOVED: SetCursor(ui::mojom::CursorType::kCross); event->SetHandled(); break; case ui::ET_MOUSE_PRESSED: if (event->IsLeftMouseButton()) { drag_start_ = location; drag_end_ = location; event->SetHandled(); } break; case ui::ET_MOUSE_DRAGGED: if (event->IsLeftMouseButton()) { drag_end_ = location; RequestRepaint(gfx::Rect()); event->SetHandled(); } break; case ui::ET_MOUSE_RELEASED: if (capture_mode_ == CaptureMode::SELECTION_RECTANGLE || capture_mode_ == CaptureMode::SELECTION_ELEMENT) { event->SetHandled(); gfx::Rect selection = gfx::BoundingRect(drag_start_, drag_end_); drag_start_.SetPoint(0, 0); drag_end_.SetPoint(0, 0); if (selection.width() >= <API key> && selection.height() >= <API key>) { CompleteCapture(<API key>::SUCCESS, selection); } else { RequestRepaint(gfx::Rect()); } } break; default: break; } } void ScreenshotFlow::CompleteCapture(<API key> result_code, const gfx::Rect& region) { RemoveUIOverlay(); <API key>(result_code, region); } void ScreenshotFlow::<API key>( <API key> result_code, gfx::Rect bounds, gfx::Image image) { <API key> result; result.result_code = result_code; result.image = image; result.screen_bounds = bounds; std::move(flow_callback_).Run(result); } void ScreenshotFlow::OnPaintLayer(const ui::PaintContext& context) { if (!<API key>) return; const gfx::Rect& screen_bounds(<API key>->bounds()); ui::PaintRecorder recorder(context, screen_bounds.size()); gfx::Canvas* canvas = recorder.canvas(); auto selection_rect = gfx::BoundingRect(drag_start_, drag_end_); PaintSelectionLayer(canvas, selection_rect, gfx::Rect()); paint_invalidation_ = gfx::Rect(); } void ScreenshotFlow::RequestRepaint(gfx::Rect region) { if (!<API key>) return; if (region.IsEmpty()) { const gfx::Size& layer_size = <API key>->size(); region = gfx::Rect(0, 0, layer_size.width(), layer_size.height()); } paint_invalidation_.Union(region); <API key>->SchedulePaint(region); } void ScreenshotFlow::PaintSelectionLayer(gfx::Canvas* canvas, const gfx::Rect& selection, const gfx::Rect& invalidation_region) { // Adjust for hidpi and lodpi support. canvas-><API key>(); // Clear the canvas with our mask color. canvas->DrawColor(<API key>); // Allow the user's selection to show through, and add a border around it. if (!selection.IsEmpty()) { float scale_factor = <API key>->device_scale_factor(); gfx::Rect selection_scaled = gfx::<API key>(selection, scale_factor); canvas->FillRect(selection_scaled, <API key>, SkBlendMode::kClear); canvas->DrawRect(gfx::RectF(selection_scaled), kColorSelectionRect); } } void ScreenshotFlow::SetCursor(ui::mojom::CursorType cursor_type) { if (!web_contents_) { return; } #if defined(OS_MAC) if (cursor_type == ui::mojom::CursorType::kCross && lens::features::<API key>.Get()) { EventCaptureMac::SetCrossCursor(); return; } #endif content::RenderWidgetHost* host = web_contents_->GetMainFrame()->GetRenderWidgetHost(); if (host) { ui::Cursor cursor(cursor_type); host->SetCursor(cursor); } } bool ScreenshotFlow::IsCaptureModeActive() { return capture_mode_ != CaptureMode::NOT_CAPTURING; } void ScreenshotFlow::<API key>() { if (IsCaptureModeActive()) { CancelCapture(); } } void ScreenshotFlow::OnVisibilityChanged(content::Visibility visibility) { if (IsCaptureModeActive()) { CancelCapture(); } } // <API key> monitors the WebContents and exits screen // capture mode if a navigation occurs. class ScreenshotFlow::<API key> : public content::WebContentsObserver { public: <API key>(content::WebContents* web_contents, ScreenshotFlow* screenshot_flow) : content::WebContentsObserver(web_contents), screenshot_flow_(screenshot_flow) {} ~<API key>() override = default; <API key>(const <API key>&) = delete; <API key>& operator=( const <API key>&) = delete; // content::WebContentsObserver void PrimaryPageChanged(content::Page& page) override { // We only care to complete/cancel a capture if the capture mode is // currently active. if (screenshot_flow_->IsCaptureModeActive()) screenshot_flow_->CompleteCapture( <API key>::USER_NAVIGATED_EXIT, gfx::Rect()); } private: ScreenshotFlow* screenshot_flow_; }; } // namespace image_editor
#ifndef <API key> #define <API key> #pragma once #include "base/compiler_specific.h" #include "content/public/common/content_client.h" namespace chrome { class ChromeContentClient : public content::ContentClient { public: static const char* const kPDFPluginName; static const char* const kNaClPluginName; static const char* const kNaClOldPluginName; virtual void SetActiveURL(const GURL& url) OVERRIDE; virtual void SetGpuInfo(const content::GPUInfo& gpu_info) OVERRIDE; virtual void AddPepperPlugins( std::vector<content::PepperPluginInfo>* plugins) OVERRIDE; virtual void AddNPAPIPlugins( webkit::npapi::PluginList* plugin_list) OVERRIDE; virtual bool <API key>(const IPC::Message* msg) OVERRIDE; virtual bool <API key>(const IPC::Message& msg) OVERRIDE; virtual std::string GetUserAgent(bool* overriding) const OVERRIDE; virtual string16 GetLocalizedString(int message_id) const OVERRIDE; virtual base::StringPiece GetDataResource(int resource_id) const OVERRIDE; #if defined(OS_WIN) virtual bool SandboxPlugin(CommandLine* command_line, sandbox::TargetPolicy* policy) OVERRIDE; #endif #if defined(OS_MACOSX) virtual bool <API key>( int sandbox_type, int* <API key>) const OVERRIDE; #endif }; } // namespace chrome #endif // <API key>
#ifndef <API key> #define <API key> #include <memory> #include "base/callback.h" #include "base/macros.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/webdatabase/database_error.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" #include "third_party/blink/renderer/platform/wtf/text/string_hash.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/<API key>.h" namespace blink { class Database; class DatabaseContext; class Page; class SecurityOrigin; class MODULES_EXPORT DatabaseTracker { USING_FAST_MALLOC(DatabaseTracker); public: static DatabaseTracker& Tracker(); DatabaseTracker(const DatabaseTracker&) = delete; DatabaseTracker& operator=(const DatabaseTracker&) = delete; // This singleton will potentially be used from multiple worker threads and // the page's context thread simultaneously. To keep this safe, it's // currently using 4 locks. In order to avoid deadlock when taking multiple // locks, you must take them in the correct order: // m_databaseGuard before quotaManager if both locks are needed. // <API key> before quotaManager if both locks are needed. // m_databaseGuard and <API key> currently don't overlap. // notificationMutex() is currently independent of the other locks. bool <API key>(DatabaseContext*, DatabaseError&); String FullPathForDatabase(const SecurityOrigin*, const String& name, bool <API key> = true); void AddOpenDatabase(Database*); void RemoveOpenDatabase(Database*); uint64_t <API key>(const Database*); void <API key>(const SecurityOrigin*, const String& name); using DatabaseCallback = base::RepeatingCallback<void(Database*)>; void <API key>(Page*, DatabaseCallback); void <API key>(Database*); void <API key>(Database*); private: using DatabaseSet = HashSet<<API key><Database>>; using DatabaseNameMap = HashMap<String, DatabaseSet*>; using DatabaseOriginMap = HashMap<String, DatabaseNameMap*>; DatabaseTracker(); void <API key>(const String& origin_identifier, const String& name, Database*); Mutex <API key>; mutable std::unique_ptr<DatabaseOriginMap> open_database_map_; }; } // namespace blink #endif // <API key>
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.c Label Definition File: <API key>.c.label.xml Template File: sources-sinks-64b.tmpl.c */ /* * @description * CWE: 457 Use of Uninitialized Variable * BadSource: no_init Don't initialize data * GoodSource: Initialize data * Sinks: use * GoodSink: Initialize then use data * BadSink : Use data * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void <API key>(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* POTENTIAL FLAW: Use data without initializing it */ printLine(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void <API key>(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* POTENTIAL FLAW: Use data without initializing it */ printLine(data); } /* goodB2G uses the BadSource with the GoodSink */ void <API key>(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* FIX: Ensure data is initialized before use */ data = "string"; printLine(data); } #endif /* OMITGOOD */
#include "content/common/<API key>.h" #include <ctype.h> #include "base/bind.h" #include "base/message_loop.h" #include "base/metrics/statistics_recorder.h" #include "base/pickle.h" #include "content/common/child_process.h" #include "content/common/<API key>.h" #include "content/common/child_thread.h" namespace content { <API key>::<API key>() : channel_(NULL), <API key>(<API key>(this)) { } <API key>::~<API key>() { } void <API key>::OnFilterAdded(IPC::Channel* channel) { channel_ = channel; } void <API key>::OnFilterRemoved() { } bool <API key>::OnMessageReceived( const IPC::Message& message) { bool handled = true; <API key>(<API key>, message) IPC_MESSAGE_HANDLER(<API key>, <API key>) <API key>(handled = false) IPC_END_MESSAGE_MAP() return handled; } void <API key>::SendHistograms(int sequence_number) { ChildProcess::current()-><API key>()->PostTask( FROM_HERE, base::Bind(&<API key>::UploadAllHistograms, this, sequence_number)); } void <API key>::<API key>(int sequence_number) { UploadAllHistograms(sequence_number); } void <API key>::UploadAllHistograms(int sequence_number) { DCHECK_EQ(0u, pickled_histograms_.size()); base::StatisticsRecorder::<API key>("ChildProcess"); // Push snapshots into our pickled_histograms_ vector. // Note: Before serializing, we set the <API key> for all // the histograms, so that the receiving process can distinguish them from the // local histograms. <API key>.PrepareDeltas( base::Histogram::<API key>, false); channel_->Send(new <API key>( sequence_number, pickled_histograms_)); pickled_histograms_.clear(); static int count = 0; count++; DHISTOGRAM_COUNTS("Histogram.<API key>", count); } void <API key>::RecordDelta( const base::HistogramBase& histogram, const base::HistogramSamples& snapshot) { DCHECK_NE(0, snapshot.TotalCount()); Pickle pickle; histogram.SerializeInfo(&pickle); snapshot.Serialize(&pickle); pickled_histograms_.push_back( std::string(static_cast<const char*>(pickle.data()), pickle.size())); } void <API key>::<API key>( base::Histogram::Inconsistencies problem) { <API key>("Histogram.<API key>", problem, base::Histogram::<API key>); } void <API key>::<API key>( base::Histogram::Inconsistencies problem) { <API key>("Histogram.<API key>", problem, base::Histogram::<API key>); } void <API key>::<API key>( int amount) { <API key>("Histogram.<API key>", std::abs(amount)); } } // namespace content
#include <jni.h> #include <stdio.h> #include <stdlib.h> #include "torchandroid.h" #include <assert.h> extern "C" { JNIEXPORT jstring JNICALL <API key>( JNIEnv* env, jobject thiz, jobject assetManager, jstring nativeLibraryDir_, jstring luaFile_ ) { // D("Hello from C"); // get native asset manager AAssetManager* manager = <API key>(env, assetManager); assert( NULL != manager); const char *nativeLibraryDir = env->GetStringUTFChars(nativeLibraryDir_, 0); const char *file = env->GetStringUTFChars(luaFile_, 0); char buffer[4096]; // buffer for textview output D("Torch.call(%s), nativeLibraryDir=%s", file, nativeLibraryDir); buffer[0] = 0; lua_State *L = inittorch(manager, nativeLibraryDir); // create a lua_State assert( NULL != manager); // load and run file int ret; long size = <API key>(file); if (size != -1) { char *filebytes = <API key>(file); ret = luaL_dobuffer(L, filebytes, size, "main"); } // check if script ran succesfully. If not, print error to logcat if (ret == 1) { D("Error doing resource: %s:%s\n", file, lua_tostring(L,-1)); strlcat(buffer, lua_tostring(L,-1), sizeof(buffer)); } else strlcat(buffer, "Torch script ran succesfully. Check Logcat for more details.", sizeof(buffer)); // destroy the Lua State lua_close(L); return env->NewStringUTF(buffer); } }
<?php use yii\helpers\Html; ?> <?php foreach ($_model as $photo): ?> <div class="thumb" style="float:left;padding: 2px" data-name="<?= $photo->name ?>" onclick="ShowFullImage('<?= $photo->name ?>')" > <div> <?= Html::img('/upload/multy-thumbs/' . $photo->name, ['height' => '70px']); ?> </div> <div style="" > <?= $photo->name; ?> </div> </div> <?php endforeach; ?> <style> .jpreloader.back_background{ background-color: #111214; bottom: 0; height: 100%; left: 0; opacity: 0.9; position: fixed; right: 0; top: 0; width: 100%; display: block; background-image: url("/img/preloader.gif"); background-repeat: no-repeat; background-position:center center; } </style>
package io.flutter.embedding.engine.mutatorsstack; import static junit.framework.TestCase.*; import static org.mockito.Mockito.*; import android.graphics.Matrix; import android.view.MotionEvent; import io.flutter.embedding.android.<API key>; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.<API key>; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(<API key>.class) public class <API key> { @Test public void canDragViews() { final <API key> touchProcessor = mock(<API key>.class); final FlutterMutatorView view = new FlutterMutatorView(RuntimeEnvironment.systemContext, 1.0f, touchProcessor); final <API key> mutatorStack = mock(<API key>.class); assertTrue(view.<API key>(mock(MotionEvent.class))); { view.readyToDisplay(mutatorStack, /*left=*/ 1, /*top=*/ 2, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(1, 2); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 3, /*top=*/ 4, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(1, 2); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 5, /*top=*/ 6, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(3, 4); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 7, /*top=*/ 8, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(7, 8); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } } }
package org.hisp.dhis.dxf2.adx; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.xerces.util.XMLChar; import org.hisp.dhis.dataelement.DataElementCategory; import org.hisp.dhis.dataelement.<API key>; import org.hisp.dhis.dataelement.<API key>; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.dataset.DataSetElement; /** * @author bobj */ public class AdxDataSetMetadata { // Lookup category options per cat option combo private final Map<Integer, Map<String, String>> categoryOptionMap; AdxDataSetMetadata( DataSet dataSet ) throws AdxException { categoryOptionMap = new HashMap<>(); Set<<API key>> catCombos = new HashSet<>(); catCombos.add( dataSet.getCategoryCombo() ); for ( DataSetElement element : dataSet.getDataSetElements() ) { catCombos.add( element.<API key>() ); } for ( <API key> categoryCombo : catCombos ) { for ( <API key> catOptCombo : categoryCombo.getOptionCombos() ) { <API key>( catOptCombo ); } } } private void <API key>( <API key> coc ) throws AdxException { Map<String, String> categoryAttributes = new HashMap<>(); if ( !coc.isDefault() ) { for ( DataElementCategory category : coc.getCategoryCombo().getCategories() ) { String categoryCode = category.getCode(); if ( categoryCode == null || !XMLChar.isValidName( categoryCode ) ) { throw new AdxException( "Category code for " + category.getName() + " is missing or invalid: " + categoryCode ); } String catOptCode = category.getCategoryOption( coc ).getCode(); if ( catOptCode == null || catOptCode.isEmpty() ) { throw new AdxException( "CategoryOption code for " + category.getCategoryOption( coc ).getName() + " is missing" ); } categoryAttributes.put( categoryCode, catOptCode ); } } categoryOptionMap.put( coc.getId(), categoryAttributes ); } public Map<String, String> <API key>( int cocId ) { return this.categoryOptionMap.get( cocId ); } }
<?php namespace backend\models; use common\helpers\CommonUtils; use common\helpers\CVietnameseTools; use common\helpers\MediaToolBoxHelper; use common\helpers\MyCurl; use common\models\Content; use common\models\News; use garyjl\simplehtmldom\SimpleHtmlDom; use Imagine\Image\Box; use Imagine\Image\<API key>; use Yii; use yii\base\Model; use yii\helpers\FileHelper; use yii\helpers\Url; use yii\validators\ImageValidator; use yii\validators\UrlValidator; use yii\web\UploadedFile; class Image extends Model { const TYPE_POSTER = 1; const TYPE_THUMBNAIL = 2; const TYPE_SLIDESHOW = 3; const TYPE_AUTO = 4; const <API key> = 1; const <API key> = 2; const RATIO_W = 16; const RATIO_H = 9; const <API key> = 120;//Ty le toi da limit (1920x1080) public static $imageConfig = null; private $_id = ''; public $content_id; public $name; public $url; public $type = self::TYPE_POSTER; public $orientation; public static $image_types = [ self::TYPE_POSTER => 'poster', self::TYPE_SLIDESHOW => 'slide show', self::TYPE_THUMBNAIL => 'thumbnail', self::TYPE_AUTO => 'auto' ]; public static $image_orient = [ self::<API key> => 'landscape', self::<API key> => 'portrait' ]; /** * @var $image UploadedFile */ public $image; /** * Create snapshot param * @param Content $video */ private static function initParamSnapshot($video, $position) { $snapshots = []; $folderSave = self::createFolderImage($video->id); if (!$folderSave) { return false; } if($position <= 0 || $position > $video->duration){ $position = rand(1, $video->duration); } $saveFileName = time() . '_' . CVietnameseTools::makeValidFileName($video->display_name . '_' . $position . '_snapshot.jpg'); $snapshot = new Snapshot(); $snapshot->time = $position; $snapshot->file_path = Yii::getAlias($folderSave) . $saveFileName; $snapshot->size = '100%'; $snapshots[] = $snapshot; return $snapshots; } private static function toAlias($path) { $basePath = Yii::getAlias('@webroot'); Yii::info(preg_quote($basePath, '/')); return preg_replace('/'.preg_quote($basePath, '/').'/', '@webroot', $path); } /** * @inheritdoc */ public function rules() { return [ [['image'], 'file', 'extensions' => ['jpg', 'png', 'jpeg', 'gif']], ['id', 'safe'], [['type', 'orientation'], 'integer'], [['url', 'name'], 'string', 'max' => 500], ]; } public function fields() { // if ($this->scenario == static::SCENARIO_DEFAULT) { // return parent::fields(); //List scenario $res = [ // field name is "email", the corresponding attribute name is "email_address" 'name', 'url', 'type', 'orientation', ]; return $res; } public function getId() { if (empty($this->_id)) { $this->_id = md5($this->url); } return $this->_id; } /** * Return full path url */ public function getImageUrl() { $validator = new UrlValidator(); if ($validator->validate($this->url)) { return $this->url; } else { if (preg_match('/(@[a-z]*)/', $this->url)) { return Yii::getAlias($this->url); } else { $configImage = self::getImageConfig(); $baseUrl = isset($configImage['base_url']) ? $configImage['base_url'] : Yii::getAlias('@web'); return $baseUrl . $this->url; } } } public function getFilePath() { $validator = new UrlValidator(); if ($validator->validate($this->url)) { return null; } else { if (preg_match('/(@[a-z]*)/', $this->url)) { return Yii::getAlias(str_replace('@web', '@webroot', $this->url)); } else { $configImage = self::getImageConfig(); $baseUrl = isset($configImage['base_url']) ? $configImage['base_url'] : Yii::getAlias('@webroot'); return $baseUrl . $this->url; } } } public function getWidthHeight() { if(is_file($this->getFilePath())){ $imageSize = getimagesize($this->getFilePath()); if ($imageSize) { return $imageSize[0] . 'x'. $imageSize[1]; } else { return 'N/A'; } }else{ return 'File not found'; } } public function <API key>() { return time() . '_' . CVietnameseTools::makeValidFileName($this->name); } public static function getImageConfig() { if (Image::$imageConfig == null) { Image::$imageConfig = [ 'folder' => '@webroot' . DIRECTORY_SEPARATOR . Yii::getAlias('@content_images') . DIRECTORY_SEPARATOR, 'base_url' => Yii::getAlias('@web') . '/' . Yii::getAlias('@content_images') . DIRECTORY_SEPARATOR ]; } return Image::$imageConfig; } /** * Create folder to store image * Each store have image separate with video id * @return full path folder with alias (@webroot/...) */ public static function createFolderImage($video_id) { $configImage = self::getImageConfig(); $basePath = Yii::getAlias($configImage['folder']); if (!is_dir($basePath)) { FileHelper::createDirectory($basePath, 0777); } if (!is_dir($basePath) || $video_id == null) { Yii::error("Folder base path not exist: " . $basePath); return false; } $fullPath = $basePath . $video_id; if (!is_dir($fullPath)) { if (!FileHelper::createDirectory($fullPath, 0777)) { Yii::error("Can not create folder save image: " . $fullPath); return false; } } if (!substr($configImage['folder'], -1) == '/') { $configImage['folder'] .= '/'; } return $configImage['folder'] . $video_id . '/'; } /** * Thuc hien save image khi dc upload len * @param $content News * @return bool * @throws \yii\web\Un<API key> */ public function saveImage($content) { $video_id = $content->id; $folderSave = self::createFolderImage($video_id); if (!$folderSave) { $this->addError('image', 'Folder save image not found'); return false; } if ($this->image == null) { $this->addError('image', "Image file not found!"); return false; } $saveFileName = $this-><API key>(); $imagePath = Yii::getAlias($folderSave) . $saveFileName; Yii::info("Save file to " . $imagePath, 'VideoImage'); if (!$this->image->saveAs($imagePath)) { $this->addError('image', 'Can not save '); return false; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $this->orientation = self::<API key>; } else { $this->orientation = self::<API key>; } } $this->url = $this->resolveUrl($folderSave) . $saveFileName; if ($this->type == self::TYPE_AUTO) { $this->autoGenerateImages($content, $folderSave, $saveFileName); } return true; } /** * replaces '/(@[a-z]*)root/' => '$1' * @param string $path * @return string */ public function resolveUrl($path) { return preg_replace('/(@[a-z]*)root/', '$1', $path); } /** * @param $content News */ public function save($content) { return $content->addImage($this->getArray()); } public function getArray() { return [ 'name' => $this->name, 'url' => $this->url, 'type' => $this->type, 'orientation' => $this->orientation ]; } public function delete() { //Delete image $file_path = $this->getFilePath(); if (is_dir($file_path)) { return true; } if ($file_path && file_exists($file_path)) { return unlink($this->getFilePath()); } return true; } /** * @param $video Content * @return bool */ public function loadImageYt($video) { $ch = new MyCurl(); $folderSave = self::createFolderImage($video->id); if (!$folderSave) { $this->addError('image', 'Folder save image not found'); return false; } $yt_info = CommonUtils::getVideoYoutubeInfo($video->youtube_id); if ($yt_info == null || $yt_info->snippet == null || $yt_info->snippet->thumbnails == null) { return false; } $img_yt_url = ''; $thumbnails = $yt_info->snippet->thumbnails; $img_yt_url = $this->getHighestImage($thumbnails); if (empty($img_yt_url)) { return false; } $image_extention = end(explode('.', $img_yt_url)); $this->name = $video->display_name . '_yt.' . $image_extention; $this->type = self::TYPE_AUTO; $saveFileName = $this-><API key>(); $imagePath = Yii::getAlias($folderSave) . $saveFileName; Yii::info("Save file to " . $imagePath, 'VideoImage'); $response = $ch->download($img_yt_url, Yii::getAlias($folderSave), $saveFileName); if (!$response) { $this->addError('image', 'Can not save '); return false; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $this->orientation = self::<API key>; } else { $this->orientation = self::<API key>; } } $this->url = $this->resolveUrl($folderSave) . $saveFileName; $this->autoGenerateImages($video, $folderSave, $saveFileName); if ($yt_info->contentDetails != null) { $video->duration = CommonUtils::<API key>($yt_info->contentDetails->duration); $video->update(false); } return true; } /** * @param Content $video * @return bool */ public static function loadImageSnapshot($video, $video_file, $position = 0) { $snapshots = self::initParamSnapshot($video,$position); $response = MediaToolBoxHelper::getVideoSnapshot($video_file, $snapshots); if (!$response) { Yii::error('Can not get snapshot'); return false; } foreach ($response as $snapshot) { $image = new Image(); $folderSave = self::toAlias(pathinfo($snapshot->file_path, PATHINFO_DIRNAME).DIRECTORY_SEPARATOR); $saveFileName = pathinfo($snapshot->file_path, PATHINFO_BASENAME); $image->name = $saveFileName; $image->autoGenerateImages($video, $folderSave, $saveFileName); } return true; } /** * Load first image from content to create some image * @param $content Content */ public function <API key>($content) { $ch = new MyCurl(); $folderSave = self::createFolderImage($content->id); if (!$folderSave) { $this->addError('image', 'Folder save image not found'); return false; } $img_content_url = ''; $html = SimpleHtmlDom::str_get_html($content->content); // Get first image foreach($html->find('img') as $element){ $img_content_url = $element->src; if(!empty($img_content_url)) break; } if(empty($img_content_url)){ return false; } $url_validator = new UrlValidator(); if(!$url_validator->validate($img_content_url)){ $img_content_url = Yii::$app->getUrlManager()->getHostInfo().$img_content_url; } Yii::info($img_content_url); $image_extention = end(explode('.', $img_content_url)); $this->name = $content->display_name . '_content.' . $image_extention; $this->type = self::TYPE_AUTO; $saveFileName = $this-><API key>(); $imagePath = Yii::getAlias($folderSave) . $saveFileName; Yii::info("Save file to " . $imagePath, 'Image'); $response = $ch->download($img_content_url, Yii::getAlias($folderSave), $saveFileName); if (!$response || !CommonUtils::validateImage($imagePath)) { $this->addError('image', 'Can not save '); return false; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $this->orientation = self::<API key>; } else { $this->orientation = self::<API key>; } } $this->url = $this->resolveUrl($folderSave) . $saveFileName; $this->autoGenerateImages($content, $folderSave, $saveFileName); return true; } /** * Tu dong generate ra cac file dinh dang khac nhau * @param $video * @param $folderSave //Dang tuong doi example '@webroot/content_images/45/ * @param $saveFileName * @return bool */ public function autoGenerateImages($video, $folderSave, $saveFileName) { $imagePath = Yii::getAlias($folderSave) . $saveFileName; $imageSize = getimagesize($imagePath); $img_width = 1; $img_height = 1; if (count($imageSize) > 0) { $img_width = $imageSize[0]; $img_height = $imageSize[1]; } else { return false; } //Resize to slide $slide = $this->resizeImage($folderSave, $imagePath, $img_width, $img_height, self::TYPE_SLIDESHOW); if (!$slide->save($video)) { return false; } //Resize to poster $poster = $this->resizeImage($folderSave, $imagePath, $img_width, $img_height); if (!$poster->save($video)) { return false; }; //Resize to thumbnail $poster = $this->resizeImage($folderSave, $imagePath, $img_width, $img_height, self::TYPE_THUMBNAIL); if (!$poster->save($video)) { return false; } } /** * @param $imageTool \yii\imagine\Image * @param $width * @param $heigh */ private function resizeImage($folder, $filename, $width, $height, $type = self::TYPE_POSTER) { $model = new Image(); $box_src = new Box($width, $height); $box = null; switch ($type) { case self::TYPE_THUMBNAIL: $box = new Box(320, 180); break; default: if (($width / $height) === (self::RATIO_W / self::RATIO_H)) { $box = $box_src; } else { list($new_width, $new_height) = $this->getNewSize($width, $height, self::RATIO_W / self::RATIO_H); $box = new Box($new_width, $new_height); } } $imageTool = \yii\imagine\Image::getImagine()->open($filename); $image = $imageTool->thumbnail($box, <API key>::THUMBNAIL_OUTBOUND); $model->name = self::$image_types[$type] . '_' . $this->name; $model->type = $type; $saveFileName = $model-><API key>(); $imagePath = Yii::getAlias($folder) . $saveFileName; Yii::info("Save file to " . $imagePath, 'VideoImage'); if (!$image->save($imagePath)) { return null; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $model->orientation = self::<API key>; } else { $model->orientation = self::<API key>; } } $model->url = $this->resolveUrl($folder) . $saveFileName; return $model; } private function getHighestImage($thumbnails) { if ($thumbnails->maxres != null) { return $thumbnails->maxres->url; } if ($thumbnails->standard != null) { return $thumbnails->standard->url; } if ($thumbnails->high != null) { return $thumbnails->high->url; } if ($thumbnails->medium != null) { return $thumbnails->medium->url; } if ($thumbnails->default != null) { return $thumbnails->default->url; } } private function getNewSize($width, $height, $ratio) { // Find closest ratio multiple to image size if ($width > $height) { // landscape $ratioMultiple = round($height / self::RATIO_H, 0, PHP_ROUND_HALF_DOWN); } else { // portrait $ratioMultiple = round($width / self::RATIO_W, 0, PHP_ROUND_HALF_DOWN); } $newWidth = $ratioMultiple * self::RATIO_W; $newHeight = $ratioMultiple * self::RATIO_H; if ($newWidth > self::RATIO_W * self::<API key> || $newHeight > self::RATIO_H * self::<API key>) { // File is larger than upper limit $ratioMultiple = self::<API key>; } $this->tweakMultiplier($ratioMultiple, $width, $height); $newWidth = $ratioMultiple * self::RATIO_W; $newHeight = $ratioMultiple * self::RATIO_H; return [ $newWidth, $newHeight ]; } /** * Xac dinh ratio sao cho new_width, new_height kho qua kich thuoc anh that * @param $ratioMultiple * @param $fitInsideWidth * @param $fitInsideHeight */ protected function tweakMultiplier(&$ratioMultiple, $fitInsideWidth, $fitInsideHeight) { $newWidth = $ratioMultiple * self::RATIO_W; $newHeight = $ratioMultiple * self::RATIO_H; if ($newWidth > $fitInsideWidth || $newHeight > $fitInsideHeight) { $ratioMultiple $this->tweakMultiplier($ratioMultiple, $fitInsideWidth, $fitInsideHeight); } else { return; } } }
Ext.define('Ozone.data.Dashboard', { extend: 'Ext.data.Model', idProperty: 'guid', fields:[ 'alteredByAdmin', 'guid', {name:'id', mapping: 'guid'}, { name: 'isdefault', type: 'boolean', defaultValue: false }, { name: 'dashboardPosition', type: 'int' }, '<API key>', 'name', { name: 'state', defaultValue: [] }, 'removed', 'groups', 'isGroupDashboard', 'description', 'createdDate', 'prettyCreatedDate', 'editedDate', 'prettyEditedDate', { name: 'stack', defaultValue: null }, { name: 'locked', type: 'boolean', defaultValue: false }, { name: 'layoutConfig', defaultValue: null }, { name: 'createdBy', model: 'User'}, { name: 'user', model: 'User'} ], constructor: function(data, id, raw) { if(data.layoutConfig && typeof data.layoutConfig === 'string' && data.layoutConfig !== Object.prototype.toString()) { data.layoutConfig = Ext.JSON.decode(data.layoutConfig); } //todo see if we still need this if(data.layoutConfig === Object.prototype.toString()) { data.layoutConfig = ""; } if(!data.guid) { data.guid = guid.util.guid(); } this.callParent(arguments); } }); Ext.define('Ozone.data.stores.AdminDashboardStore', { extend:'Ozone.data.OWFStore', model: 'Ozone.data.Dashboard', alias: 'store.admindashboardstore', remoteSort: true, totalProperty:'results', sorters: [ { property : 'dashboardPosition', direction: 'ASC' } ], constructor: function(config) { Ext.applyIf(config, { api: { read: "/dashboard", create: "/dashboard", update: "/dashboard", destroy: "/dashboard" }, reader: { root: 'data' }, writer: { root: 'data' } }); this.callParent(arguments); }, reorder: function() { if (this.getCount() > 0) { for (var i = 0; i < this.getCount(); i++) { var dashboard = this.getAt(i); dashboard.set('dashboardPosition', i + 1); } } } }); Ext.define('Ozone.components.admin.grid.DashboardGroupsGrid', { extend: 'Ext.grid.Panel', alias: ['widget.dashboardgroupsgrid'], quickSearchFields: ['name'], plugins: new Ozone.components.focusable.FocusableGridPanel(), cls: 'grid-dashboard', defaultPageSize: 50, multiSelect: true, forceFit: true, baseParams: null, initComponent: function() { //create new store if (this.store == null) { this.store = Ext.StoreMgr.lookup({ type: 'admindashboardstore', pageSize: this.defaultPageSize }); } if (this.baseParams) { this.setBaseParams(this.baseParams); } Ext.apply(this, { columnLines:true, columns: [ { itemId: 'guid', header: 'GUID', dataIndex: 'guid', flex: 1, width: 210, minWidth: 210, sortable: true, hidden: true, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { return '<div class="grid-text">' + value +'</div>'; } },{ itemId: 'name', header: 'Dashboard Title', dataIndex: 'name', flex: 3, minWidth: 200, sortable: true, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { var title = value; var dashboardLayoutList = record.get('<API key>'); //List of valid ENUM Dashboard Layout Strings var dashboardLayout = record.get('layout'); //current dashboard layout string var iconClass = "<API key>"; // if(dashboardLayout && dashboardLayoutList){ // if(dashboardLayoutList.indexOf(dashboardLayout) != -1){ // iconClass = "<API key>-" + dashboardLayout; // var retVal = '<div class="<API key>"><div class="grid-dashboard-icon ' + iconClass +'"></div>'; // retVal += '<div class="<API key>">' + title + '</div>'; // retVal += '</div>'; return '<p class="<API key> '+ iconClass + '">' + Ext.htmlEncode(title) + '</p>'; } }, { itemId: 'groups', header: 'Groups', dataIndex: 'groups', flex: 1, sortable: false, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { return '<div class="grid-text <API key>">' + value.length +'</div>'; } }, { itemId: 'widgets', header: 'Widgets', dataIndex: 'layoutConfig', flex: 1, sortable: false, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { var widgetCount = 0; if (value) { var countWidgets = function(cfg) { if(!cfg || !cfg.items) return; if(cfg.items.length === 0) { if(cfg.widgets && cfg.widgets.length > 0) { widgetCount += cfg.widgets.length; } } else { for(var i = 0, len = cfg.items.length; i < len; i++) { countWidgets(cfg.items[i]); } } return widgetCount; }; widgetCount = countWidgets(value); } return '<div class="grid-text <API key>">' + widgetCount +'</div>'; } } ] }); Ext.apply(this, { multiSelect: true, dockedItems: [Ext.create('Ext.toolbar.Paging', { dock: 'bottom', store: this.store, displayInfo: true, hidden: this.hidePagingToolbar, itemId: '<API key>' })] }); this.callParent(arguments); }, <API key>: function(){ return this.getSelectionModel().getSelection(); }, load: function() { this.store.loadPage(1); }, refresh: function() { this.store.loadPage(this.store.currentPage); }, getTopToolbar: function() { return this.getDockedItems('toolbar[dock="top"]')[0]; }, getBottomToolbar: function() { return this.getDockedItems('toolbar[dock="bottom"]')[0]; }, applyFilter: function(filterText, fields) { this.store.proxy.extraParams = undefined; if (filterText) { var filters = []; for (var i = 0; i < fields.length; i++) { filters.push({ filterField: fields[i], filterValue: filterText }); } this.store.proxy.extraParams = { filters: Ext.JSON.encode(filters), filterOperator: 'OR' }; } if (this.baseParams) { this.setBaseParams(this.baseParams); } this.store.loadPage(1,{ params: { offset: 0, max: this.store.pageSize } }); }, clearFilters: function() { this.store.proxy.extraParams = undefined; if (this.baseParams) { this.setBaseParams(this.baseParams); } this.store.load({ params: { start: 0, max: this.store.pageSize } }); }, setBaseParams: function(params) { this.baseParams = params; if (this.store.proxy.extraParams) { Ext.apply(this.store.proxy.extraParams, params); } else { this.store.proxy.extraParams = params; } }, setStore: function(store, cols) { this.reconfigure(store, cols); var pgtb = this.getBottomToolbar(); if (pgtb) { pgtb.bindStore(store); } } }); Ext.define('Ozone.components.admin.dashboard.<API key>', { extend: 'Ext.panel.Panel', alias: ['widget.<API key>', 'widget.dashboarddetail'], viewDashboard: null, loadedRecord: null, initComponent: function() { //init quicktips Ext.tip.QuickTipManager.init(true,{ dismissDelay: 60000, showDelay: 2000 }); this.viewDashboard = Ext.create('Ext.view.View', { store: Ext.create('Ext.data.Store', { storeId: 'storeDashboardItem', fields: [ { name: 'name', type: 'string' }, { name: 'layout', type: 'string' }, { name: '<API key>', type: 'string' }, { name: 'isGroupDashboard', type: 'boolean'}, { name: 'groups', model: 'Group'}, { name: 'description', type: 'string' }, { name: 'createdDate', type: 'string' }, { name: 'prettyCreatedDate', type: 'string' }, { name: 'editedDate', type: 'string' }, { name: 'prettyEditedDate', type: 'string' }, { name: 'createdBy', model: 'User' }, { name: 'stack', model: 'Stack'} ] }), deferEmptyText: false, tpl: new Ext.XTemplate( '<tpl for=".">', '<div class="selector">', '<div id="detail-info" class="detail-info">', '<div class="<API key>">', '{[this.renderIconBlock(values)]}', '</div>', '<div class="<API key>">', '<div class="detail-header-block">', '{[this.<API key>(values)]}', '</div>', '<div class="detail-block">', '<div><span class="detail-label">Description:</span> {description:htmlEncode}</span></div><br>', '<div><span class="detail-label">Groups:</span> {[this.renderGroups(values)]}</div>', '<div><span class="detail-label">Created:</span> <span {createdDate:this.renderToolTip}>{prettyCreatedDate:this.renderDate}</span></div>', '<div><span class="detail-label">Author:</span> {[this.renderUserRealName(values)]}</div>', '<div><span class="detail-label">Last Modified:</span> <span {editedDate:this.renderToolTip}>{prettyEditedDate:this.renderDate}</span></div>', '</div>', '</div>', '</div>', '</div>', '</tpl>', { compiled: true, renderDate: function(value) { return value ? value : ''; }, renderToolTip: function (value) { var str = 'data-qtip="' + value + '"'; return str; }, renderUserRealName: function(values) { var createdBy = values.createdBy; return (createdBy.userRealName ? Ext.htmlEncode(createdBy.userRealName) : '') }, renderGroups: function(values) { var groups = values.groups; var stack = values.stack; var retVal = ''; if (!stack && groups && groups.length > 0) { for (var i = -1; ++i < groups.length;) { retVal += Ext.htmlEncode(groups[i].name) + ', '; } retVal = retVal.substring(0, retVal.length - 2); } return retVal; }, renderIconBlock: function(values) { var iconClass = "<API key>"; var retVal = '<div class="dashboard-icon ' + iconClass + '"></div>'; return retVal; }, <API key>: function(values){ var isGroupDashboard = values.isGroupDashboard; var title = values.name; var retVal = '<div class="<API key>">'; retVal += '<div class="dashboard-title detail-title">' + Ext.htmlEncode(title) + '</div>'; retVal += (isGroupDashboard) ? '<div>This is a group dashboard.</div>' : ''; retVal += '</div>'; return retVal; } } ), emptyText: 'No dashboard selected', itemSelector: 'div.selector', autoScroll: 'true' }); this.items = [this.viewDashboard]; this.callParent(arguments); }, loadData: function(record) { this.viewDashboard.store.loadData([record], false); this.loadedRecord = record; }, removeData: function() { this.viewDashboard.store.removeAll(false); this.loadedRecord = null; } }); Ext.define('Ozone.components.admin.dashboard.<API key>', { extend: 'Ozone.components.admin.ManagementPanel', alias: ['widget.<API key>','widget.<API key>','widget.Ozone.components.admin.<API key>'], layout: 'fit', cls: '<API key>', gridDashboards: null, pnlDashboardDetail: null, txtHeading: null, lastAction: null, guid_EditCopyWidget: null, widgetStateHandler: null, dragAndDrop: true, launchesWidgets: true, channel: 'AdminChannel', defaultTitle: 'Group Dashboards', minButtonWidth: 80, detailsAutoOpen: true, initComponent: function() { var me = this; OWF.Preferences.getUserPreference({ namespace: 'owf.admin.DashboardEditCopy', name: 'guid_to_launch', onSuccess: function(result) { me.guid_EditCopyWidget = result.value; }, onFailure: function(err){ /* No op */ me.showAlert('Preferences Error', 'Error looking up Dashboard Editor: ' + err); } }); this.gridDashboards = Ext.create('Ozone.components.admin.grid.DashboardGroupsGrid', { preventHeader: true, region: 'center', border: false }); this.gridDashboards.setBaseParams({ adminEnabled: true, isGroupDashboard: true, isStackDashboard: false }); this.gridDashboards.store.load({ params: { offset: 0, max: this.pageSize } }); this.relayEvents(this.gridDashboards, ['datachanged', 'select', 'deselect', 'itemdblclick']); this.pnlDashboardDetail = Ext.create('Ozone.components.admin.dashboard.<API key>', { layout: { type: 'fit', align: 'stretch' }, region: 'east', preventHeader: true, collapseMode: 'mini', collapsible: true, collapsed: true, split: true, border: false, width: 266 }); this.txtHeading = Ext.create('Ext.toolbar.TextItem', { text: '<span class="heading-bold">'+this.defaultTitle+'</span>' }); this.searchBox = Ext.widget('searchbox'); this.items = [{ xtype: 'panel', layout: 'border', border: false, items: [ this.gridDashboards, this.pnlDashboardDetail ] }]; this.dockedItems = [{ xtype: 'toolbar', dock: 'top', layout: { type: 'hbox', align: 'stretchmax' }, items: [ this.txtHeading, { xtype: 'tbfill' }, this.searchBox ] }, { xtype: 'toolbar', dock: 'bottom', ui: 'footer', defaults: { minWidth: this.minButtonWidth }, items: [{ xtype: 'button', text: 'Create', handler: function(button, evt) { evt.stopPropagation(); me.doCreate(); } }, { xtype: 'button', text: 'Edit', handler: function() { me.doEdit(); } }, { xtype: 'button', text: 'Delete', handler: function(button) { me.doDelete(); } }] }]; this.gridDashboards.store.on( 'load', function(thisStore, records, options){ if ((this.pnlDashboardDetail != null ) && (!this.pnlDashboardDetail.collapsed) && (this.pnlDashboardDetail.loadedRecord != null)){ for(var idx=0; idx < records.length; idx++){ if(records[idx].id == this.pnlDashboardDetail.loadedRecord.id){ this.pnlDashboardDetail.loadData(records[idx]); break; } } } }, this ); this.on( 'datachanged', function(store, opts) { //collapse and clear detail panel if the store is refreshed if (this.pnlDashboardDetail != null ) { this.pnlDashboardDetail.collapse(); this.pnlDashboardDetail.removeData(); } //refresh launch menu if (!this.<API key>) { this.<API key>(); } }, this ); this.on( 'select', function(rowModel, record, index, opts) { this.pnlDashboardDetail.loadData(record); if (this.pnlDashboardDetail.collapsed && this.detailsAutoOpen) {this.pnlDashboardDetail.expand();} }, this ); this.searchBox.on( 'searchChanged', function(searchbox, value) { var grid = this.gridDashboards; if (grid) { if (!value) this.gridDashboards.clearFilters(); else this.gridDashboards.applyFilter(value, ['name', 'description']); } }, this ); this.on({ 'itemdblclick': { scope: this, fn: this.doEdit } }); this.gridDashboards.getView().on({ itemkeydown: { scope: this, fn: function(view, record, dom, index, evt) { switch(evt.getKey()) { case evt.SPACE: case evt.ENTER: this.doEdit(); } } } }); this.callParent(arguments); OWF.Eventing.subscribe('AdminChannel', owfdojo.hitch(this, function(sender, msg, channel) { if(msg.domain === 'Dashboard') { this.gridDashboards.getBottomToolbar().doRefresh(); } })); this.on( 'afterrender', function() { var splitterEl = this.el.down(".x-collapse-el"); splitterEl.on('click', function() { var collapsed = this.el.down(".<API key>"); if(collapsed) { this.detailsAutoOpen = true; } else { this.detailsAutoOpen = false; } }, this); }, this ); }, onLaunchFailed: function(response) { if (response.error) { this.showAlert('Launch Error', 'Dashboard Editor Launch Failed: ' + response.message); } }, doCreate: function() { var dataString = Ozone.util.toString({ copyFlag: false, isCreate: true, isGroupDashboard: true }); OWF.Launcher.launch({ guid: this.guid_EditCopyWidget, launchOnlyIfClosed: false, data: dataString }, this.onLaunchFailed); }, doEdit: function() { var records = this.gridDashboards.<API key>(); if (records && records.length > 0) { for (var i = 0; i < records.length; i++) { var id = records[i].getId();//From Id property of Dashboard Model var dataString = Ozone.util.toString({ id: id, copyFlag: false, isCreate: false, isGroupDashboard: true }); OWF.Launcher.launch({ title: '$1 - ' + records[i].get('name'), titleRegex: /(.*)/, guid: this.guid_EditCopyWidget, launchOnlyIfClosed: false, data: dataString }, this.onLaunchFailed); } } else { this.showAlert("Error", "You must select at least one dashboard to edit"); } }, doDelete: function() { var records = this.gridDashboards.getSelectionModel().getSelection(); if (records && records.length > 0) { var msg = 'This action will permanently delete '; if (records.length == 1) { msg += '<span class="heading-bold">' + Ext.htmlEncode(records[0].data.name) + '</span>.'; } else { msg += 'the selected <span class="heading-bold">' + records.length + ' dashboards</span>.'; } this.showConfirmation('Warning', msg, function(btn, text, opts) { if(btn == 'ok') { var store = this.gridDashboards.getStore(); store.remove(records); var remainingRecords = store.getTotalCount() - records.length; store.on({ write: { fn: function() { if(store.data.items.length == 0 && store.currentPage > 1) { var lastPage = store.<API key>(remainingRecords - 1); var pageToLoad = (lastPage >= store.currentPage) ? store.currentPage : lastPage; store.loadPage(pageToLoad); } this.gridDashboards.getBottomToolbar().doRefresh(); this.pnlDashboardDetail.removeData(); if(!this.pnlDashboardDetail.collapsed) { this.pnlDashboardDetail.collapse();} this.<API key>(); }, scope: this, single: true } }); store.save(); } }); } else { this.showAlert("Error", "You must select at least one dashboard to delete"); } } });
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.cpp Label Definition File: <API key>.label.xml Template File: sources-sink-45.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: file Read input from a file * GoodSource: Full path and file name * Sinks: fopen * BadSink : Open the file named in data using fopen() * Flow Variant: 45 Data flow: data passed as a static global variable from one function to another in the same source file * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #ifdef _WIN32 #define FOPEN _wfopen #else #define FOPEN fopen #endif namespace <API key> { static wchar_t * badData; static wchar_t * goodG2BData; #ifndef OMITBAD static void badSink() { wchar_t * data = badData; { FILE *pFile = NULL; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ pFile = FOPEN(data, L"wb+"); if (pFile != NULL) { fclose(pFile); } } } void bad() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; { /* Read input from a file */ size_t dataLen = wcslen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (<API key> > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgetws(data+dataLen, (int)(<API key>), pFile) == NULL) { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } fclose(pFile); } } } badData = data; badSink(); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSink() { wchar_t * data = goodG2BData; { FILE *pFile = NULL; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ pFile = FOPEN(data, L"wb+"); if (pFile != NULL) { fclose(pFile); } } } static void goodG2B() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; #ifdef _WIN32 /* FIX: Use a fixed, full path and file name */ wcscat(data, L"c:\\temp\\file.txt"); #else /* FIX: Use a fixed, full path and file name */ wcscat(data, L"/tmp/file.txt"); #endif goodG2BData = data; goodG2BSink(); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace <API key>; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.cpp Label Definition File: <API key>.label.xml Template File: sources-sinks-52b.tmpl.cpp */ /* * @description * CWE: 401 Memory Leak * BadSource: Allocate data using new * GoodSource: Allocate data on the stack * Sinks: * GoodSink: call delete on data * BadSink : no deallocation of data * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif namespace <API key> { #ifndef OMITBAD /* bad function declaration */ void badSink_c(twoIntsStruct * data); void badSink_b(twoIntsStruct * data) { badSink_c(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_c(twoIntsStruct * data); void goodG2BSink_b(twoIntsStruct * data) { goodG2BSink_c(data); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink_c(twoIntsStruct * data); void goodB2GSink_b(twoIntsStruct * data) { goodB2GSink_c(data); } #endif /* OMITGOOD */ } /* close namespace */
#include <config.h> #include <roken.h> #include <strsafe.h> #ifndef _WIN32 #error This implementation is Windows specific. #endif /** * <API key> waits for a process to terminate or until a * specified timeout occurs. * * @param[in] pid Process id for the monitored process * @param[in] func Timeout callback function. When the wait times out, * the callback function is called. The possible return values * from the callback function are: * * - ((time_t) -2) Exit loop without killing child and return SE_E_EXECTIMEOUT. * - ((time_t) -1) Kill child with SIGTERM and wait for child to exit. * - 0 Don't timeout again * - n Seconds to next timeout * * @param[in] ptr Optional parameter for func() * * @param[in] timeout Seconds to first timeout. * * @retval SE_E_UNSPECIFIED Unspecified system error * @retval SE_E_FORKFAILED Fork failure (not applicable for _WIN32 targets) * @retval SE_E_WAITPIDFAILED waitpid errors * @retval SE_E_EXECTIMEOUT exec timeout * @retval 0 <= Return value from subprocess * @retval SE_E_NOTFOUND The program coudln't be found * @retval 128- The signal that killed the subprocess +128. */ ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL <API key>(pid_t pid, time_t (*func)(void *), void *ptr, time_t timeout) { HANDLE hProcess; DWORD wrv = 0; DWORD dtimeout; int rv = 0; hProcess = OpenProcess(SYNCHRONIZE, FALSE, pid); if (hProcess == NULL) { return SE_E_WAITPIDFAILED; } dtimeout = (DWORD) ((timeout == 0)? INFINITE: timeout * 1000); do { wrv = WaitForSingleObject(hProcess, dtimeout); if (wrv == WAIT_OBJECT_0) { DWORD prv = 0; GetExitCodeProcess(hProcess, &prv); rv = (int) prv; break; } else if (wrv == WAIT_TIMEOUT) { if (func == NULL) continue; timeout = (*func)(ptr); if (timeout == (time_t)-1) { if (TerminateProcess(hProcess, 128 + 9)) { dtimeout = INFINITE; continue; } rv = SE_E_UNSPECIFIED; break; } else if (timeout == (time_t) -2) { rv = SE_E_EXECTIMEOUT; break; } else { dtimeout = (DWORD) ((timeout == 0)? INFINITE: timeout * 1000); continue; } } else { rv = SE_E_UNSPECIFIED; break; } } while(TRUE); CloseHandle(hProcess); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL wait_for_process(pid_t pid) { return <API key>(pid, NULL, NULL, 0); } static char * collect_commandline(const char * fn, va_list * ap) { size_t len = 0; size_t alloc_len = 0; const char * s; char * cmd = NULL; for (s = fn; s; s = (char *) va_arg(*ap, char *)) { size_t cmp_len; int need_quote = FALSE; if (FAILED(StringCchLength(s, MAX_PATH, &cmp_len))) { if (cmd) free(cmd); return NULL; } if (cmp_len == 0) continue; if (strchr(s, ' ') && /* need to quote any component that has embedded spaces, but not if they are already quoted. */ s[0] != '"' && s[cmp_len - 1] != '"') { need_quote = TRUE; cmp_len += 2 * sizeof(char); } if (s != fn) cmp_len += 1 * sizeof(char); if (alloc_len < len + cmp_len + 1) { char * nc; alloc_len += ((len + cmp_len - alloc_len) / MAX_PATH + 1) * MAX_PATH; nc = (char *) realloc(cmd, alloc_len * sizeof(char)); if (nc == NULL) { if (cmd) free(cmd); return NULL; } } if (cmd == NULL) return NULL; if (s != fn) cmd[len++] = ' '; if (need_quote) { StringCchPrintf(cmd + len, alloc_len - len, "\"%s\"", s); } else { StringCchCopy(cmd + len, alloc_len - len, s); } len += cmp_len; } return cmd; } ROKEN_LIB_FUNCTION pid_t ROKEN_LIB_CALL pipe_execv(FILE **stdin_fd, FILE **stdout_fd, FILE **stderr_fd, const char *file, ...) { HANDLE hOut_r = NULL; HANDLE hOut_w = NULL; HANDLE hIn_r = NULL; HANDLE hIn_w = NULL; HANDLE hErr_r = NULL; HANDLE hErr_w = NULL; SECURITY_ATTRIBUTES sa; STARTUPINFO si; PROCESS_INFORMATION pi; char * commandline = NULL; pid_t rv = (pid_t) -1; { va_list ap; va_start(ap, file); commandline = collect_commandline(file, &ap); if (commandline == NULL) return rv; } ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&sa, sizeof(sa)); pi.hProcess = NULL; pi.hThread = NULL; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.<API key> = NULL; if ((stdout_fd && !CreatePipe(&hOut_r, &hOut_w, &sa, 0 /* Use default */)) || (stdin_fd && !CreatePipe(&hIn_r, &hIn_w, &sa, 0)) || (stderr_fd && !CreatePipe(&hErr_r, &hErr_w, &sa, 0)) || (!stdout_fd && (hOut_w = CreateFile("CON", GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == <API key>) || (!stdin_fd && (hIn_r = CreateFile("CON",GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == <API key>) || (!stderr_fd && (hErr_w = CreateFile("CON", GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == <API key>)) goto _exit; /* We don't want the child processes inheriting these */ if (hOut_r) <API key>(hOut_r, HANDLE_FLAG_INHERIT, FALSE); if (hIn_w) <API key>(hIn_w, HANDLE_FLAG_INHERIT, FALSE); if (hErr_r) <API key>(hErr_r, HANDLE_FLAG_INHERIT, FALSE); si.cb = sizeof(si); si.lpReserved = NULL; si.lpDesktop = NULL; si.lpTitle = NULL; si.dwFlags = <API key>; si.hStdInput = hIn_r; si.hStdOutput = hOut_w; si.hStdError = hErr_w; if (!CreateProcess(file, commandline, NULL, NULL, TRUE, /* bInheritHandles */ CREATE_NO_WINDOW, /* dwCreationFlags */ NULL, /* lpEnvironment */ NULL, /* lpCurrentDirectory */ &si, &pi)) { rv = (pid_t) (GetLastError() == <API key>)? 127 : -1; goto _exit; } if (stdin_fd) { *stdin_fd = _fdopen(_open_osfhandle((intptr_t) hIn_w, 0), "wb"); if (*stdin_fd) hIn_w = NULL; } if (stdout_fd) { *stdout_fd = _fdopen(_open_osfhandle((intptr_t) hOut_r, _O_RDONLY), "rb"); if (*stdout_fd) hOut_r = NULL; } if (stderr_fd) { *stderr_fd = _fdopen(_open_osfhandle((intptr_t) hErr_r, _O_RDONLY), "rb"); if (*stderr_fd) hErr_r = NULL; } rv = (pid_t) pi.dwProcessId; _exit: if (pi.hProcess) CloseHandle(pi.hProcess); if (pi.hThread) CloseHandle(pi.hThread); if (hIn_r) CloseHandle(hIn_r); if (hIn_w) CloseHandle(hIn_w); if (hOut_r) CloseHandle(hOut_r); if (hOut_w) CloseHandle(hOut_w); if (hErr_r) CloseHandle(hErr_r); if (hErr_w) CloseHandle(hErr_w); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execvp_timed(const char *file, char *const args[], time_t (*func)(void *), void *ptr, time_t timeout) { intptr_t hp; int rv; hp = spawnvp(_P_NOWAIT, file, args); if (hp == -1) return (errno == ENOENT)? 127: 126; else if (hp == 0) return 0; rv = <API key>(GetProcessId((HANDLE) hp), func, ptr, timeout); CloseHandle((HANDLE) hp); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execvp(const char *file, char *const args[]) { return simple_execvp_timed(file, args, NULL, NULL, 0); } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execve_timed(const char *file, char *const args[], char *const envp[], time_t (*func)(void *), void *ptr, time_t timeout) { intptr_t hp; int rv; hp = spawnve(_P_NOWAIT, file, args, envp); if (hp == -1) return (errno == ENOENT)? 127: 126; else if (hp == 0) return 0; rv = <API key>(GetProcessId((HANDLE) hp), func, ptr, timeout); CloseHandle((HANDLE) hp); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execve(const char *file, char *const args[], char *const envp[]) { return simple_execve_timed(file, args, envp, NULL, NULL, 0); } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execlp(const char *file, ...) { va_list ap; char **argv; int ret; va_start(ap, file); argv = vstrcollect(&ap); va_end(ap); if(argv == NULL) return SE_E_UNSPECIFIED; ret = simple_execvp(file, argv); free(argv); return ret; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execle(const char *file, ... /* ,char *const envp[] */) { va_list ap; char **argv; char *const* envp; int ret; va_start(ap, file); argv = vstrcollect(&ap); envp = va_arg(ap, char **); va_end(ap); if(argv == NULL) return SE_E_UNSPECIFIED; ret = simple_execve(file, argv, envp); free(argv); return ret; }
#ifndef <API key> #ifndef _LIBLINEAR_H #define _LIBLINEAR_H #include <shogun/lib/config.h> #include <shogun/optimization/liblinear/tron.h> #include <shogun/features/DotFeatures.h> namespace shogun { #undef I #ifdef __cplusplus extern "C" { #endif /** problem */ struct liblinear_problem { int32_t l; int32_t n; float64_t* y; /** sparse features x */ std::shared_ptr<DotFeatures> x; /** if bias shall be used */ bool use_bias; }; /** parameter */ struct liblinear_parameter { /** solver type */ int32_t solver_type; /* these are for training only */ /** stopping criteria */ float64_t eps; float64_t C; /** number of weights */ int32_t nr_weight; /** weight label */ int32_t *weight_label; /** weight */ float64_t* weight; }; /** model */ struct liblinear_model { /** parameter */ struct liblinear_parameter param; /** number of classes */ int32_t nr_class; /** number of features */ int32_t nr_feature; float64_t *w; /** label of each class (label[n]) */ int32_t *label; /** bias */ float64_t bias; }; void destroy_model(struct liblinear_model *model_); void destroy_param(struct liblinear_parameter *param); #ifdef __cplusplus } #endif /** class l2loss_svm_vun */ class l2loss_svm_fun : public function { public: /** constructor * * @param prob prob * @param Cp Cp * @param Cn Cn */ l2loss_svm_fun(const liblinear_problem *prob, float64_t Cp, float64_t Cn); ~l2loss_svm_fun(); /** fun * * @param w w * @return something floaty */ float64_t fun(float64_t *w); /** grad * * @param w w * @param g g */ void grad(float64_t *w, float64_t *g); /** Hv * * @param s s * @param Hs Hs */ void Hv(float64_t *s, float64_t *Hs); /** get number of variables * * @return number of variables */ int32_t get_nr_variable(); private: void Xv(float64_t *v, float64_t *Xv); void subXv(float64_t *v, float64_t *Xv); void subXTv(float64_t *v, float64_t *XTv); float64_t *C; float64_t *z; float64_t *D; int32_t *I; int32_t sizeI; const liblinear_problem *prob; }; /** class l2r_lr_fun */ class l2r_lr_fun : public function { public: /** constructor * * @param prob prob * @param Cp Cp * @param Cn Cn */ l2r_lr_fun(const liblinear_problem *prob, float64_t* C); ~l2r_lr_fun(); /** fun * * @param w w * @return something floaty */ float64_t fun(float64_t *w); /** grad * * @param w w * @param g g */ void grad(float64_t *w, float64_t *g); /** Hv * * @param s s * @param Hs Hs */ void Hv(float64_t *s, float64_t *Hs); int32_t get_nr_variable(); private: void Xv(float64_t *v, float64_t *Xv); void XTv(float64_t *v, float64_t *XTv); float64_t *C; float64_t *z; float64_t *D; const liblinear_problem *m_prob; }; class l2r_l2_svc_fun : public function { public: l2r_l2_svc_fun(const liblinear_problem *prob, float64_t* Cs); ~l2r_l2_svc_fun(); double fun(double *w); void grad(double *w, double *g); void Hv(double *s, double *Hs); int get_nr_variable(); protected: void Xv(double *v, double *Xv); void subXv(double *v, double *Xv); void subXTv(double *v, double *XTv); double *C; double *z; double *D; int *I; int sizeI; const liblinear_problem *m_prob; }; class l2r_l2_svr_fun: public l2r_l2_svc_fun { public: l2r_l2_svr_fun(const liblinear_problem *prob, double *Cs, double p); double fun(double *w); void grad(double *w, double *g); private: double m_p; }; struct mcsvm_state { double* w; double* B; double* G; double* alpha; double* alpha_new; int* index; double* QD; int* d_ind; double* d_val; int* alpha_index; int* y_index; int* active_size_i; bool allocated,inited; mcsvm_state() { w = NULL; B = NULL; G = NULL; alpha = NULL; alpha_new = NULL; index = NULL; QD = NULL; d_ind = NULL; d_val = NULL; alpha_index = NULL; y_index = NULL; active_size_i = NULL; allocated = false; inited = false; } ~mcsvm_state() { SG_FREE(w); SG_FREE(B); SG_FREE(G); SG_FREE(alpha); SG_FREE(alpha_new); SG_FREE(index); SG_FREE(QD); SG_FREE(d_ind); SG_FREE(d_val); SG_FREE(alpha_index); SG_FREE(y_index); SG_FREE(active_size_i); } }; class Solver_MCSVM_CS { public: Solver_MCSVM_CS(const liblinear_problem *prob, int nr_class, double *C, double *w0, double eps, int max_iter, double train_time, mcsvm_state* given_state); ~Solver_MCSVM_CS(); template <typename PRNG> void solve(PRNG& prng); private: void solve_sub_problem(double A_i, int yi, double C_yi, int active_i, double *alpha_new); bool be_shrunk(int i, int m, int yi, double alpha_i, double minG); double *C; int w_size, l; int nr_class; int max_iter; double eps; double max_train_time; double* w0; const liblinear_problem *prob; mcsvm_state* state; }; } #endif //_LIBLINEAR_H #endif // <API key>
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.c Label Definition File: <API key>.label.xml Template File: sources-sink-22a.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sink: memcpy * BadSink : Copy twoIntsStruct array to data using memcpy * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources. * * */ #include "std_testcase.h" #ifndef OMITBAD /* The global variable below is used to drive control flow in the source function */ int <API key> = 0; twoIntsStruct * <API key>(twoIntsStruct * data); void <API key>() { twoIntsStruct * data; data = NULL; <API key> = 1; /* true */ data = <API key>(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* The global variables below are used to drive control flow in the source functions. */ int <API key> = 0; int <API key> = 0; /* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */ twoIntsStruct * <API key>(twoIntsStruct * data); static void goodG2B1() { twoIntsStruct * data; data = NULL; <API key> = 0; /* false */ data = <API key>(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */ twoIntsStruct * <API key>(twoIntsStruct * data); static void goodG2B2() { twoIntsStruct * data; data = NULL; <API key> = 1; /* true */ data = <API key>(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } void <API key>() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); <API key>(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); <API key>(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
#include "chrome/browser/chromeos/login/users/<API key>.h" #include <cstddef> #include <set> #include "ash/multi_profile_uma.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/prefs/<API key>.h" #include "base/prefs/pref_service.h" #include "base/prefs/<API key>.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/<API key>.h" #include "base/<API key>.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/<API key>.h" #include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h" #include "chrome/browser/chromeos/login/session/<API key>.h" #include "chrome/browser/chromeos/login/signin/auth_sync_observer.h" #include "chrome/browser/chromeos/login/signin/<API key>.h" #include "chrome/browser/chromeos/login/users/avatar/<API key>.h" #include "chrome/browser/chromeos/login/users/<API key>.h" #include "chrome/browser/chromeos/login/users/<API key>.h" #include "chrome/browser/chromeos/policy/<API key>.h" #include "chrome/browser/chromeos/policy/<API key>.h" #include "chrome/browser/chromeos/profiles/<API key>.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/<API key>.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/supervised_user/chromeos/manager_<API key>.h" #include "chrome/browser/supervised_user/chromeos/supervised_user_<API key>.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/crash_keys.h" #include "chrome/common/pref_names.h" #include "chrome/grit/theme_resources.h" #include "chromeos/chromeos_switches.h" #include "chromeos/login/user_names.h" #include "chromeos/settings/cros_settings_names.h" #include "components/session_manager/core/session_manager.h" #include "components/user_manager/<API key>.h" #include "components/user_manager/user_image/user_image.h" #include "components/user_manager/user_type.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/<API key>.h" #include "policy/policy_constants.h" #include "ui/base/resource/resource_bundle.h" #include "ui/wm/core/wm_core_switches.h" using content::BrowserThread; namespace chromeos { namespace { // A vector pref of the the regular users known on this device, arranged in LRU // order. const char kRegularUsers[] = "LoggedInUsers"; // A vector pref of the public accounts defined on this device. const char kPublicAccounts[] = "PublicAccounts"; // A string pref that gets set when a public account is removed but a user is // currently logged into that account, requiring the account's data to be // removed after logout. const char <API key>[] = "<API key>"; } // namespace // static void <API key>::RegisterPrefs(PrefRegistrySimple* registry) { ChromeUserManager::RegisterPrefs(registry); registry->RegisterListPref(kPublicAccounts); registry->RegisterStringPref(<API key>, std::string()); <API key>::RegisterPrefs(registry); <API key>::RegisterPrefs(registry); } // static scoped_ptr<ChromeUserManager> <API key>::<API key>() { return scoped_ptr<ChromeUserManager>(new <API key>()); } <API key>::<API key>() : ChromeUserManager(base::<API key>::Get(), BrowserThread::GetBlockingPool()), cros_settings_(CrosSettings::Get()), <API key>(NULL), <API key>(new <API key>(this)), weak_factory_(this) { UpdateNumberOfUsers(); // UserManager instance should be used only on UI thread. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); registrar_.Add(this, chrome::<API key>, content::NotificationService::AllSources()); registrar_.Add(this, chrome::<API key>, content::NotificationService::AllSources()); registrar_.Add(this, chrome::<API key>, content::NotificationService::AllSources()); // Since we're in ctor postpone any actions till this is fully created. if (base::MessageLoop::current()) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&<API key>::<API key>, weak_factory_.GetWeakPtr())); } <API key> = cros_settings_->AddSettingsObserver( <API key>, base::Bind(&<API key>::<API key>, weak_factory_.GetWeakPtr())); <API key>.reset( new <API key>(this, GetLocalState())); policy::<API key>* connector = g_browser_process->platform_part()-><API key>(); <API key>.reset(new policy::<API key>( cros_settings_, connector-><API key>(), policy::key::kUserAvatarImage, this)); <API key>->Init(); <API key>.reset(new policy::<API key>( cros_settings_, connector-><API key>(), policy::key::kWallpaperImage, this)); <API key>->Init(); } <API key>::~<API key>() { } void <API key>::Shutdown() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::Shutdown(); <API key>.reset(); // Stop the session length limiter. <API key>.reset(); if (<API key>) <API key>->RemoveObserver(this); for (UserImageManagerMap::iterator it = <API key>.begin(), ie = <API key>.end(); it != ie; ++it) { it->second->Shutdown(); } <API key>.reset(); <API key>.reset(); <API key>.reset(); registrar_.RemoveAll(); } <API key>* <API key>::<API key>() { return <API key>.get(); } UserImageManager* <API key>::GetUserImageManager( const std::string& user_id) { UserImageManagerMap::iterator ui = <API key>.find(user_id); if (ui != <API key>.end()) return ui->second.get(); linked_ptr<<API key>> mgr(new <API key>(user_id, this)); <API key>[user_id] = mgr; return mgr.get(); } <API key>* <API key>::<API key>() { return <API key>.get(); } user_manager::UserList <API key>::<API key>() const { // Supervised users are not allowed to use multi-profiles. if (GetLoggedInUsers().size() == 1 && GetPrimaryUser()->GetType() != user_manager::USER_TYPE_REGULAR) { return user_manager::UserList(); } user_manager::UserList result; const user_manager::UserList& users = GetUsers(); for (user_manager::UserList::const_iterator it = users.begin(); it != users.end(); ++it) { if ((*it)->GetType() == user_manager::USER_TYPE_REGULAR && !(*it)->is_logged_in()) { <API key>::<API key> check; <API key>-><API key>((*it)->email(), &check); if (check == <API key>::<API key>) { return user_manager::UserList(); } // Users with a policy that prevents them being added to a session will be // shown in login UI but will be grayed out. if (check == <API key>::ALLOWED || check == <API key>::<API key> || check == <API key>::<API key> || check == <API key>::<API key>) { result.push_back(*it); } } } return result; } user_manager::UserList <API key>::GetUnlockUsers() const { const user_manager::UserList& logged_in_users = GetLoggedInUsers(); if (logged_in_users.empty()) return user_manager::UserList(); user_manager::UserList unlock_users; Profile* profile = ProfileHelper::Get()-><API key>(GetPrimaryUser()); std::string primary_behavior = profile->GetPrefs()->GetString(prefs::<API key>); // Specific case: only one logged in user or // primary user has primary-only multi-profile policy. if (logged_in_users.size() == 1 || primary_behavior == <API key>::<API key>) { if (GetPrimaryUser()->can_lock()) unlock_users.push_back(primary_user_); } else { // Fill list of potential unlock users based on multi-profile policy state. for (user_manager::UserList::const_iterator it = logged_in_users.begin(); it != logged_in_users.end(); ++it) { user_manager::User* user = (*it); Profile* profile = ProfileHelper::Get()-><API key>(user); const std::string behavior = profile->GetPrefs()->GetString(prefs::<API key>); if (behavior == <API key>::<API key> && user->can_lock()) { unlock_users.push_back(user); } else if (behavior == <API key>::<API key>) { NOTREACHED() << "Spotted primary-only multi-profile policy for non-primary user"; } } } return unlock_users; } void <API key>::SessionStarted() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::SessionStarted(); content::NotificationService::current()->Notify( chrome::<API key>, content::Source<UserManager>(this), content::Details<const user_manager::User>(GetActiveUser())); } void <API key>::RemoveUserInternal( const std::string& user_email, user_manager::RemoveUserDelegate* delegate) { CrosSettings* cros_settings = CrosSettings::Get(); const base::Closure& callback = base::Bind(&<API key>::RemoveUserInternal, weak_factory_.GetWeakPtr(), user_email, delegate); // Ensure the value of owner email has been fetched. if (<API key>::TRUSTED != cros_settings-><API key>(callback)) { // Value of owner email is not fetched yet. RemoveUserInternal will be // called again after fetch completion. return; } std::string owner; cros_settings->GetString(kDeviceOwner, &owner); if (user_email == owner) { // Owner is not allowed to be removed from the device. return; } <API key>(user_email, delegate); } void <API key>::SaveUserOAuthStatus( const std::string& user_id, user_manager::User::OAuthTokenStatus oauth_token_status) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::SaveUserOAuthStatus(user_id, oauth_token_status); GetUserFlow(user_id)->HandleO<API key>(oauth_token_status); } void <API key>::SaveUserDisplayName( const std::string& user_id, const base::string16& display_name) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::SaveUserDisplayName(user_id, display_name); // Do not update local state if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. if (!<API key>(user_id)) <API key>->UpdateManagerName(user_id, display_name); } void <API key>::<API key>() { <API key>.reset(); <API key>.reset(); } void <API key>::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::<API key>: if (!<API key>) { policy::<API key>* connector = g_browser_process->platform_part() -><API key>(); <API key> = connector-><API key>(); if (<API key>) <API key>->AddObserver(this); } <API key>(); UpdateOwnership(); break; case chrome::<API key>: { Profile* profile = content::Details<Profile>(details).ptr(); if (IsUserLoggedIn() && !IsLoggedInAsGuest() && !<API key>()) { if (<API key>()) <API key>::GetForProfile(profile); if (<API key>()) <API key>::GetForProfile(profile); if (!profile->IsOffTheRecord()) { AuthSyncObserver* sync_observer = <API key>::GetInstance()->GetForProfile(profile); sync_observer->StartObserving(); <API key>->StartObserving(profile); } } break; } case chrome::<API key>: { Profile* profile = content::Source<Profile>(source).ptr(); user_manager::User* user = ProfileHelper::Get()->GetUserByProfile(profile); if (user != NULL) user-><API key>(); // If there is pending user switch, do it now. if (!<API key>().empty()) { // Call SwitchActiveUser async because otherwise it may cause // ProfileManager::GetProfile before the profile gets registered // in ProfileManager. It happens in case of sync profile load when // <API key> is called synchronously. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&<API key>::SwitchActiveUser, weak_factory_.GetWeakPtr(), <API key>())); <API key>(std::string()); } break; } default: NOTREACHED(); } } void <API key>::OnExternalDataSet(const std::string& policy, const std::string& user_id) { if (policy == policy::key::kUserAvatarImage) GetUserImageManager(user_id)->OnExternalDataSet(policy); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicySet(policy, user_id); else NOTREACHED(); } void <API key>::<API key>(const std::string& policy, const std::string& user_id) { if (policy == policy::key::kUserAvatarImage) GetUserImageManager(user_id)-><API key>(policy); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicyCleared(policy, user_id); else NOTREACHED(); } void <API key>::<API key>( const std::string& policy, const std::string& user_id, scoped_ptr<std::string> data) { if (policy == policy::key::kUserAvatarImage) GetUserImageManager(user_id)-><API key>(policy, data.Pass()); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicyFetched(policy, user_id, data.Pass()); else NOTREACHED(); } void <API key>::OnPolicyUpdated(const std::string& user_id) { const user_manager::User* user = FindUser(user_id); if (!user || user->GetType() != user_manager::<API key>) return; <API key>(user_id); } void <API key>::<API key>() { // No action needed here, changes to the list of device-local accounts get // handled via the <API key> device setting observer. } bool <API key>::CanCurrentUserLock() const { return ChromeUserManager::CanCurrentUserLock() && GetCurrentUserFlow()->CanLockScreen(); } bool <API key>::<API key>( const std::string& user_id) const { // Data belonging to the obsolete public accounts whose data has not been // removed yet is not ephemeral. bool <API key> = <API key>(user_id); return !<API key> && ChromeUserManager::<API key>(user_id); } bool <API key>::<API key>() const { policy::<API key>* connector = g_browser_process->platform_part()-><API key>(); return <API key>() && (connector->IsEnterpriseManaged() || !GetOwnerEmail().empty()); } const std::string& <API key>::<API key>() const { return g_browser_process-><API key>(); } PrefService* <API key>::GetLocalState() const { return g_browser_process ? g_browser_process->local_state() : NULL; } void <API key>::HandleUserO<API key>( const std::string& user_id, user_manager::User::OAuthTokenStatus status) const { GetUserFlow(user_id)->HandleO<API key>(status); } bool <API key>::IsEnterpriseManaged() const { policy::<API key>* connector = g_browser_process->platform_part()-><API key>(); return connector->IsEnterpriseManaged(); } void <API key>::LoadPublicAccounts( std::set<std::string>* public_sessions_set) { const base::ListValue* <API key> = GetLocalState()->GetList(kPublicAccounts); std::vector<std::string> public_sessions; ParseUserList(*<API key>, std::set<std::string>(), &public_sessions, public_sessions_set); for (std::vector<std::string>::const_iterator it = public_sessions.begin(); it != public_sessions.end(); ++it) { users_.push_back(user_manager::User::<API key>(*it)); <API key>(*it); } } void <API key>::<API key>() { // Clean up user list first. All code down the path should be synchronous, // so that local state after transaction rollback is in consistent state. // This process also should not trigger EnsureUsersLoaded again. if (<API key>-><API key>()) <API key>-><API key>(); } void <API key>::<API key>() { for (user_manager::UserList::iterator ui = users_.begin(), ue = users_.end(); ui != ue; ++ui) { GetUserImageManager((*ui)->email())->LoadUserImage(); } } void <API key>::<API key>( bool browser_restart) { // Initialize the session length limiter and start it only if // session limit is defined by the policy. <API key>.reset( new <API key>(NULL, browser_restart)); } bool <API key>::IsDemoApp(const std::string& user_id) const { return DemoAppLauncher::IsDemoAppSession(user_id); } bool <API key>::IsKioskApp(const std::string& user_id) const { policy::DeviceLocalAccount::Type <API key>; return policy::<API key>(user_id, &<API key>) && <API key> == policy::DeviceLocalAccount::TYPE_KIOSK_APP; } bool <API key>::<API key>( const std::string& user_id) const { return user_id == GetLocalState()->GetString(<API key>); } void <API key>::<API key>() { // Local state may not be initialized in unit_tests. if (!GetLocalState()) return; <API key>(false); SetOwnerEmail(std::string()); // Schedule a callback if device policy has not yet been verified. if (<API key>::TRUSTED != cros_settings_-><API key>( base::Bind(&<API key>::<API key>, weak_factory_.GetWeakPtr()))) { return; } bool <API key> = false; cros_settings_->GetBoolean(<API key>, &<API key>); <API key>(<API key>); std::string owner_email; cros_settings_->GetString(kDeviceOwner, &owner_email); SetOwnerEmail(owner_email); EnsureUsersLoaded(); bool changed = <API key>( policy::<API key>(cros_settings_)); // If ephemeral users are enabled and we are on the login screen, take this // opportunity to clean up by removing all regular users except the owner. if (<API key>() && !IsUserLoggedIn()) { ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers); prefs_users_update->Clear(); for (user_manager::UserList::iterator it = users_.begin(); it != users_.end();) { const std::string user_email = (*it)->email(); if ((*it)->GetType() == user_manager::USER_TYPE_REGULAR && user_email != GetOwnerEmail()) { <API key>(user_email); DeleteUser(*it); it = users_.erase(it); changed = true; } else { if ((*it)->GetType() != user_manager::<API key>) prefs_users_update->Append(new base::StringValue(user_email)); ++it; } } } if (changed) <API key>(); } void <API key>::GuestUserLoggedIn() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::GuestUserLoggedIn(); // TODO(nkostylev): Add support for passing guest session cryptohome // mount point. Legacy (--login-profile) value will be used for now. active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( <API key>)), user_manager::User::USER_IMAGE_INVALID, false); // Initializes wallpaper after active_user_ is set. WallpaperManager::Get()->SetUserWallpaperNow(chromeos::login::kGuestUserName); } void <API key>::RegularUserLoggedIn(const std::string& user_id) { ChromeUserManager::RegularUserLoggedIn(user_id); if (IsCurrentUserNew()) WallpaperManager::Get()->SetUserWallpaperNow(user_id); GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false); WallpaperManager::Get()-><API key>(); // Make sure that new data is persisted to Local State. GetLocalState()->CommitPendingWrite(); } void <API key>::<API key>( const std::string& user_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::<API key>(user_id); GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false); WallpaperManager::Get()->SetUserWallpaperNow(user_id); } void <API key>::<API key>(const std::string& user_id) { // TODO(nkostylev): Refactor, share code with RegularUserLoggedIn(). // Remove the user from the user list. active_user_ = <API key>(user_id); // If the user was not found on the user list, create a new user. if (!GetActiveUser()) { SetIsCurrentUserNew(true); active_user_ = user_manager::User::<API key>(user_id); // Leaving OAuth token status at the default state = unknown. WallpaperManager::Get()->SetUserWallpaperNow(user_id); } else { if (<API key>->CheckForFirstRun(user_id)) { SetIsCurrentUserNew(true); WallpaperManager::Get()->SetUserWallpaperNow(user_id); } else { SetIsCurrentUserNew(false); } } // Add the user to the front of the user list. ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers); prefs_users_update->Insert(0, new base::StringValue(user_id)); users_.insert(users_.begin(), active_user_); // Now that user is in the list, save display name. if (IsCurrentUserNew()) { SaveUserDisplayName(GetActiveUser()->email(), GetActiveUser()->GetDisplayName()); } GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), true); WallpaperManager::Get()-><API key>(); // Make sure that new data is persisted to Local State. GetLocalState()->CommitPendingWrite(); } void <API key>::<API key>( user_manager::User* user) { SetIsCurrentUserNew(true); active_user_ = user; // The UserImageManager chooses a random avatar picture when a user logs in // for the first time. Tell the UserImageManager that this user is not new to // prevent the avatar from getting changed. GetUserImageManager(user->email())->UserLoggedIn(false, true); WallpaperManager::Get()-><API key>(); } void <API key>::KioskAppLoggedIn(const std::string& app_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); policy::DeviceLocalAccount::Type <API key>; DCHECK(policy::<API key>(app_id, &<API key>)); DCHECK_EQ(policy::DeviceLocalAccount::TYPE_KIOSK_APP, <API key>); active_user_ = user_manager::User::CreateKioskAppUser(app_id); active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( <API key>)), user_manager::User::USER_IMAGE_INVALID, false); WallpaperManager::Get()->SetUserWallpaperNow(app_id); // TODO(bartfab): Add KioskAppUsers to the users_ list and keep metadata like // the kiosk_app_id in these objects, removing the need to re-parse the // device-local account list here to extract the kiosk_app_id. const std::vector<policy::DeviceLocalAccount> <API key> = policy::<API key>(cros_settings_); const policy::DeviceLocalAccount* account = NULL; for (std::vector<policy::DeviceLocalAccount>::const_iterator it = <API key>.begin(); it != <API key>.end(); ++it) { if (it->user_id == app_id) { account = &*it; break; } } std::string kiosk_app_id; if (account) { kiosk_app_id = account->kiosk_app_id; } else { LOG(ERROR) << "Logged into nonexistent kiosk-app account: " << app_id; NOTREACHED(); } CommandLine* command_line = CommandLine::ForCurrentProcess(); command_line->AppendSwitch(::switches::kForceAppMode); command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_id); // Disable window animation since kiosk app runs in a single full screen // window and window animation causes start-up janks. command_line->AppendSwitch(wm::switches::<API key>); } void <API key>::DemoAccountLoggedIn() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); active_user_ = user_manager::User::CreateKioskAppUser(DemoAppLauncher::kDemoUserName); active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( <API key>)), user_manager::User::USER_IMAGE_INVALID, false); WallpaperManager::Get()->SetUserWallpaperNow(DemoAppLauncher::kDemoUserName); CommandLine* command_line = CommandLine::ForCurrentProcess(); command_line->AppendSwitch(::switches::kForceAppMode); command_line->AppendSwitchASCII(::switches::kAppId, DemoAppLauncher::kDemoAppId); // Disable window animation since the demo app runs in a single full screen // window and window animation causes start-up janks. CommandLine::ForCurrentProcess()->AppendSwitch( wm::switches::<API key>); } void <API key>::<API key>() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); SetIsCurrentUserNew(true); active_user_ = user_manager::User::<API key>(); GetUserImageManager(chromeos::login::kRetailModeUserName) ->UserLoggedIn(IsCurrentUserNew(), true); WallpaperManager::Get()->SetUserWallpaperNow( chromeos::login::kRetailModeUserName); } void <API key>::NotifyOnLogin() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); UserSessionManager::OverrideHomedir(); UpdateNumberOfUsers(); ChromeUserManager::NotifyOnLogin(); // TODO(nkostylev): Deprecate this notification in favor of // ActiveUserChanged() observer call. content::NotificationService::current()->Notify( chrome::<API key>, content::Source<UserManager>(this), content::Details<const user_manager::User>(GetActiveUser())); UserSessionManager::GetInstance()-><API key>(); } void <API key>::UpdateOwnership() { bool is_owner = <API key>::Get()->HasPrivateOwnerKey(); VLOG(1) << "Current user " << (is_owner ? "is owner" : "is not owner"); <API key>(is_owner); } void <API key>::<API key>( const std::string& user_id) { ChromeUserManager::<API key>(user_id); WallpaperManager::Get()-><API key>(user_id); GetUserImageManager(user_id)->DeleteUserImage(); <API key>-><API key>(user_id); <API key>->RemoveCachedValues(user_id); } void <API key>::<API key>() { PrefService* local_state = GetLocalState(); const std::string <API key> = local_state->GetString(<API key>); if (<API key>.empty() || (IsUserLoggedIn() && <API key> == GetActiveUser()->email())) { return; } <API key>(<API key>); local_state->ClearPref(<API key>); } void <API key>::<API key>( const std::vector<std::string>& old_public_accounts) { std::set<std::string> users; for (user_manager::UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) users.insert((*it)->email()); // If the user is logged into a public account that has been removed from the // user list, mark the account's data as pending removal after logout. if (<API key>()) { const std::string active_user_id = GetActiveUser()->email(); if (users.find(active_user_id) == users.end()) { GetLocalState()->SetString(<API key>, active_user_id); users.insert(active_user_id); } } // Remove the data belonging to any other public accounts that are no longer // found on the user list. for (std::vector<std::string>::const_iterator it = old_public_accounts.begin(); it != old_public_accounts.end(); ++it) { if (users.find(*it) == users.end()) <API key>(*it); } } bool <API key>::<API key>( const std::vector<policy::DeviceLocalAccount>& <API key>) { // Try to remove any public account data marked as pending removal. <API key>(); // Get the current list of public accounts. std::vector<std::string> old_public_accounts; for (user_manager::UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) { if ((*it)->GetType() == user_manager::<API key>) old_public_accounts.push_back((*it)->email()); } // Get the new list of public accounts from policy. std::vector<std::string> new_public_accounts; for (std::vector<policy::DeviceLocalAccount>::const_iterator it = <API key>.begin(); it != <API key>.end(); ++it) { // TODO(mnissler, nkostylev, bartfab): Process Kiosk Apps within the if (it->type == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION) new_public_accounts.push_back(it->user_id); } // If the list of public accounts has not changed, return. if (new_public_accounts.size() == old_public_accounts.size()) { bool changed = false; for (size_t i = 0; i < new_public_accounts.size(); ++i) { if (new_public_accounts[i] != old_public_accounts[i]) { changed = true; break; } } if (!changed) return false; } // Persist the new list of public accounts in a pref. ListPrefUpdate <API key>(GetLocalState(), kPublicAccounts); <API key>->Clear(); for (std::vector<std::string>::const_iterator it = new_public_accounts.begin(); it != new_public_accounts.end(); ++it) { <API key>->AppendString(*it); } // Remove the old public accounts from the user list. for (user_manager::UserList::iterator it = users_.begin(); it != users_.end();) { if ((*it)->GetType() == user_manager::<API key>) { if (*it != GetLoggedInUser()) DeleteUser(*it); it = users_.erase(it); } else { ++it; } } // Add the new public accounts to the front of the user list. for (std::vector<std::string>::<API key> it = new_public_accounts.rbegin(); it != new_public_accounts.rend(); ++it) { if (<API key>() && *it == GetActiveUser()->email()) users_.insert(users_.begin(), GetLoggedInUser()); else users_.insert(users_.begin(), user_manager::User::<API key>(*it)); <API key>(*it); } for (user_manager::UserList::iterator ui = users_.begin(), ue = users_.begin() + new_public_accounts.size(); ui != ue; ++ui) { GetUserImageManager((*ui)->email())->LoadUserImage(); } // Remove data belonging to public accounts that are no longer found on the // user list. <API key>(old_public_accounts); return true; } void <API key>::<API key>( const std::string& user_id) { std::string display_name; if (<API key>) { policy::<API key>* broker = <API key>->GetBrokerForUser(user_id); if (broker) display_name = broker->GetDisplayName(); } // Set or clear the display name. SaveUserDisplayName(user_id, base::UTF8ToUTF16(display_name)); } UserFlow* <API key>::GetCurrentUserFlow() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!IsUserLoggedIn()) return GetDefaultUserFlow(); return GetUserFlow(GetLoggedInUser()->email()); } UserFlow* <API key>::GetUserFlow(const std::string& user_id) const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FlowMap::const_iterator it = specific_flows_.find(user_id); if (it != specific_flows_.end()) return it->second; return GetDefaultUserFlow(); } void <API key>::SetUserFlow(const std::string& user_id, UserFlow* flow) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ResetUserFlow(user_id); specific_flows_[user_id] = flow; } void <API key>::ResetUserFlow(const std::string& user_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FlowMap::iterator it = specific_flows_.find(user_id); if (it != specific_flows_.end()) { delete it->second; specific_flows_.erase(it); } } bool <API key>::<API key>() const { bool <API key> = false; cros_settings_->GetBoolean(<API key>, &<API key>); return <API key>; } UserFlow* <API key>::GetDefaultUserFlow() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!default_flow_.get()) default_flow_.reset(new DefaultUserFlow()); return default_flow_.get(); } void <API key>::<API key>() { content::NotificationService::current()->Notify( chrome::<API key>, content::Source<UserManager>(this), content::NotificationService::NoDetails()); } void <API key>::<API key>( const user_manager::User* added_user, bool user_switch_pending) { if (user_switch_pending) <API key>(added_user->email()); UpdateNumberOfUsers(); ChromeUserManager::<API key>(added_user, user_switch_pending); } void <API key>::OnUserNotAllowed(const std::string& user_email) { LOG(ERROR) << "Shutdown session because a user is not allowed to be in the " "current session"; chromeos::<API key>(user_email); } void <API key>::UpdateNumberOfUsers() { size_t users = GetLoggedInUsers().size(); if (users) { // Write the user number as UMA stat when a multi user session is possible. if ((users + <API key>().size()) > 1) ash::MultiProfileUMA::RecordUserCount(users); } base::debug::SetCrashKeyValue( crash_keys::kNumberOfUsers, base::StringPrintf("%" PRIuS, GetLoggedInUsers().size())); } } // namespace chromeos
#include <pcl_conversions/pcl_conversions.h> #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include "grid_map_pcl/helpers.hpp" namespace gm = ::grid_map::grid_map_pcl; using Point = ::pcl::PointXYZ; using PointCloud = ::pcl::PointCloud<Point>; void publishCloud(const std::string& filename, const ros::Publisher& pub, const std::string& frame) { PointCloud::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); cloud = gm::<API key>(filename); cloud->header.frame_id = frame; sensor_msgs::PointCloud2 msg; pcl::toROSMsg(*cloud, msg); ROS_INFO_STREAM("Publishing loaded cloud, number of points: " << cloud->points.size()); msg.header.stamp = ros::Time::now(); pub.publish(msg); } int main(int argc, char** argv) { ros::init(argc, argv, "<API key>"); ros::NodeHandle nh("~"); const std::string pathToCloud = gm::getPcdFilePath(nh); const std::string cloudFrame = nh.param<std::string>("cloud_frame", ""); // publish cloud ros::Publisher cloudPub = nh.advertise<sensor_msgs::PointCloud2>("raw_pointcloud", 1, true); publishCloud(pathToCloud, cloudPub, cloudFrame); // run ros::spin(); return EXIT_SUCCESS; }
#ifndef <API key> #define <API key> #include "base/memory/weak_ptr.h" #include "chrome/browser/metrics/<API key>.h" #include "components/metrics/metrics_provider.h" namespace device { class BluetoothAdapter; } namespace metrics { class <API key>; } class PrefRegistrySimple; class PrefService; // Performs ChromeOS specific metrics logging. class <API key> : public metrics::MetricsProvider { public: <API key>(); ~<API key>() override; static void RegisterPrefs(PrefRegistrySimple* registry); // Records a crash. static void LogCrash(const std::string& crash_type); // Loads hardware class information. When this task is complete, |callback| // is run. void <API key>(const base::Closure& callback); // metrics::MetricsProvider: void <API key>() override; void <API key>( metrics::SystemProfileProto* <API key>) override; void <API key>( metrics::SystemProfileProto* <API key>) override; void <API key>( metrics::<API key>* uma_proto) override; private: // Called on the FILE thread to load hardware class information. void <API key>(); // Update the number of users logged into a multi-profile session. // If the number of users change while the log is open, the call invalidates // the user count value. void <API key>( metrics::SystemProfileProto* <API key>); // Sets the Bluetooth Adapter instance used for the WriteBluetoothProto() // call. void SetBluetoothAdapter(scoped_refptr<device::BluetoothAdapter> adapter); // Writes info about paired Bluetooth devices on this system. void WriteBluetoothProto(metrics::SystemProfileProto* <API key>); metrics::PerfProvider perf_provider_; // Bluetooth Adapter instance for collecting information about paired devices. scoped_refptr<device::BluetoothAdapter> adapter_; // Whether the user count was registered at the last log initialization. bool <API key>; // The user count at the time that a log was last initialized. Contains a // valid value only if |<API key>| is // true. uint64 <API key>; // Hardware class (e.g., hardware qualification ID). This class identifies // the configured system components such as CPU, WiFi adapter, etc. std::string hardware_class_; base::WeakPtrFactory<<API key>> weak_ptr_factory_; <API key>(<API key>); }; #endif // <API key>
#ifndef <API key> #define <API key> #include <stdint.h> #include <memory> #include "base/macros.h" #include "media/gpu/vaapi/vaapi_image_decoder.h" namespace media { namespace fuzzing { class <API key>; } // namespace fuzzing struct JpegFrameHeader; struct JpegParseResult; class ScopedVAImage; // Returns the internal format required for a JPEG image given its parsed // |frame_header|. If the image's subsampling format is not one of 4:2:0, 4:2:2, // or 4:4:4, returns kInvalidVaRtFormat. unsigned int <API key>(const JpegFrameHeader& frame_header); class VaapiJpegDecoder : public VaapiImageDecoder { public: VaapiJpegDecoder(); VaapiJpegDecoder(const VaapiJpegDecoder&) = delete; VaapiJpegDecoder& operator=(const VaapiJpegDecoder&) = delete; ~VaapiJpegDecoder() override; // VaapiImageDecoder implementation. gpu::<API key> GetType() const override; SkYUVColorSpace GetYUVColorSpace() const override; // Get the decoded data from the last Decode() call as a ScopedVAImage. The // VAImage's format will be either |<API key>| if the conversion // from the internal format is supported or a fallback FOURCC (see // VaapiWrapper::<API key>() for details). Returns // nullptr on failure and sets *|status| to the reason for failure. std::unique_ptr<ScopedVAImage> GetImage(uint32_t <API key>, <API key>* status); private: friend class fuzzing::<API key>; // VaapiImageDecoder implementation. <API key> <API key>( base::span<const uint8_t> encoded_image) override; // <API key>() is implemented by calling the // following methods. They are here so that a fuzzer can inject (almost) // arbitrary data into libva by skipping the parsing and image support checks // in <API key>(). bool MaybeCreateSurface(unsigned int <API key>, const gfx::Size& new_coded_size, const gfx::Size& new_visible_size); bool SubmitBuffers(const JpegParseResult& parse_result); }; } // namespace media #endif // <API key>
using System; using Inbox2.Framework; namespace Inbox2.Core.Configuration { public static class CloudApi { public static string ApiBaseUrl { get { return String.Format("http://api{0}.inbox2.com/", String.IsNullOrEmpty(CommandLine.Current.Environment) ? String.Empty : "." + CommandLine.Current.Environment); } } public static string ApplicationKey { get { return "<API key>=="; } } public static string AccessToken { get { return SettingsManager.ClientSettings.AppConfiguration.AuthToken; } } } }
#include "content/browser/payments/<API key>.h" #include <limits> #include <utility> #include "base/base64.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "components/payments/content/icon/icon_size.h" #include "content/browser/renderer_host/<API key>.h" #include "content/browser/service_worker/<API key>.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/global_routing_id.h" #include "content/public/browser/<API key>.h" #include "content/public/browser/page.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/manifest/<API key>.h" #include "third_party/blink/public/common/manifest/manifest_util.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" #include "third_party/blink/public/mojom/manifest/manifest.mojom.h" #include "ui/gfx/codec/png_codec.h" #include "url/origin.h" namespace content { <API key>::PaymentAppInfo::PaymentAppInfo() {} <API key>::PaymentAppInfo::~PaymentAppInfo() {} void <API key>::Start( const GURL& context_url, scoped_refptr<<API key>> <API key>, <API key> callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::unique_ptr<std::vector<<API key>>> frame_routing_ids = <API key>-><API key>( blink::StorageKey(url::Origin::Create(context_url))); SelfDeleteFetcher* fetcher = new SelfDeleteFetcher(std::move(callback)); fetcher->Start(context_url, std::move(frame_routing_ids)); } <API key>::WebContentsHelper::WebContentsHelper( WebContents* web_contents) : WebContentsObserver(web_contents) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } <API key>::WebContentsHelper::~WebContentsHelper() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } <API key>::SelfDeleteFetcher::SelfDeleteFetcher( <API key> callback) : <API key>(std::make_unique<PaymentAppInfo>()), callback_(std::move(callback)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } <API key>::SelfDeleteFetcher::~SelfDeleteFetcher() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } void <API key>::SelfDeleteFetcher::Start( const GURL& context_url, const std::unique_ptr<std::vector<<API key>>>& frame_routing_ids) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (frame_routing_ids->empty()) { // Cannot print this error to the developer console, because the appropriate // developer console has not been found. LOG(ERROR) << "Unable to find the top level web content for retrieving the web " "app manifest of a payment handler for \"" << context_url << "\"."; <API key>(); return; } for (const auto& frame : *frame_routing_ids) { // Find out the render frame host registering the payment app. Although a // service worker can manage instruments, the first instrument must be set // on a page that has a link to a web app manifest, so it can be fetched // here. RenderFrameHostImpl* render_frame_host = RenderFrameHostImpl::FromID(frame.child_id, frame.frame_routing_id); if (!render_frame_host || context_url.spec().compare( render_frame_host->GetLastCommittedURL().spec()) != 0) { continue; } // Get the main frame since web app manifest is only available in the main // frame's document by definition. The main frame's document must come from // the same origin. RenderFrameHostImpl* <API key> = render_frame_host; while (<API key>->GetParent() != nullptr) { <API key> = <API key>->GetParent(); } WebContentsImpl* <API key> = static_cast<WebContentsImpl*>( WebContents::FromRenderFrameHost(<API key>)); if (!<API key>) { <API key>->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, "Unable to find the web page for \"" + context_url.spec() + "\" to fetch payment handler manifest (for name and icon)."); continue; } if (<API key>->IsHidden()) { <API key>->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, "Unable to fetch payment handler manifest (for name and icon) for " "\"" + context_url.spec() + "\" from a hidden top level web page \"" + <API key>->GetLastCommittedURL().spec() + "\"."); continue; } if (!url::IsSameOriginWith(context_url, <API key>->GetLastCommittedURL())) { <API key>->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, "Unable to fetch payment handler manifest (for name and icon) for " "\"" + context_url.spec() + "\" from a cross-origin top level web page \"" + <API key>->GetLastCommittedURL().spec() + "\"."); continue; } <API key> = std::make_unique<WebContentsHelper>(<API key>); <API key>->GetPage().GetManifest( base::BindOnce(&<API key>::SelfDeleteFetcher:: <API key>, weak_ptr_factory_.GetWeakPtr())); return; } // Cannot print this error to the developer console, because the appropriate // developer console has not been found. LOG(ERROR) << "Unable to find the top level web content for retrieving the web " "app manifest of a payment handler for \"" << context_url << "\"."; <API key>(); } void <API key>::SelfDeleteFetcher::<API key>() { DCHECK_CURRENTLY_ON(BrowserThread::UI); base::<API key>::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback_), std::move(<API key>))); delete this; } void <API key>::SelfDeleteFetcher::<API key>( const GURL& url, blink::mojom::ManifestPtr manifest) { DCHECK_CURRENTLY_ON(BrowserThread::UI); manifest_url_ = url; if (manifest_url_.is_empty()) { WarnIfPossible( "The page that installed the payment handler does not contain a web " "app manifest link: <link rel=\"manifest\" " "href=\"some-file-name-here\">. This manifest defines the payment " "handler's name and icon. User may not recognize this payment handler " "in UI, because it will be labeled only by its origin."); <API key>(); return; } if (blink::IsEmptyManifest(manifest)) { WarnIfPossible( "Unable to download a valid payment handler web app manifest from \"" + manifest_url_.spec() + "\". This manifest cannot be empty and must in JSON format. The " "manifest defines the payment handler's name and icon. User may not " "recognize this payment handler in UI, because it will be labeled only " "by its origin."); <API key>(); return; } <API key>-><API key> = manifest-><API key>; for (const auto& related_application : manifest-><API key>) { <API key>-><API key>.emplace_back( <API key>()); if (related_application.platform) { base::UTF16ToUTF8( related_application.platform->c_str(), related_application.platform->length(), &(<API key>-><API key>.back().platform)); } if (related_application.id) { base::UTF16ToUTF8( related_application.id->c_str(), related_application.id->length(), &(<API key>-><API key>.back().id)); } } if (!manifest->name) { WarnIfPossible("The payment handler's web app manifest \"" + manifest_url_.spec() + "\" does not contain a \"name\" field. User may not " "recognize this payment handler in UI, because it will be " "labeled only by its origin."); } else if (manifest->name->empty()) { WarnIfPossible( "The \"name\" field in the payment handler's web app manifest \"" + manifest_url_.spec() + "\" is empty. User may not recognize this payment handler in UI, " "because it will be labeled only by its origin."); } else { base::UTF16ToUTF8(manifest->name->c_str(), manifest->name->length(), &(<API key>->name)); } if (manifest->icons.empty()) { WarnIfPossible( "Unable to download the payment handler's icon, because the web app " "manifest \"" + manifest_url_.spec() + "\" does not contain an \"icons\" field with a valid URL in \"src\" " "sub-field. User may not recognize this payment handler in UI."); <API key>(); return; } WebContents* web_contents = <API key>->web_contents(); if (!web_contents) { LOG(WARNING) << "Unable to download the payment handler's icon because no " "renderer was found, possibly because the page was closed " "or navigated away during installation. User may not " "recognize this payment handler in UI, because it will be " "labeled only by its name and origin."; <API key>(); return; } gfx::NativeView native_view = web_contents->GetNativeView(); icon_url_ = blink::<API key>::<API key>( manifest->icons, payments::IconSizeCalculator::IdealIconHeight(native_view), payments::IconSizeCalculator::MinimumIconHeight(), <API key>::<API key>, blink::mojom::<API key>::ANY); if (!icon_url_.is_valid()) { WarnIfPossible( "No suitable payment handler icon found in the \"icons\" field defined " "in the web app manifest \"" + manifest_url_.spec() + "\". This is most likely due to unsupported MIME types in the " "\"icons\" field. User may not recognize this payment handler in UI."); <API key>(); return; } bool can_download = <API key>::Download( web_contents, icon_url_, payments::IconSizeCalculator::IdealIconHeight(native_view), payments::IconSizeCalculator::MinimumIconHeight(), /* <API key>= */ std::numeric_limits<int>::max(), base::BindOnce(&<API key>::SelfDeleteFetcher::OnIconFetched, weak_ptr_factory_.GetWeakPtr()), false /* square_only */); // |can_download| is false only if web contents are null or the icon URL is // not valid. Both of these conditions are manually checked above, so // |can_download| should never be false. The manual checks above are necessary // to provide more detailed error messages. DCHECK(can_download); } void <API key>::SelfDeleteFetcher::OnIconFetched( const SkBitmap& icon) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (icon.drawsNothing()) { WarnIfPossible("Unable to download a valid payment handler icon from \"" + icon_url_.spec() + "\", which is defined in the web app manifest \"" + manifest_url_.spec() + "\". User may not recognize this payment handler in UI."); <API key>(); return; } std::vector<unsigned char> bitmap_data; bool success = gfx::PNGCodec::EncodeBGRASkBitmap(icon, false, &bitmap_data); DCHECK(success); base::Base64Encode( base::StringPiece(reinterpret_cast<const char*>(&bitmap_data[0]), bitmap_data.size()), &(<API key>->icon)); <API key>(); } void <API key>::SelfDeleteFetcher::WarnIfPossible( const std::string& message) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(<API key>); if (<API key>->web_contents()) { <API key>->web_contents()->GetMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kWarning, message); } else { LOG(WARNING) << message; } } } // namespace content
#ifndef <API key> #define <API key> #include "net/third_party/quic/core/<API key>.h" namespace quic { namespace test { class <API key> { public: explicit <API key>(<API key>* buffer); <API key>(const <API key>&) = delete; <API key>& operator=( const <API key>&) = delete; // Read from this buffer_ into the given destination buffer_ up to the // size of the destination. Returns the number of bytes read. Reading from // an empty buffer_->returns 0. size_t Read(char* dest_buffer, size_t size); // If buffer is empty, the blocks_ array must be empty, which means all // blocks are deallocated. bool <API key>(); bool IsBlockArrayEmpty(); bool CheckInitialState(); bool <API key>(); size_t GetInBlockOffset(QuicStreamOffset offset); <API key>::BufferBlock* GetBlock(size_t index); int IntervalSize(); size_t max_buffer_capacity(); size_t ReadableBytes(); void <API key>(QuicStreamOffset total_bytes_read); void AddBytesReceived(QuicStreamOffset offset, QuicByteCount length); bool IsBufferAllocated(); size_t block_count(); const QuicIntervalSet<QuicStreamOffset>& bytes_received(); private: <API key>* buffer_; }; } // namespace test } // namespace quic #endif // <API key>
/** * @fileoverview A command is an abstraction of an action a user can do in the * UI. * * When the focus changes in the document for each command a canExecute event * is dispatched on the active element. By listening to this event you can * enable and disable the command by setting the event.canExecute property. * * When a command is executed a command event is dispatched on the active * element. Note that you should stop the propagation after you have handled the * command if there might be other command listeners higher up in the DOM tree. */ cr.define('cr.ui', function() { /** * This is used to identify keyboard shortcuts. * @param {string} shortcut The text used to describe the keys for this * keyboard shortcut. * @constructor */ function KeyboardShortcut(shortcut) { var mods = {}; var ident = ''; shortcut.split('-').forEach(function(part) { var partLc = part.toLowerCase(); switch (partLc) { case 'alt': case 'ctrl': case 'meta': case 'shift': mods[partLc + 'Key'] = true; break; default: if (ident) throw Error('Invalid shortcut'); ident = part; } }); this.ident_ = ident; this.mods_ = mods; } KeyboardShortcut.prototype = { /** * Whether the keyboard shortcut object matches a keyboard event. * @param {!Event} e The keyboard event object. * @return {boolean} Whether we found a match or not. */ matchesEvent: function(e) { if (e.keyIdentifier == this.ident_) { // All keyboard modifiers needs to match. var mods = this.mods_; return ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'].every(function(k) { return e[k] == !!mods[k]; }); } return false; } }; /** * Creates a new command element. * @constructor * @extends {HTMLElement} */ var Command = cr.ui.define('command'); Command.prototype = { __proto__: HTMLElement.prototype, /** * Initializes the command. */ decorate: function() { CommandManager.init(this.ownerDocument); if (this.hasAttribute('shortcut')) this.shortcut = this.getAttribute('shortcut'); }, /** * Executes the command by dispatching a command event on the given element. * If |element| isn't given, the active element is used instead. * If the command is {@code disabled} this does nothing. * @param {HTMLElement=} opt_element Optional element to dispatch event on. */ execute: function(opt_element) { if (this.disabled) return; var doc = this.ownerDocument; if (doc.activeElement) { var e = new cr.Event('command', true, false); e.command = this; (opt_element || doc.activeElement).dispatchEvent(e); } }, /** * Call this when there have been changes that might change whether the * command can be executed or not. * @param {Node=} opt_node Node for which to actuate command state. */ canExecuteChange: function(opt_node) { <API key>(this, opt_node || this.ownerDocument.activeElement); }, /** * The keyboard shortcut that triggers the command. This is a string * consisting of a keyIdentifier (as reported by WebKit in keydown) as * well as optional key modifiers joinded with a '-'. * * Multiple keyboard shortcuts can be provided by separating them by * whitespace. * * For example: * "F1" * "U+0008-Meta" for Apple command backspace. * "U+0041-Ctrl" for Control A * "U+007F U+0008-Meta" for Delete and Command Backspace * * @type {string} */ shortcut_: '', get shortcut() { return this.shortcut_; }, set shortcut(shortcut) { var oldShortcut = this.shortcut_; if (shortcut !== oldShortcut) { this.keyboardShortcuts_ = shortcut.split(/\s+/).map(function(shortcut) { return new KeyboardShortcut(shortcut); }); // Set this after the keyboardShortcuts_ since that might throw. this.shortcut_ = shortcut; cr.<API key>(this, 'shortcut', this.shortcut_, oldShortcut); } }, /** * Whether the event object matches the shortcut for this command. * @param {!Event} e The key event object. * @return {boolean} Whether it matched or not. */ matchesEvent: function(e) { if (!this.keyboardShortcuts_) return false; return this.keyboardShortcuts_.some(function(keyboardShortcut) { return keyboardShortcut.matchesEvent(e); }); } }; /** * The label of the command. * @type {string} */ cr.defineProperty(Command, 'label', cr.PropertyKind.ATTR); /** * Whether the command is disabled or not. * @type {boolean} */ cr.defineProperty(Command, 'disabled', cr.PropertyKind.BOOL_ATTR); /** * Whether the command is hidden or not. * @type {boolean} */ cr.defineProperty(Command, 'hidden', cr.PropertyKind.BOOL_ATTR); /** * Whether the command is checked or not. * @type {boolean} */ cr.defineProperty(Command, 'checked', cr.PropertyKind.BOOL_ATTR); /** * Dispatches a canExecute event on the target. * @param {cr.ui.Command} command The command that we are testing for. * @param {Element} target The target element to dispatch the event on. */ function <API key>(command, target) { var e = new CanExecuteEvent(command, true); target.dispatchEvent(e); command.disabled = !e.canExecute; } /** * The command managers for different documents. */ var commandManagers = {}; /** * Keeps track of the focused element and updates the commands when the focus * changes. * @param {!Document} doc The document that we are managing the commands for. * @constructor */ function CommandManager(doc) { doc.addEventListener('focus', this.handleFocus_.bind(this), true); // Make sure we add the listener to the bubbling phase so that elements can // prevent the command. doc.addEventListener('keydown', this.handleKeyDown_.bind(this), false); } /** * Initializes a command manager for the document as needed. * @param {!Document} doc The document to manage the commands for. */ CommandManager.init = function(doc) { var uid = cr.getUid(doc); if (!(uid in commandManagers)) { commandManagers[uid] = new CommandManager(doc); } }; CommandManager.prototype = { /** * Handles focus changes on the document. * @param {Event} e The focus event object. * @private */ handleFocus_: function(e) { var target = e.target; // Ignore focus on a menu button or command item if (target.menu || target.command) return; var commands = Array.prototype.slice.call( target.ownerDocument.querySelectorAll('command')); commands.forEach(function(command) { <API key>(command, target); }); }, /** * Handles the keydown event and routes it to the right command. * @param {!Event} e The keydown event. */ handleKeyDown_: function(e) { var target = e.target; var commands = Array.prototype.slice.call( target.ownerDocument.querySelectorAll('command')); for (var i = 0, command; command = commands[i]; i++) { if (!command.disabled && command.matchesEvent(e)) { e.preventDefault(); // We do not want any other element to handle this. e.stopPropagation(); command.execute(); return; } } } }; /** * The event type used for canExecute events. * @param {!cr.ui.Command} command The command that we are evaluating. * @extends {Event} * @constructor * @class */ function CanExecuteEvent(command) { var e = command.ownerDocument.createEvent('Event'); e.initEvent('canExecute', true, false); e.__proto__ = CanExecuteEvent.prototype; e.command = command; return e; } CanExecuteEvent.prototype = { __proto__: Event.prototype, /** * The current command * @type {cr.ui.Command} */ command: null, /** * Whether the target can execute the command. Setting this also stops the * propagation. * @type {boolean} */ canExecute_: false, get canExecute() { return this.canExecute_; }, set canExecute(canExecute) { this.canExecute_ = !!canExecute; this.stopPropagation(); } }; // Export return { Command: Command, CanExecuteEvent: CanExecuteEvent }; });
#ifndef <API key> #define <API key> #include <memory> #include <string> #include "base/values.h" #include "url/gurl.h" namespace base { class DictionaryValue; } namespace error_page { class LocalizedError { public: // Information about elements shown on the error page. struct PageState { PageState(); ~PageState(); PageState(const PageState& other) = delete; PageState(PageState&& other); PageState& operator=(PageState&& other); // Strings used within the error page HTML/JS. base::DictionaryValue strings; bool is_offline_error = false; bool reload_button_shown = false; bool <API key> = false; bool <API key> = false; bool auto_fetch_allowed = false; }; LocalizedError() = delete; LocalizedError(const LocalizedError&) = delete; LocalizedError& operator=(const LocalizedError&) = delete; // Returns a |PageState| that describes the elements that should be shown on // on HTTP errors, like 404 or connection reset. static PageState GetPageState( int error_code, const std::string& error_domain, const GURL& failed_url, bool is_post, bool <API key>, bool stale_copy_in_cache, bool <API key>, bool is_incognito, bool <API key>, bool <API key>, bool is_kiosk_mode, // whether device is currently in single app (kiosk) // mode const std::string& locale, bool <API key>); // Returns a description of the encountered error. static std::u16string GetErrorDetails(const std::string& error_domain, int error_code, bool <API key>, bool is_post); // Returns true if an error page exists for the specified parameters. static bool HasStrings(const std::string& error_domain, int error_code); }; } // namespace error_page #endif // <API key>
using System.Linq.Expressions; using NHibernate.Metadata; namespace NHibernate.Linq.Expressions { public class EntityExpression : <API key> { private readonly string _alias; private readonly string _associationPath; private readonly IClassMetadata _metaData; private readonly Expression _expression; public string Alias { get { return _alias; } } public string AssociationPath { get { return _associationPath; } } public IClassMetadata MetaData { get { return _metaData; } } public Expression Expression { get { return _expression; } } public EntityExpression(string associationPath, string alias, System.Type type, IClassMetadata metaData, Expression expression) : base(IsRoot(expression) ? <API key>.RootEntity : <API key>.Entity, type) { _associationPath = associationPath; _alias = alias; _metaData = metaData; _expression = expression; } private static bool IsRoot(Expression expr) { if (expr == null) return true; if (!(expr is EntityExpression)) return true; return false; } public override string ToString() { return Alias; } public virtual string <API key>() { if ((<API key>)this.NodeType == <API key>.RootEntity) { return this.MetaData.<API key>; } return string.Format("{0}.{1}", this.Alias, this.MetaData.<API key>); } } }
#ifndef HTTPParsers_h #define HTTPParsers_h #include "platform/PlatformExport.h" #include "wtf/Allocator.h" #include "wtf/Forward.h" #include "wtf/HashSet.h" #include "wtf/Vector.h" #include "wtf/text/StringHash.h" namespace blink { typedef enum { <API key>, <API key>, <API key>, <API key> } <API key>; enum <API key> { <API key>, <API key> }; enum <API key> { <API key>, XFrameOptionsDeny, <API key>, <API key>, <API key> }; // Be sure to update the behavior of XSSAuditor::<API key> whenever you change this enum's content or ordering. enum <API key> { ReflectedXSSUnset = 0, AllowReflectedXSS, ReflectedXSSInvalid, FilterReflectedXSS, BlockReflectedXSS }; using <API key> = HashSet<String, CaseFoldingHash>; struct CacheControlHeader { DISALLOW_NEW(); bool parsed : 1; bool containsNoCache : 1; bool containsNoStore : 1; bool <API key> : 1; double maxAge; double <API key>; CacheControlHeader() : parsed(false) , containsNoCache(false) , containsNoStore(false) , <API key>(false) , maxAge(0.0) , <API key>(0.0) { } }; PLATFORM_EXPORT <API key> <API key>(const String&); PLATFORM_EXPORT bool <API key>(const String&); PLATFORM_EXPORT bool <API key>(const String&); PLATFORM_EXPORT bool isValidHTTPToken(const String&); PLATFORM_EXPORT bool parseHTTPRefresh(const String& refresh, bool fromHttpEquivMeta, double& delay, String& url); PLATFORM_EXPORT double parseDate(const String&); // Given a Media Type (like "foo/bar; baz=gazonk" - usually from the // 'Content-Type' HTTP header), extract and return the "type/subtype" portion // ("foo/bar"). // Note: This function does not in any way check that the "type/subtype" pair // is well-formed. PLATFORM_EXPORT AtomicString <API key>(const AtomicString&); PLATFORM_EXPORT String <API key>(const String&); PLATFORM_EXPORT void <API key>(const String& mediaType, unsigned& charsetPos, unsigned& charsetLen, unsigned start = 0); PLATFORM_EXPORT <API key> <API key>(const String& header, String& failureReason, unsigned& failurePosition, String& reportURL); PLATFORM_EXPORT <API key> <API key>(const String&); PLATFORM_EXPORT CacheControlHeader <API key>(const AtomicString& cacheControlHeader, const AtomicString& pragmaHeader); PLATFORM_EXPORT void <API key>(const String& headerValue, <API key>&); PLATFORM_EXPORT <API key> <API key>(const String& header); } // namespace blink #endif
#ifndef <API key> #define <API key> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef MAXFLOW #include <taskQMaxflow.h> #else #include "../include/taskQ.h" #endif #ifdef USE_ATHREADS // Alamere threads #include "taskQAThread.h" #endif #define CACHE_LINE_SIZE 256 /* Largest cache line size */ // #define HERE printf( ">>> at %s : %d\n", __FILE__, __LINE__) // #define HERE printf( "%ld $$$ at %s : %d\n", ( long)alt_index(), __FILE__, __LINE__) #define HERE // #define TRACE printf( "%ld ### at %s : %d\n", ( long)alt_index(), __FILE__, __LINE__); fflush( stdout); // #define TRACE printf( ">>> at %s : %d\n", __FILE__, __LINE__) // #define TRACE printf( ">>> %10d at %s : %d\n", pthread_self(), __FILE__, __LINE__) #define TRACE #define ERROR { printf( "Error in TaskQ: This function should not have been called at %s : %d\n", __FILE__, __LINE__); exit(0); } // #define IF_STATS(s) s #define IF_STATS(s) #define TQ_ASSERT(v) { \ if ( !(v)) { \ printf( "TQ Assertion failed at %s:%d\n", __FILE__, __LINE__); \ exit(1); \ } \ } #define UNDEFINED_VALUE ( ( void *)-999) // #define DEBUG_TASKQ #ifdef DEBUG_TASKQ #define DEBUG_ASSERT(v) TQ_ASSERT(v) #define IF_DEBUG(v) v #define DEBUG_ANNOUNCE { printf( "\n\n>>>>>>>>>>>>>>>>>>>>>> Running the DEBUG version of the TaskQ <<<<<<<<<<<<<<<<<<<\n\n\n"); } #else #define DEBUG_ASSERT(v) #define IF_DEBUG(v) #define DEBUG_ANNOUNCE #endif #define NUM_FIELDS (MAX_DIMENSION+1) static inline void copyTask( void *taskDest[NUM_FIELDS], void *taskSrc[NUM_FIELDS]) { int i; for ( i = 0; i < NUM_FIELDS; i++) taskDest[i] = taskSrc[i]; } static inline void copyArgs1( void *task[NUM_FIELDS], TaskQTask1 taskFunction, void *arg1) { TQ_ASSERT( NUM_FIELDS >= 2); task[0] = ( void *)taskFunction; task[1] = arg1; IF_DEBUG( { int i; for ( i = 2; i < NUM_FIELDS; i++) task[i] = UNDEFINED_VALUE; }); } static inline void copyArgs2( void *task[NUM_FIELDS], TaskQTask2 taskFunction, void *arg1, void *arg2) { TQ_ASSERT( NUM_FIELDS >= 3); task[0] = ( void *)taskFunction; task[1] = arg1; task[2] = arg2; IF_DEBUG( { int i; for ( i = 3; i < NUM_FIELDS; i++) task[i] = UNDEFINED_VALUE; }); } static inline void copyArgs3( void *task[NUM_FIELDS], TaskQTask3 taskFunction, void *arg1, void *arg2, void *arg3) { TQ_ASSERT( NUM_FIELDS >= 4); task[0] = ( void *)taskFunction; task[1] = arg1; task[2] = arg2; task[3] = arg3; IF_DEBUG( { int i; for ( i = 4; i < NUM_FIELDS; i++) task[i] = UNDEFINED_VALUE; }); } // The following functions are used to enqueue a grid of tasks typedef void ( *AssignTasksFn)( TaskQTask3 taskFn, int numDimensions, int queueNo, long min[MAX_DIMENSION], long max[MAX_DIMENSION], long step[MAX_DIMENSION]); void standardize( int n, long min1[MAX_DIMENSION], long max1[MAX_DIMENSION], long step1[MAX_DIMENSION], long min2[MAX_DIMENSION], long max2[MAX_DIMENSION], long step2[MAX_DIMENSION]) { long k; DEBUG_ASSERT( MAX_DIMENSION == 3); for ( k = 0; k < MAX_DIMENSION; k++) { if ( k < n) { min1[k] = min2[k]; max1[k] = max2[k]; step1[k] = step2[k]; } else { min1[k] = 0; max1[k] = 1; step1[k] = 1; } } } static inline void <API key>( AssignTasksFn fn, TaskQTask3 taskFn, int numDimensions, int queueNo, long min[MAX_DIMENSION], long max[MAX_DIMENSION], long step[MAX_DIMENSION]) { long min1[MAX_DIMENSION], max1[MAX_DIMENSION], step1[MAX_DIMENSION]; standardize( numDimensions, min1, max1, step1, min, max, step); fn( taskFn, numDimensions, queueNo, min1, max1, step1); } static void enqueueGridRec( AssignTasksFn fn, TaskQTask3 taskFn, int numDimensions, int startQueue, int totalQueues, int currentDimension, long min[MAX_DIMENSION], long max[MAX_DIMENSION], long step[MAX_DIMENSION]) { if ( totalQueues == 1) { <API key>( fn, taskFn, numDimensions, startQueue, min, max, step); } else { long j, k; for ( j = 0, k = currentDimension; j < numDimensions; j++, k = (k+1) % numDimensions) if ( max[k] - min[k] > 1) break; if ( max[k] - min[k] == 1) { // Only one task left. Put it in the first queue <API key>( fn, taskFn, numDimensions, startQueue, min, max, step); // The rest get nothing for ( j = 0; j < numDimensions; j++) max[j] = min[j]; for ( j = 1; j < totalQueues; j++) <API key>( fn, taskFn, numDimensions, startQueue+j, min, max, step); } else { // Split it into two halfs and give half to each long next, middle, half, alt[MAX_DIMENSION]; middle = min[k] + ( max[k] - min[k])/2; next = (k+1) % numDimensions; half = totalQueues/2; // First half for ( j = 0; j < numDimensions; j++) if ( j == k) alt[j] = middle; else alt[j] = max[j]; enqueueGridRec( fn, taskFn, numDimensions, startQueue, half, next, min, alt, step); // Seconf half for ( j = 0; j < numDimensions; j++) if ( j == k) alt[j] = middle; else alt[j] = min[j]; enqueueGridRec( fn, taskFn, numDimensions, startQueue+half, totalQueues-half, next, alt, max, step); } } } long countTasks( int n, long max[MAX_DIMENSION], long step[MAX_DIMENSION]) { long k, count = 1; for ( k = 0; k < n; k++) count *= max[k]/step[k]; return count; } static inline void enqueueGridHelper( AssignTasksFn assignFunction, TaskQTask3 taskFunction, int numDimensions, int numTaskQs, long dimensionSize[MAX_DIMENSION], long tileSize[MAX_DIMENSION]) { long i, min[MAX_DIMENSION], max[MAX_DIMENSION]; for ( i = 0; i < numDimensions; i++) { DEBUG_ASSERT( dimensionSize[i] > 0); TQ_ASSERT( dimensionSize[i] % tileSize[i] == 0); min[i] = 0; max[i] = dimensionSize[i] / tileSize[i]; } enqueueGridRec( assignFunction, taskFunction, numDimensions, 0, numTaskQs, 0, min, max, tileSize); } // These are used to get/set task queue parameters static long paramValues[] = { ( long)UNDEFINED_VALUE, 1, ( long)UNDEFINED_VALUE }; void taskQSetParam( enum TaskQParam param, long value) { TQ_ASSERT( ( param > 0) && ( param < TaskQNumParams)); TQ_ASSERT( paramValues[TaskQNumParams] == ( long)UNDEFINED_VALUE); paramValues[param] = value; } long taskQGetParam( enum TaskQParam param) { TQ_ASSERT( ( param > 0) && ( param < TaskQNumParams)); TQ_ASSERT( paramValues[TaskQNumParams] == ( long)UNDEFINED_VALUE); return paramValues[param]; } #endif
#include "src/core/lib/surface/completion_queue.h" #include <stdio.h> #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/atm.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/support/string.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/call.h" #include "src/core/lib/surface/event_string.h" #include "src/core/lib/surface/surface_trace.h" typedef struct { grpc_pollset_worker **worker; void *tag; } plucker; /* Completion queue structure */ struct <API key> { /** owned by pollset */ gpr_mu *mu; /** completed events */ grpc_cq_completion completed_head; grpc_cq_completion *completed_tail; /** Number of pending events (+1 if we're not shutdown) */ gpr_refcount pending_events; /** Once owning_refs drops to zero, we will destroy the cq */ gpr_refcount owning_refs; /** 0 initially, 1 once we've begun shutting down */ int shutdown; int shutdown_called; int is_server_cq; int num_pluckers; plucker pluckers[<API key>]; grpc_closure <API key>; #ifndef NDEBUG void **outstanding_tags; size_t <API key>; size_t <API key>; #endif <API key> *next_free; }; #define POLLSET_FROM_CQ(cq) ((grpc_pollset *)(cq + 1)) static gpr_mu g_freelist_mu; static <API key> *g_freelist; static void <API key>(grpc_exec_ctx *exec_ctx, void *cc, bool success); void grpc_cq_global_init(void) { gpr_mu_init(&g_freelist_mu); } void <API key>(void) { gpr_mu_destroy(&g_freelist_mu); while (g_freelist) { <API key> *next = g_freelist->next_free; <API key>(POLLSET_FROM_CQ(g_freelist)); #ifndef NDEBUG gpr_free(g_freelist->outstanding_tags); #endif gpr_free(g_freelist); g_freelist = next; } } struct grpc_cq_alarm { grpc_timer alarm; grpc_cq_completion completion; /** completion queue where events about this alarm will be posted */ <API key> *cq; /** user supplied tag */ void *tag; }; <API key> *<API key>(void *reserved) { <API key> *cc; GPR_ASSERT(!reserved); GPR_TIMER_BEGIN("<API key>", 0); GRPC_API_TRACE("<API key>(reserved=%p)", 1, (reserved)); gpr_mu_lock(&g_freelist_mu); if (g_freelist == NULL) { gpr_mu_unlock(&g_freelist_mu); cc = gpr_malloc(sizeof(<API key>) + grpc_pollset_size()); grpc_pollset_init(POLLSET_FROM_CQ(cc), &cc->mu); #ifndef NDEBUG cc->outstanding_tags = NULL; cc-><API key> = 0; #endif } else { cc = g_freelist; g_freelist = g_freelist->next_free; gpr_mu_unlock(&g_freelist_mu); /* pollset already initialized */ } /* Initial ref is dropped by <API key> */ gpr_ref_init(&cc->pending_events, 1); /* One for destroy(), one for pollset_shutdown */ gpr_ref_init(&cc->owning_refs, 2); cc->completed_tail = &cc->completed_head; cc->completed_head.next = (uintptr_t)cc->completed_tail; cc->shutdown = 0; cc->shutdown_called = 0; cc->is_server_cq = 0; cc->num_pluckers = 0; #ifndef NDEBUG cc-><API key> = 0; #endif grpc_closure_init(&cc-><API key>, <API key>, cc); GPR_TIMER_END("<API key>", 0); return cc; } #ifdef <API key> void <API key>(<API key> *cc, const char *reason, const char *file, int line) { gpr_log(file, line, <API key>, "CQ:%p ref %d -> %d %s", cc, (int)cc->owning_refs.count, (int)cc->owning_refs.count + 1, reason); #else void <API key>(<API key> *cc) { #endif gpr_ref(&cc->owning_refs); } static void <API key>(grpc_exec_ctx *exec_ctx, void *arg, bool success) { <API key> *cc = arg; <API key>(cc, "pollset_destroy"); } #ifdef <API key> void <API key>(<API key> *cc, const char *reason, const char *file, int line) { gpr_log(file, line, <API key>, "CQ:%p unref %d -> %d %s", cc, (int)cc->owning_refs.count, (int)cc->owning_refs.count - 1, reason); #else void <API key>(<API key> *cc) { #endif if (gpr_unref(&cc->owning_refs)) { GPR_ASSERT(cc->completed_head.next == (uintptr_t)&cc->completed_head); grpc_pollset_reset(POLLSET_FROM_CQ(cc)); gpr_mu_lock(&g_freelist_mu); cc->next_free = g_freelist; g_freelist = cc; gpr_mu_unlock(&g_freelist_mu); } } void grpc_cq_begin_op(<API key> *cc, void *tag) { #ifndef NDEBUG gpr_mu_lock(cc->mu); GPR_ASSERT(!cc->shutdown_called); if (cc-><API key> == cc-><API key>) { cc-><API key> = GPR_MAX(4, 2 * cc-><API key>); cc->outstanding_tags = gpr_realloc(cc->outstanding_tags, sizeof(*cc->outstanding_tags) * cc-><API key>); } cc->outstanding_tags[cc-><API key>++] = tag; gpr_mu_unlock(cc->mu); #endif gpr_ref(&cc->pending_events); } /* Signal the end of an operation - if this is the last <API key> event, then enter shutdown mode */ /* Queue a GRPC_OP_COMPLETED operation */ void grpc_cq_end_op(grpc_exec_ctx *exec_ctx, <API key> *cc, void *tag, int success, void (*done)(grpc_exec_ctx *exec_ctx, void *done_arg, grpc_cq_completion *storage), void *done_arg, grpc_cq_completion *storage) { int shutdown; int i; grpc_pollset_worker *pluck_worker; #ifndef NDEBUG int found = 0; #endif GPR_TIMER_BEGIN("grpc_cq_end_op", 0); storage->tag = tag; storage->done = done; storage->done_arg = done_arg; storage->next = ((uintptr_t)&cc->completed_head) | ((uintptr_t)(success != 0)); gpr_mu_lock(cc->mu); #ifndef NDEBUG for (i = 0; i < (int)cc-><API key>; i++) { if (cc->outstanding_tags[i] == tag) { cc-><API key> GPR_SWAP(void *, cc->outstanding_tags[i], cc->outstanding_tags[cc-><API key>]); found = 1; break; } } GPR_ASSERT(found); #endif shutdown = gpr_unref(&cc->pending_events); if (!shutdown) { cc->completed_tail->next = ((uintptr_t)storage) | (1u & (uintptr_t)cc->completed_tail->next); cc->completed_tail = storage; pluck_worker = NULL; for (i = 0; i < cc->num_pluckers; i++) { if (cc->pluckers[i].tag == tag) { pluck_worker = *cc->pluckers[i].worker; break; } } grpc_pollset_kick(POLLSET_FROM_CQ(cc), pluck_worker); gpr_mu_unlock(cc->mu); } else { cc->completed_tail->next = ((uintptr_t)storage) | (1u & (uintptr_t)cc->completed_tail->next); cc->completed_tail = storage; GPR_ASSERT(!cc->shutdown); GPR_ASSERT(cc->shutdown_called); cc->shutdown = 1; <API key>(exec_ctx, POLLSET_FROM_CQ(cc), &cc-><API key>); gpr_mu_unlock(cc->mu); } GPR_TIMER_END("grpc_cq_end_op", 0); } grpc_event <API key>(<API key> *cc, gpr_timespec deadline, void *reserved) { grpc_event ret; grpc_pollset_worker *worker = NULL; int first_loop = 1; gpr_timespec now; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("<API key>", 0); GRPC_API_TRACE( "<API key>(" "cc=%p, " "deadline=gpr_timespec { tv_sec: %lld, tv_nsec: %d, clock_type: %d }, " "reserved=%p)", 5, (cc, (long long)deadline.tv_sec, (int)deadline.tv_nsec, (int)deadline.clock_type, reserved)); GPR_ASSERT(!reserved); deadline = <API key>(deadline, GPR_CLOCK_MONOTONIC); <API key>(cc, "next"); gpr_mu_lock(cc->mu); for (;;) { if (cc->completed_tail != &cc->completed_head) { grpc_cq_completion *c = (grpc_cq_completion *)cc->completed_head.next; cc->completed_head.next = c->next & ~(uintptr_t)1; if (c == cc->completed_tail) { cc->completed_tail = &cc->completed_head; } gpr_mu_unlock(cc->mu); ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; c->done(&exec_ctx, c->done_arg, c); break; } if (cc->shutdown) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_SHUTDOWN; break; } now = gpr_now(GPR_CLOCK_MONOTONIC); if (!first_loop && gpr_time_cmp(now, deadline) >= 0) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_TIMEOUT; break; } first_loop = 0; /* Check alarms - these are a global resource so we just ping each time through on every pollset. May update deadline to ensure timely wakeups. TODO(ctiller): can this work be localized? */ gpr_timespec iteration_deadline = deadline; if (grpc_timer_check(&exec_ctx, now, &iteration_deadline)) { GPR_TIMER_MARK("alarm_triggered", 0); gpr_mu_unlock(cc->mu); grpc_exec_ctx_flush(&exec_ctx); gpr_mu_lock(cc->mu); continue; } else { grpc_pollset_work(&exec_ctx, POLLSET_FROM_CQ(cc), &worker, now, iteration_deadline); } } <API key>(cc, &ret); <API key>(cc, "next"); <API key>(&exec_ctx); GPR_TIMER_END("<API key>", 0); return ret; } static int add_plucker(<API key> *cc, void *tag, grpc_pollset_worker **worker) { if (cc->num_pluckers == <API key>) { return 0; } cc->pluckers[cc->num_pluckers].tag = tag; cc->pluckers[cc->num_pluckers].worker = worker; cc->num_pluckers++; return 1; } static void del_plucker(<API key> *cc, void *tag, grpc_pollset_worker **worker) { int i; for (i = 0; i < cc->num_pluckers; i++) { if (cc->pluckers[i].tag == tag && cc->pluckers[i].worker == worker) { cc->num_pluckers GPR_SWAP(plucker, cc->pluckers[i], cc->pluckers[cc->num_pluckers]); return; } } <API key>(return ); } grpc_event <API key>(<API key> *cc, void *tag, gpr_timespec deadline, void *reserved) { grpc_event ret; grpc_cq_completion *c; grpc_cq_completion *prev; grpc_pollset_worker *worker = NULL; gpr_timespec now; int first_loop = 1; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("<API key>", 0); GRPC_API_TRACE( "<API key>(" "cc=%p, tag=%p, " "deadline=gpr_timespec { tv_sec: %lld, tv_nsec: %d, clock_type: %d }, " "reserved=%p)", 6, (cc, tag, (long long)deadline.tv_sec, (int)deadline.tv_nsec, (int)deadline.clock_type, reserved)); GPR_ASSERT(!reserved); deadline = <API key>(deadline, GPR_CLOCK_MONOTONIC); <API key>(cc, "pluck"); gpr_mu_lock(cc->mu); for (;;) { prev = &cc->completed_head; while ((c = (grpc_cq_completion *)(prev->next & ~(uintptr_t)1)) != &cc->completed_head) { if (c->tag == tag) { prev->next = (prev->next & (uintptr_t)1) | (c->next & ~(uintptr_t)1); if (c == cc->completed_tail) { cc->completed_tail = prev; } gpr_mu_unlock(cc->mu); ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; c->done(&exec_ctx, c->done_arg, c); goto done; } prev = c; } if (cc->shutdown) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_SHUTDOWN; break; } if (!add_plucker(cc, tag, &worker)) { gpr_log(GPR_DEBUG, "Too many outstanding <API key> calls: maximum " "is %d", <API key>); gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); /* TODO(ctiller): should we use a different result here */ ret.type = GRPC_QUEUE_TIMEOUT; break; } now = gpr_now(GPR_CLOCK_MONOTONIC); if (!first_loop && gpr_time_cmp(now, deadline) >= 0) { del_plucker(cc, tag, &worker); gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_TIMEOUT; break; } first_loop = 0; /* Check alarms - these are a global resource so we just ping each time through on every pollset. May update deadline to ensure timely wakeups. TODO(ctiller): can this work be localized? */ gpr_timespec iteration_deadline = deadline; if (grpc_timer_check(&exec_ctx, now, &iteration_deadline)) { GPR_TIMER_MARK("alarm_triggered", 0); gpr_mu_unlock(cc->mu); grpc_exec_ctx_flush(&exec_ctx); gpr_mu_lock(cc->mu); } else { grpc_pollset_work(&exec_ctx, POLLSET_FROM_CQ(cc), &worker, now, iteration_deadline); } del_plucker(cc, tag, &worker); } done: <API key>(cc, &ret); <API key>(cc, "pluck"); <API key>(&exec_ctx); GPR_TIMER_END("<API key>", 0); return ret; } /* Shutdown simply drops a ref that we reserved at creation time; if we drop to zero here, then enter shutdown mode and wake up any waiters */ void <API key>(<API key> *cc) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("<API key>", 0); GRPC_API_TRACE("<API key>(cc=%p)", 1, (cc)); gpr_mu_lock(cc->mu); if (cc->shutdown_called) { gpr_mu_unlock(cc->mu); GPR_TIMER_END("<API key>", 0); return; } cc->shutdown_called = 1; if (gpr_unref(&cc->pending_events)) { GPR_ASSERT(!cc->shutdown); cc->shutdown = 1; <API key>(&exec_ctx, POLLSET_FROM_CQ(cc), &cc-><API key>); } gpr_mu_unlock(cc->mu); <API key>(&exec_ctx); GPR_TIMER_END("<API key>", 0); } void <API key>(<API key> *cc) { GRPC_API_TRACE("<API key>(cc=%p)", 1, (cc)); GPR_TIMER_BEGIN("<API key>", 0); <API key>(cc); <API key>(cc, "destroy"); GPR_TIMER_END("<API key>", 0); } grpc_pollset *grpc_cq_pollset(<API key> *cc) { return POLLSET_FROM_CQ(cc); } void <API key>(<API key> *cc) { cc->is_server_cq = 1; } int <API key>(<API key> *cc) { return cc->is_server_cq; }
import shutil from nose.tools import * from holland.lib.lvm import LogicalVolume from holland.lib.lvm.snapshot import * from tests.constants import * class TestSnapshot(object): def setup(self): self.tmpdir = tempfile.mkdtemp() def teardown(self): shutil.rmtree(self.tmpdir) def test_snapshot_fsm(self): lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV)) name = lv.lv_name + '_snapshot' size = 1 # extent snapshot = Snapshot(name, size, self.tmpdir) snapshot.start(lv) def <API key>(self): lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV)) name = lv.lv_name + '_snapshot' size = 1 # extent snapshot = Snapshot(name, size, self.tmpdir) def handle_event(event, *args, **kwargs): pass snapshot.register('pre-mount', handle_event) snapshot.register('post-mount', handle_event) snapshot.start(lv) def <API key>(self): lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV)) name = lv.lv_name + '_snapshot' size = 1 # extent snapshot = Snapshot(name, size, self.tmpdir) def bad_callback(event, *args, **kwargs): raise Exception("Oooh nooo!") for evt in ('initialize', 'pre-snapshot', 'post-snapshot', 'pre-mount', 'post-mount', 'pre-unmount', 'post-unmount', 'pre-remove', 'post-remove', 'finish'): snapshot.register(evt, bad_callback) assert_raises(<API key>, snapshot.start, lv) snapshot.unregister(evt, bad_callback) if snapshot.sigmgr._handlers: raise Exception("WTF. sigmgr handlers still exist when checking event => %r", evt)
package com.mitchellbosecke.pebble.extension; import com.mitchellbosecke.pebble.attributes.AttributeResolver; import com.mitchellbosecke.pebble.operator.BinaryOperator; import com.mitchellbosecke.pebble.operator.UnaryOperator; import com.mitchellbosecke.pebble.tokenParser.TokenParser; import java.util.List; import java.util.Map; public abstract class AbstractExtension implements Extension { @Override public List<TokenParser> getTokenParsers() { return null; } @Override public List<BinaryOperator> getBinaryOperators() { return null; } @Override public List<UnaryOperator> getUnaryOperators() { return null; } @Override public Map<String, Filter> getFilters() { return null; } @Override public Map<String, Test> getTests() { return null; } @Override public Map<String, Function> getFunctions() { return null; } @Override public Map<String, Object> getGlobalVariables() { return null; } @Override public List<NodeVisitorFactory> getNodeVisitors() { return null; } @Override public List<AttributeResolver> <API key>() { return null; } }
<!DOCTYPE html> <! Copyright (c) 2013 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. <link rel="import" href="/core/analysis/analysis_sub_view.html"> <link rel="import" href="/core/analysis/util.html"> <link rel="import" href="/core/analysis/analysis_link.html"> <link rel="import" href="/base/utils.html"> <polymer-element name="<API key>" extends="<API key>"> <template> <style> table { border-collapse: collapse; border-width: 0; margin-bottom: 25px; width: 100%; } table tr > td:first-child { padding-left: 2px; } table tr > td { padding: 2px 4px 2px 4px; vertical-align: text-top; width: 150px; } table td td { padding: 0 0 0 0; width: auto; } tr { vertical-align: top; } tr:nth-child(2n+0) { background-color: #e2e2e2; } </style> <table> <tr> <td>Running process:</td><td id="process-name"></td> </tr> <tr> <td>Running thread:</td><td id="thread-name"></td> </tr> <tr> <td>Start:</td><td id="start"></td> </tr> <tr> <td>Duration:</td><td id="duration"></td> </tr> <tr> <td>Active slices:</td><td id="running-thread"></td> </tr> <tr> <td>Args:</td> <td> <<API key> id="args"> </<API key>> </td> </tr> </table> </template> <script> 'use strict'; Polymer({ created: function() { this.currentSelection_ = undefined; }, get selection() { return this.currentSelection_; }, set selection(selection) { if (selection.length !== 1) throw new Error('Only supports single slices'); if (!(selection[0] instanceof tv.c.trace_model.CpuSlice)) throw new Error('Only supports thread time slices'); this.currentSelection_ = selection; var cpuSlice = selection[0]; var thread = cpuSlice.<API key>; var shadowRoot = this.shadowRoot; if (thread) { shadowRoot.querySelector('#process-name').textContent = thread.parent.userFriendlyName; shadowRoot.querySelector('#thread-name').textContent = thread.userFriendlyName; } else { shadowRoot.querySelector('#process-name').parentElement.style.display = 'none'; shadowRoot.querySelector('#thread-name').textContent = cpuSlice.title; } shadowRoot.querySelector('#start').textContent = tv.c.analysis.tsString(cpuSlice.start); shadowRoot.querySelector('#duration').textContent = tv.c.analysis.tsString(cpuSlice.duration); var runningThreadEl = shadowRoot.querySelector('#running-thread'); var timeSlice = cpuSlice.<API key>(); if (!timeSlice) { runningThreadEl.parentElement.style.display = 'none'; } else { var threadLink = document.createElement('tv-c-analysis-link'); threadLink.selection = new tv.c.Selection(timeSlice); threadLink.textContent = 'Click to select'; runningThreadEl.parentElement.style.display = ''; runningThreadEl.textContent = ''; runningThreadEl.appendChild(threadLink); } shadowRoot.querySelector('#args').object = cpuSlice.args; } }); </script> </polymer-element>
.editable:hover { background-color: #FDFDFF; box-shadow: 0 0 20px #D5E3ED; -<API key>: padding-box; -<API key>: 5px; -moz-border-radius: 5px; border-radius: 5px; } #wysihtml5-toolbar { box-shadow: 0 0 5px #999; position: fixed; top: 10px; left: 10px; width: 50px; -<API key>: padding-box; -<API key>: 5px; -moz-border-radius: 5px; border-radius: 5px; } #wysihtml5-toolbar .dialog { background-color: #f8f8f7; box-shadow: 0 0 10px #999; display: block; left: 60px; padding: 10px; position: absolute; top: 120px; width: 300px; -<API key>: padding-box; -<API key>: 5px; -moz-border-radius: 5px; border-radius: 5px; } #wysihtml5-toolbar a { display: inline-block; height: 50px; width: 48px; border: 1px solid #ddd; } #wysihtml5-toolbar a.cmd { background-color: #f8f8f7; background-position: center center; background-repeat: no-repeat; text-indent: -999px; } #wysihtml5-toolbar a.cmd:first-child { -<API key>: 5px 5px 0 0; -moz-border-radius: 5px 5px 0 0; border-radius: 5px 5px 0 0; } #wysihtml5-toolbar a.cmd:last-child { background-color: red; -<API key>: 0 0 5px 5px; -moz-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; } #wysihtml5-toolbar a.italic { background-image: url(/static/images/icons/<API key>.png); } #wysihtml5-toolbar a.bold { background-image: url(/static/images/icons/glyphicons_102_bold.png); } #wysihtml5-toolbar a.link { background-image: url(/static/images/icons/glyphicons_050_link.png); } #wysihtml5-toolbar a.img { background-image: url(/static/images/icons/<API key>.png); } #wysihtml5-toolbar a.list { background-image: url(/static/images/icons/glyphicons_114_list.png); } #wysihtml5-toolbar a.blockquote { background-image: url(/static/images/icons/<API key>.png); } #wysihtml5-toolbar a.heading { color: #000; font-weight: bold; height: 30px; padding: 10px 0 0 0; text-align: center; text-indent: 0; } #wysihtml5-toolbar a.save { background-color: #C1E3D4; background-image: url(/static/images/icons/glyphicons_206_ok_2.png); } #wysihtml5-toolbar a.cancel { background-color: #E3C1D1; background-image: url(/static/images/icons/<API key>.png); }
package net.sourceforge.pmd.rules.design; import net.sourceforge.pmd.AbstractRule; import net.sourceforge.pmd.ast.<API key>; import net.sourceforge.pmd.ast.<API key>; import net.sourceforge.pmd.ast.<API key>; import net.sourceforge.pmd.ast.ASTExpression; import net.sourceforge.pmd.ast.ASTName; import net.sourceforge.pmd.ast.ASTNullLiteral; import net.sourceforge.pmd.ast.<API key>; import net.sourceforge.pmd.symboltable.<API key>; // TODO - should check that this is not the first assignment. e.g., this is OK: // Object x; // x = null; public class NullAssignmentRule extends AbstractRule { public Object visit(ASTNullLiteral node, Object data) { if (node.getNthParent(5) instanceof <API key>) { <API key> n = (<API key>) node.getNthParent(5); if (<API key>(n)) { return data; } if (n.jjtGetNumChildren() > 2 && n.jjtGetChild(1) instanceof <API key>) { addViolation(data, node); } } else if (node.getNthParent(4) instanceof <API key>) { // "false" expression of ternary if (isBadTernary((<API key>)node.getNthParent(4))) { addViolation(data, node); } } else if (node.getNthParent(5) instanceof <API key> && node.getNthParent(4) instanceof ASTExpression) { // "true" expression of ternary if (isBadTernary((<API key>)node.getNthParent(5))) { addViolation(data, node); } } return data; } private boolean <API key>(<API key> n) { ASTName name = n.getFirstChildOfType(ASTName.class); return name != null && name.getNameDeclaration() instanceof <API key> && ((<API key>) name.getNameDeclaration()).getAccessNodeParent().isFinal(); } private boolean isBadTernary(<API key> n) { return n.isTernary() && !(n.jjtGetChild(0) instanceof <API key>); } }
'use strict'; jest.disableAutomock(); const React = require('React'); const ReactTestRenderer = require('react-test-renderer'); const VirtualizedList = require('VirtualizedList'); describe('VirtualizedList', () => { it('renders simple list', () => { const component = ReactTestRenderer.create( <VirtualizedList data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); it('renders empty list', () => { const component = ReactTestRenderer.create( <VirtualizedList data={[]} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); it('renders null list', () => { const component = ReactTestRenderer.create( <VirtualizedList data={undefined} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); it('renders all the bells and whistles', () => { const component = ReactTestRenderer.create( <VirtualizedList <API key>={() => <separator />} ListFooterComponent={() => <footer />} ListHeaderComponent={() => <header />} data={new Array(5).fill().map((_, ii) => ({id: String(ii)}))} keyExtractor={(item, index) => item.id} getItemLayout={({index}) => ({length: 50, offset: index * 50})} numColumns={2} refreshing={false} onRefresh={jest.fn()} renderItem={({item}) => <item value={item.id} />} /> ); expect(component).toMatchSnapshot(); }); it('test getItem functionality where data is not an Array', () => { const component = ReactTestRenderer.create( <VirtualizedList data={new Map([['id_0', {key: 'item_0'}]])} getItem={(data, index) => data.get('id_' + index)} getItemCount={(data: Map) => data.size} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); });
#include "config.h" #include <stddef.h> #include <stdint.h> #include <string.h> #include "common/attributes.h" #include "common/intops.h" #include "src/itx.h" #include "src/itx_1d.h" static NOINLINE void inv_txfm_add_c(pixel *dst, const ptrdiff_t stride, coef *const coeff, const int eob, const int w, const int h, const int shift, const itx_1d_fn first_1d_fn, const itx_1d_fn second_1d_fn, const int has_dconly HIGHBD_DECL_SUFFIX) { assert(w >= 4 && w <= 64); assert(h >= 4 && h <= 64); assert(eob >= 0); const int is_rect2 = w * 2 == h || h * 2 == w; const int rnd = (1 << shift) >> 1; if (eob < has_dconly) { int dc = coeff[0]; coeff[0] = 0; if (is_rect2) dc = (dc * 181 + 128) >> 8; dc = (dc * 181 + 128) >> 8; dc = (dc + rnd) >> shift; dc = (dc * 181 + 128 + 2048) >> 12; for (int y = 0; y < h; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < w; x++) dst[x] = iclip_pixel(dst[x] + dc); return; } const int sh = imin(h, 32), sw = imin(w, 32); #if BITDEPTH == 8 const int row_clip_min = INT16_MIN; const int col_clip_min = INT16_MIN; #else const int row_clip_min = (int) ((unsigned) ~bitdepth_max << 7); const int col_clip_min = (int) ((unsigned) ~bitdepth_max << 5); #endif const int row_clip_max = ~row_clip_min; const int col_clip_max = ~col_clip_min; int32_t tmp[64 * 64], *c = tmp; for (int y = 0; y < sh; y++, c += w) { if (is_rect2) for (int x = 0; x < sw; x++) c[x] = (coeff[y + x * sh] * 181 + 128) >> 8; else for (int x = 0; x < sw; x++) c[x] = coeff[y + x * sh]; first_1d_fn(c, 1, row_clip_min, row_clip_max); } memset(coeff, 0, sizeof(*coeff) * sw * sh); for (int i = 0; i < w * sh; i++) tmp[i] = iclip((tmp[i] + rnd) >> shift, col_clip_min, col_clip_max); for (int x = 0; x < w; x++) second_1d_fn(&tmp[x], w, col_clip_min, col_clip_max); c = tmp; for (int y = 0; y < h; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < w; x++) dst[x] = iclip_pixel(dst[x] + ((*c++ + 8) >> 4)); } #define inv_txfm_fn(type1, type2, w, h, shift, has_dconly) \ static void \ inv_txfm_add_##type1##_##type2##_##w##x##h##_c(pixel *dst, \ const ptrdiff_t stride, \ coef *const coeff, \ const int eob \ HIGHBD_DECL_SUFFIX) \ { \ inv_txfm_add_c(dst, stride, coeff, eob, w, h, shift, \ dav1d_inv_##type1##w##_1d_c, dav1d_inv_##type2##h##_1d_c, \ has_dconly HIGHBD_TAIL_SUFFIX); \ } #define inv_txfm_fn64(w, h, shift) \ inv_txfm_fn(dct, dct, w, h, shift, 1) #define inv_txfm_fn32(w, h, shift) \ inv_txfm_fn64(w, h, shift) \ inv_txfm_fn(identity, identity, w, h, shift, 0) #define inv_txfm_fn16(w, h, shift) \ inv_txfm_fn32(w, h, shift) \ inv_txfm_fn(adst, dct, w, h, shift, 0) \ inv_txfm_fn(dct, adst, w, h, shift, 0) \ inv_txfm_fn(adst, adst, w, h, shift, 0) \ inv_txfm_fn(dct, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, dct, w, h, shift, 0) \ inv_txfm_fn(adst, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, adst, w, h, shift, 0) \ inv_txfm_fn(flipadst, flipadst, w, h, shift, 0) \ inv_txfm_fn(identity, dct, w, h, shift, 0) \ inv_txfm_fn(dct, identity, w, h, shift, 0) \ #define inv_txfm_fn84(w, h, shift) \ inv_txfm_fn16(w, h, shift) \ inv_txfm_fn(identity, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, identity, w, h, shift, 0) \ inv_txfm_fn(identity, adst, w, h, shift, 0) \ inv_txfm_fn(adst, identity, w, h, shift, 0) \ inv_txfm_fn84( 4, 4, 0) inv_txfm_fn84( 4, 8, 0) inv_txfm_fn84( 4, 16, 1) inv_txfm_fn84( 8, 4, 0) inv_txfm_fn84( 8, 8, 1) inv_txfm_fn84( 8, 16, 1) inv_txfm_fn32( 8, 32, 2) inv_txfm_fn84(16, 4, 1) inv_txfm_fn84(16, 8, 1) inv_txfm_fn16(16, 16, 2) inv_txfm_fn32(16, 32, 1) inv_txfm_fn64(16, 64, 2) inv_txfm_fn32(32, 8, 2) inv_txfm_fn32(32, 16, 1) inv_txfm_fn32(32, 32, 2) inv_txfm_fn64(32, 64, 1) inv_txfm_fn64(64, 16, 2) inv_txfm_fn64(64, 32, 1) inv_txfm_fn64(64, 64, 2) static void <API key>(pixel *dst, const ptrdiff_t stride, coef *const coeff, const int eob HIGHBD_DECL_SUFFIX) { int32_t tmp[4 * 4], *c = tmp; for (int y = 0; y < 4; y++, c += 4) { for (int x = 0; x < 4; x++) c[x] = coeff[y + x * 4] >> 2; dav1d_inv_wht4_1d_c(c, 1); } memset(coeff, 0, sizeof(*coeff) * 4 * 4); for (int x = 0; x < 4; x++) dav1d_inv_wht4_1d_c(&tmp[x], 4); c = tmp; for (int y = 0; y < 4; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < 4; x++) dst[x] = iclip_pixel(dst[x] + *c++); } COLD void bitfn(dav1d_itx_dsp_init)(<API key> *const c) { #define assign_itx_all_fn64(w, h, pfx) \ c->itxfm_add[pfx##TX_##w##X##h][DCT_DCT ] = \ <API key>##w##x##h##_c #define assign_itx_all_fn32(w, h, pfx) \ assign_itx_all_fn64(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][IDTX] = \ <API key>##w##x##h##_c #define assign_itx_all_fn16(w, h, pfx) \ assign_itx_all_fn32(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][DCT_ADST ] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_DCT ] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_ADST] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_FLIPADST] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_ADST] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][DCT_FLIPADST] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_DCT] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_FLIPADST] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][H_DCT] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_DCT] = \ <API key>##w##x##h##_c #define assign_itx_all_fn84(w, h, pfx) \ assign_itx_all_fn16(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][H_FLIPADST] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_FLIPADST] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][H_ADST] = \ <API key>##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_ADST] = \ <API key>##w##x##h##_c; \ memset(c, 0, sizeof(*c)); /* Zero unused function pointer elements. */ c->itxfm_add[TX_4X4][WHT_WHT] = <API key>; assign_itx_all_fn84( 4, 4, ); assign_itx_all_fn84( 4, 8, R); assign_itx_all_fn84( 4, 16, R); assign_itx_all_fn84( 8, 4, R); assign_itx_all_fn84( 8, 8, ); assign_itx_all_fn84( 8, 16, R); assign_itx_all_fn32( 8, 32, R); assign_itx_all_fn84(16, 4, R); assign_itx_all_fn84(16, 8, R); assign_itx_all_fn16(16, 16, ); assign_itx_all_fn32(16, 32, R); assign_itx_all_fn64(16, 64, R); assign_itx_all_fn32(32, 8, R); assign_itx_all_fn32(32, 16, R); assign_itx_all_fn32(32, 32, ); assign_itx_all_fn64(32, 64, R); assign_itx_all_fn64(64, 16, R); assign_itx_all_fn64(64, 32, R); assign_itx_all_fn64(64, 64, ); #if HAVE_ASM #if ARCH_AARCH64 || ARCH_ARM bitfn(<API key>)(c); #endif #if ARCH_X86 bitfn(<API key>)(c); #endif #endif }
#include <limits.h> #include <stddef.h> #include <stdint.h> #include "base/files/file_path.h" #include "base/files/memory_mapped_file.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/strings/string_piece.h" #include "ipc/ipc_message.h" #include "tools/ipc_fuzzer/message_lib/message_cracker.h" #include "tools/ipc_fuzzer/message_lib/message_file.h" #include "tools/ipc_fuzzer/message_lib/message_file_format.h" #include "tools/ipc_fuzzer/message_lib/message_names.h" namespace ipc_fuzzer { namespace { // Helper class to read IPC message file into a MessageVector and // fix message types. class Reader { public: Reader(const base::FilePath& path); bool Read(MessageVector* messages); private: template <typename T> bool CutObject(const T** object); // Reads the header, checks magic and version. bool ReadHeader(); bool MapFile(); bool ReadMessages(); // Last part of the file is a string table for message names. bool ReadStringTable(); // Reads type <-> name mapping into name_map_. References string table. bool ReadNameTable(); // Removes obsolete messages from the vector. bool <API key>(); // Does type -> name -> correct_type fixup. void FixMessageTypes(); // Raw data. base::FilePath path_; base::MemoryMappedFile mapped_file_; base::StringPiece file_data_; base::StringPiece string_table_; // Parsed data. const FileHeader* header_; MessageVector* messages_; MessageNames name_map_; <API key>(Reader); }; Reader::Reader(const base::FilePath& path) : path_(path), header_(NULL), messages_(NULL) { } template <typename T> bool Reader::CutObject(const T** object) { if (file_data_.size() < sizeof(T)) { LOG(ERROR) << "Unexpected EOF."; return false; } *object = reinterpret_cast<const T*>(file_data_.data()); file_data_.remove_prefix(sizeof(T)); return true; } bool Reader::ReadHeader() { if (!CutObject<FileHeader>(&header_)) return false; if (header_->magic != FileHeader::kMagicValue) { LOG(ERROR) << path_.value() << " is not an IPC message file."; return false; } if (header_->version != FileHeader::kCurrentVersion) { LOG(ERROR) << "Wrong version for message file " << path_.value() << ". " << "File version is " << header_->version << ", " << "current version is " << FileHeader::kCurrentVersion << "."; return false; } return true; } bool Reader::MapFile() { if (!mapped_file_.Initialize(path_)) { LOG(ERROR) << "Failed to map testcase: " << path_.value(); return false; } const char* data = reinterpret_cast<const char*>(mapped_file_.data()); file_data_ = base::StringPiece(data, mapped_file_.length()); return true; } bool Reader::ReadMessages() { for (size_t i = 0; i < header_->message_count; ++i) { const char* begin = file_data_.begin(); const char* end = file_data_.end(); IPC::Message::NextMessageInfo info; IPC::Message::FindNext(begin, end, &info); if (!info.message_found) { LOG(ERROR) << "Failed to parse message."; return false; } CHECK_EQ(info.message_end, info.pickle_end); size_t msglen = info.message_end - begin; if (msglen > INT_MAX) { LOG(ERROR) << "Message too large."; return false; } // Copy is necessary to fix message type later. IPC::Message const_message(begin, msglen); messages_->push_back(std::make_unique<IPC::Message>(const_message)); file_data_.remove_prefix(msglen); } return true; } bool Reader::ReadStringTable() { size_t name_count = header_->name_count; if (!name_count) return true; if (name_count > file_data_.size() / sizeof(NameTableEntry)) { LOG(ERROR) << "Invalid name table size: " << name_count; return false; } size_t string_table_offset = name_count * sizeof(NameTableEntry); string_table_ = file_data_.substr(string_table_offset); if (string_table_.empty()) { LOG(ERROR) << "Missing string table."; return false; } if (string_table_.end()[-1] != '\0') { LOG(ERROR) << "String table doesn't end with NUL."; return false; } return true; } bool Reader::ReadNameTable() { for (size_t i = 0; i < header_->name_count; ++i) { const NameTableEntry* entry; if (!CutObject<NameTableEntry>(&entry)) return false; size_t offset = entry->string_table_offset; if (offset >= string_table_.size()) { LOG(ERROR) << "Invalid string table offset: " << offset; return false; } name_map_.Add(entry->type, string_table_.data() + offset); } return true; } bool Reader::<API key>() { MessageVector::iterator it = messages_->begin(); while (it != messages_->end()) { uint32_t type = (*it)->type(); if (!name_map_.TypeExists(type)) { LOG(ERROR) << "Missing name table entry for type " << type; return false; } const std::string& name = name_map_.TypeToName(type); if (!MessageNames::GetInstance()->NameExists(name)) { LOG(WARNING) << "Unknown message " << name; it = messages_->erase(it); } else { ++it; } } return true; } // Message types are based on line numbers, so a minor edit of *_messages.h // changes the types of messages in that file. The types are fixed here to // increase the lifetime of message files. This is only a partial fix because // message arguments and structure layouts can change as well. void Reader::FixMessageTypes() { for (const auto& message : *messages_) { uint32_t type = message->type(); const std::string& name = name_map_.TypeToName(type); uint32_t correct_type = MessageNames::GetInstance()->NameToType(name); if (type != correct_type) MessageCracker::SetMessageType(message.get(), correct_type); } } bool Reader::Read(MessageVector* messages) { messages_ = messages; if (!MapFile()) return false; if (!ReadHeader()) return false; if (!ReadMessages()) return false; if (!ReadStringTable()) return false; if (!ReadNameTable()) return false; if (!<API key>()) return false; FixMessageTypes(); return true; } } // namespace bool MessageFile::Read(const base::FilePath& path, MessageVector* messages) { Reader reader(path); return reader.Read(messages); } } // namespace ipc_fuzzer
#include "chrome/browser/renderer_host/<API key>.h" namespace { const char* const kKeyName = "<API key>"; } // namespace <API key>::<API key>() : is_prerender_(false) { } // static <API key>* <API key>::Get( const net::URLRequest* request) { DCHECK(request); return static_cast<<API key>*>(request->GetUserData(kKeyName)); } // static <API key>* <API key>::Create( net::URLRequest* request) { DCHECK(request); DCHECK(!Get(request)); <API key>* user_data = new <API key>(); request->SetUserData(kKeyName, user_data); return user_data; } // static void <API key>::Delete(net::URLRequest* request) { DCHECK(request); request->SetUserData(kKeyName, NULL); }
#ifndef <API key> #define <API key> #pragma once #include <set> #include "base/id_map.h" #include "base/memory/scoped_ptr.h" #include "base/process.h" #include "base/process_util.h" #include "base/time.h" #include "chrome/common/visitedlink_common.h" #include "ipc/ipc_sync_channel.h" #include "ui/gfx/surface/transport_dib.h" class Profile; struct <API key>; namespace base { class SharedMemory; } namespace net { class <API key>; } // Virtual interface that represents the browser side of the browser <-> // renderer communication channel. There will generally be one // RenderProcessHost per renderer process. // The concrete implementation of this class for normal use is the // <API key>. It may also be implemented by a testing interface // for mocking purposes. class RenderProcessHost : public IPC::Channel::Sender, public IPC::Channel::Listener { public: typedef IDMap<RenderProcessHost>::iterator iterator; // We classify renderers according to their highest privilege, and try // to group pages into renderers with similar privileges. // Note: it may be possible for a renderer to have multiple privileges, // in which case we call it an "extension" renderer. enum Type { TYPE_NORMAL, // Normal renderer, no extra privileges. TYPE_WEBUI, // Renderer with WebUI privileges, like New Tab. TYPE_EXTENSION, // Renderer with extension privileges. }; // Details for <API key> notifications. struct <API key> { <API key>(base::TerminationStatus status, int exit_code, bool <API key>) { this->status = status; this->exit_code = exit_code; this-><API key> = <API key>; } base::TerminationStatus status; int exit_code; bool <API key>; }; explicit RenderProcessHost(Profile* profile); virtual ~RenderProcessHost(); // Returns the user profile associated with this renderer process. Profile* profile() const { return profile_; } // Returns the unique ID for this child process. This can be used later in // a call to FromID() to get back to this object (this is used to avoid // sending non-threadsafe pointers to other threads). // This ID will be unique for all child processes, including workers, plugins, // etc. It is generated by ChildProcessInfo. int id() const { return id_; } // Returns true iff channel_ has been set to non-NULL. Use this for checking // if there is connection or not. bool HasConnection() { return channel_.get() != NULL; } bool <API key>() const { return <API key>; } void <API key>(bool enabled) { <API key> = enabled; } // Used for refcounting, each holder of this object must Attach and Release // just like it would for a COM object. This object should be allocated on // the heap; when no listeners own it any more, it will delete itself. void Attach(IPC::Channel::Listener* listener, int routing_id); // See Attach() void Release(int listener_id); // Listeners should call this when they've sent a "Close" message and // they're waiting for a "Close_ACK", so that if the renderer process // goes away we'll know that it was intentional rather than a crash. void <API key>(int32 listener_id); // Allows iteration over this RenderProcessHost's RenderViewHost listeners. // Use from UI thread only. typedef IDMap<IPC::Channel::Listener>::const_iterator listeners_iterator; listeners_iterator ListenersIterator() { return listeners_iterator(&listeners_); } IPC::Channel::Listener* GetListenerByID(int routing_id) { return listeners_.Lookup(routing_id); } IPC::SyncChannel* channel() { return channel_.get(); } // Called to inform the render process host of a new "max page id" for a // render view host. The render process host computes the largest page id // across all render view hosts and uses the value when it needs to // initialize a new renderer in place of the current one. void UpdateMaxPageID(int32 page_id); void <API key>(bool ignore_input_events) { <API key> = ignore_input_events; } bool ignore_input_events() { return <API key>; } // Returns how long the child has been idle. The definition of idle // depends on when a derived class calls <API key>(). // This is a rough indicator and its resolution should not be better than // 10 milliseconds. base::TimeDelta <API key>() const { return base::TimeTicks::Now() - <API key>; } // Call this function when it is evident that the child process is actively // performing some operation, for example if we just received an IPC message. void <API key>() { <API key> = base::TimeTicks::Now(); } // Try to shutdown the associated render process as fast as possible, but // only if |count| matches the number of render widgets that this process // controls. bool <API key>(size_t count); bool <API key>() { return <API key>; } // Initialize the new renderer process, returning true on success. This must // be called once before the object can be used, but can be called after // that with no effect. Therefore, if the caller isn't sure about whether // the process has been created, it should just call Init(). virtual bool Init( bool <API key>, bool <API key>) = 0; // Gets the next available routing id. virtual int GetNextRoutingID() = 0; // Called on the UI thread to cancel any outstanding resource requests for // the specified render widget. virtual void <API key>(int render_widget_id) = 0; // Called on the UI thread to simulate a ClosePage_ACK message to the // <API key>. Necessary for a cross-site request, in the case // that the original RenderViewHost is not live and thus cannot run an // onunload handler. virtual void <API key>( const <API key>& params) = 0; // Called on the UI thread to wait for the next UpdateRect message for the // specified render widget. Returns true if successful, and the msg out- // param will contain a copy of the received UpdateRect message. virtual bool WaitForUpdateMsg(int render_widget_id, const base::TimeDelta& max_delay, IPC::Message* msg) = 0; // Called when a received message cannot be decoded. virtual void ReceivedBadMessage() = 0; // Track the count of visible widgets. Called by listeners to register and // unregister visibility. virtual void WidgetRestored() = 0; virtual void WidgetHidden() = 0; virtual void ViewCreated() = 0; // Informs the renderer about a new visited link table. virtual void <API key>(base::SharedMemory* table_memory) = 0; // Notify the renderer that a link was visited. virtual void AddVisitedLinks( const VisitedLinkCommon::Fingerprints& links) = 0; // Clear internal visited links buffer and ask the renderer to update link // coloring state for all of its links. virtual void ResetVisitedLinks() = 0; // Try to shutdown the associated renderer process as fast as possible. // If this renderer has any RenderViews with unload handlers, then this // function does nothing. The current implementation uses TerminateProcess. // Returns True if it was able to do fast shutdown. virtual bool <API key>() = 0; // Synchronously sends the message, waiting for the specified timeout. The // implementor takes ownership of the given Message regardless of whether or // not this method succeeds. Returns true on success. virtual bool SendWithTimeout(IPC::Message* msg, int timeout_ms) = 0; // Returns the process object associated with the child process. In certain // tests or single-process mode, this will actually represent the current // process. // NOTE: this is not necessarily valid immediately after calling Init, as // Init starts the process asynchronously. It's guaranteed to be valid after // the first IPC arrives. virtual base::ProcessHandle GetHandle() = 0; // Return the TransportDIB for the given id. On Linux, this can involve // mapping shared memory. On Mac, the shared memory is created in the browser // process and the cached metadata is returned. On Windows, this involves // duplicating the handle from the remote process. The RenderProcessHost // still owns the returned DIB. virtual TransportDIB* GetTransportDIB(TransportDIB::Id dib_id) = 0; // Flag to run the renderer in process. This is primarily // for debugging purposes. When running "in process", the // browser maintains a single RenderProcessHost which communicates // to a RenderProcess which is instantiated in the same process // with the Browser. All IPC between the Browser and the // Renderer is the same, it's just not crossing a process boundary. static bool <API key>() { return <API key>; } static void <API key>(bool value) { <API key> = value; } // Allows iteration over all the RenderProcessHosts in the browser. Note // that each host may not be active, and therefore may have NULL channels. static iterator AllHostsIterator(); // Returns the RenderProcessHost given its ID. Returns NULL if the ID does // not correspond to a live RenderProcessHost. static RenderProcessHost* FromID(int render_process_id); // Returns true if the caller should attempt to use an existing // RenderProcessHost rather than creating a new one. static bool <API key>(); // Get an existing RenderProcessHost associated with the given profile, if // possible. The renderer process is chosen randomly from suitable renderers // that share the same profile and type. // Returns NULL if no suitable renderer process is available, in which case // the caller is free to create a new renderer. static RenderProcessHost* <API key>(Profile* profile, Type type); // Overrides the default heuristic for limiting the max renderer process // count. This is useful for unit testing process limit behaviors. // A value of zero means to use the default heuristic. static void <API key>(size_t count); protected: // A proxy for our IPC::Channel that lives on the IO thread (see // browser_process.h) scoped_ptr<IPC::SyncChannel> channel_; // The registered listeners. When this list is empty or all NULL, we should // delete ourselves IDMap<IPC::Channel::Listener> listeners_; // The maximum page ID we've ever seen from the renderer process. int32 max_page_id_; // True if fast shutdown has been performed on this RPH. bool <API key>; // True if we've posted a DeleteTask and will be deleted soon. bool deleting_soon_; private: // The globally-unique identifier for this RPH. int id_; Profile* profile_; // set of listeners that expect the renderer process to close std::set<int> <API key>; // True if the process can be shut down suddenly. If this is true, then we're // sure that all the RenderViews in the process can be shutdown suddenly. If // it's false, then specific RenderViews might still be allowed to be shutdown // suddenly by checking their <API key>() flag. This can occur // if one tab has an unload event listener but another tab in the same process // doesn't. bool <API key>; // Set to true if we shouldn't send input events. We actually do the // filtering for this at the render widget level. bool <API key>; // See getter above. static bool <API key>; // Records the last time we regarded the child process active. base::TimeTicks <API key>; <API key>(RenderProcessHost); }; // Factory object for RenderProcessHosts. Using this factory allows tests to // swap out a different one to use a <API key>. class <API key> { public: virtual ~<API key>() {} virtual RenderProcessHost* <API key>( Profile* profile) const = 0; }; #endif // <API key>
package org.scalameter import org.scalameter.examples.BoxingCountBench import org.scalameter.examples.<API key> class <API key> extends <API key> { test("BoxingCountTest.all should be deterministic") { <API key>(new BoxingCountBench) } } class <API key> extends <API key> { test("<API key>.allocations should be deterministic") { <API key>(new <API key>) } }
define(["require"], function (require) { function boot(ev) { ev.target.removeEventListener("click", boot); require(["demos/water/water"]); } const start = document.querySelector(".code-demo.water [data-trigger='water.start']"); start.addEventListener("click", boot); start.disabled = false; });
#locale-settings { margin-top: 30px; } #preferred-locale { margin-top: 10px; } #locale-settings .label { color: #aaa; display: inline-block; font-size: 16px; font-weight: 300; margin: 6px 10px 0 0; text-align: right; width: 280px; vertical-align: top; } #locale-settings .locale-selector { display: inline-block; } #locale-settings .locale-selector .locale.select { width: 280px; } #locale-settings .locale-selector .locale.select .button { background: #272a2f; color: #aaaaaa; font-size: 16px; font-weight: 400; height: 36px; margin: 0; padding: 8px 12px; width: 100%; } #locale-settings .locale-selector .locale.select .menu { background: #272a2f; border: 1px solid #333941; border-top: none; top: 36px; left: -1px; width: 282px; z-index: 30; } #main form { margin: 0 auto; } #main form section { margin: 0 auto 70px; } #main form section h3 { margin-bottom: 20px; } #main .controls .cancel { float: none; margin: 9px; } #profile-form { display: block; position: relative; text-align: left; width: 620px; } #profile-form .field { text-align: left; } #profile-form .field:not(:last-child) { margin-bottom: 20px; } #profile-form .field input { color: #ffffff; background: #333941; border: 1px solid #4d5967; border-radius: 3px; float: none; width: 290px; padding: 4px; -moz-box-sizing: border-box; box-sizing: border-box; } #profile-form button { margin-top: 10px; } #profile-form .help { color: #888888; font-style: italic; margin-top: 5px; } .errorlist { color: #f36; list-style: none; margin: 0; margin-top: 5px; text-align: left; } .check-list { cursor: pointer; }
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.cpp Label Definition File: <API key>.label.xml Template File: sources-sink-66a.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Use a fixed file name * Sinks: w32CreateFile * BadSink : Open the file named in data using CreateFile() * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files * * */ #include "std_testcase.h" #ifdef _WIN32 #define BASEPATH "c:\\temp\\" #else #include <wchar.h> #define BASEPATH "/tmp/" #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" namespace <API key> { #ifndef OMITBAD /* bad function declaration */ void badSink(char * dataArray[]); void bad() { char * data; char * dataArray[5]; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; char *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = strlen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(char)] = '\0'; /* Eliminate CRLF */ replace = strchr(data, '\r'); if (replace) { *replace = '\0'; } replace = strchr(data, '\n'); if (replace) { *replace = '\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } /* put data in array */ dataArray[2] = data; badSink(dataArray); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(char * dataArray[]); static void goodG2B() { char * data; char * dataArray[5]; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; /* FIX: Use a fixed file name */ strcat(data, "file.txt"); dataArray[2] = data; goodG2BSink(dataArray); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace <API key>; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
#include "debug/VIOPci.hh" #include "dev/virtio/pci.hh" #include "mem/packet_access.hh" #include "params/PciVirtIO.hh" PciVirtIO::PciVirtIO(const Params *params) : PciDevice(params), queueNotify(0), <API key>(false), vio(*params->vio), callbackKick(this) { // Override the subsystem ID with the device ID from VirtIO config.subsystemID = htole(vio.deviceId); BARSize[0] = BAR0_SIZE_BASE + vio.configSize; vio.<API key>(&callbackKick); } PciVirtIO::~PciVirtIO() { } Tick PciVirtIO::read(PacketPtr pkt) { const unsigned M5_VAR_USED size(pkt->getSize()); int bar; Addr offset; if (!getBAR(pkt->getAddr(), bar, offset)) panic("Invalid PCI memory access to unmapped memory.\n"); assert(bar == 0); DPRINTF(VIOPci, "Reading offset 0x%x [len: %i]\n", offset, size); // Forward device configuration writes to the device VirtIO model if (offset >= OFF_VIO_DEVICE) { vio.readConfig(pkt, offset - OFF_VIO_DEVICE); return 0; } pkt->makeResponse(); switch(offset) { case OFF_DEVICE_FEATURES: DPRINTF(VIOPci, " DEVICE_FEATURES request\n"); assert(size == sizeof(uint32_t)); pkt->set<uint32_t>(vio.deviceFeatures); break; case OFF_GUEST_FEATURES: DPRINTF(VIOPci, " GUEST_FEATURES request\n"); assert(size == sizeof(uint32_t)); pkt->set<uint32_t>(vio.getGuestFeatures()); break; case OFF_QUEUE_ADDRESS: DPRINTF(VIOPci, " QUEUE_ADDRESS request\n"); assert(size == sizeof(uint32_t)); pkt->set<uint32_t>(vio.getQueueAddress()); break; case OFF_QUEUE_SIZE: DPRINTF(VIOPci, " QUEUE_SIZE request\n"); assert(size == sizeof(uint16_t)); pkt->set<uint16_t>(vio.getQueueSize()); break; case OFF_QUEUE_SELECT: DPRINTF(VIOPci, " QUEUE_SELECT\n"); assert(size == sizeof(uint16_t)); pkt->set<uint16_t>(vio.getQueueSelect()); break; case OFF_QUEUE_NOTIFY: DPRINTF(VIOPci, " QUEUE_NOTIFY request\n"); assert(size == sizeof(uint16_t)); pkt->set<uint16_t>(queueNotify); break; case OFF_DEVICE_STATUS: DPRINTF(VIOPci, " DEVICE_STATUS request\n"); assert(size == sizeof(uint8_t)); pkt->set<uint8_t>(vio.getDeviceStatus()); break; case OFF_ISR_STATUS: { DPRINTF(VIOPci, " ISR_STATUS\n"); assert(size == sizeof(uint8_t)); uint8_t isr_status(<API key> ? 1 : 0); <API key> = false; pkt->set<uint8_t>(isr_status); } break; default: panic("Unhandled read offset (0x%x)\n", offset); } return 0; } Tick PciVirtIO::write(PacketPtr pkt) { const unsigned M5_VAR_USED size(pkt->getSize()); int bar; Addr offset; if (!getBAR(pkt->getAddr(), bar, offset)) panic("Invalid PCI memory access to unmapped memory.\n"); assert(bar == 0); DPRINTF(VIOPci, "Writing offset 0x%x [len: %i]\n", offset, size); // Forward device configuration writes to the device VirtIO model if (offset >= OFF_VIO_DEVICE) { vio.writeConfig(pkt, offset - OFF_VIO_DEVICE); return 0; } pkt->makeResponse(); switch(offset) { case OFF_DEVICE_FEATURES: warn("Guest tried to write device features."); break; case OFF_GUEST_FEATURES: DPRINTF(VIOPci, " WRITE GUEST_FEATURES request\n"); assert(size == sizeof(uint32_t)); vio.setGuestFeatures(pkt->get<uint32_t>()); break; case OFF_QUEUE_ADDRESS: DPRINTF(VIOPci, " WRITE QUEUE_ADDRESS\n"); assert(size == sizeof(uint32_t)); vio.setQueueAddress(pkt->get<uint32_t>()); break; case OFF_QUEUE_SIZE: panic("Guest tried to write queue size."); break; case OFF_QUEUE_SELECT: DPRINTF(VIOPci, " WRITE QUEUE_SELECT\n"); assert(size == sizeof(uint16_t)); vio.setQueueSelect(pkt->get<uint16_t>()); break; case OFF_QUEUE_NOTIFY: DPRINTF(VIOPci, " WRITE QUEUE_NOTIFY\n"); assert(size == sizeof(uint16_t)); queueNotify = pkt->get<uint16_t>(); vio.onNotify(queueNotify); break; case OFF_DEVICE_STATUS: { assert(size == sizeof(uint8_t)); uint8_t status(pkt->get<uint8_t>()); DPRINTF(VIOPci, "VirtIO set status: 0x%x\n", status); vio.setDeviceStatus(status); } break; case OFF_ISR_STATUS: warn("Guest tried to write ISR status."); break; default: panic("Unhandled read offset (0x%x)\n", offset); } return 0; } void PciVirtIO::kick() { DPRINTF(VIOPci, "kick(): Sending interrupt...\n"); <API key> = true; intrPost(); } PciVirtIO * PciVirtIOParams::create() { return new PciVirtIO(this); }
/* $NetBSD: ecoff_machdep.h,v 1.1 2002/03/13 05:03:18 simonb Exp $ */ #include <mips/ecoff_machdep.h>
\documentclass{jarticle} \usepackage{plext} \usepackage{calc} \begin{document} %% cf. latex.ltx macros (from ltboxes) \makebox[60pt]{}\par \makebox[-30pt]{}\par % calc extension check \makebox[60pt+10pt]{}\par \makebox[-30pt/2*3]{}\par % robustness \section{\makebox[60pt]{}} \section{\makebox[-30pt]{}} %% plext.sty macros \pbox[60pt]{}\par \pbox[-30pt]{}\par % natural width % calc extension check \pbox[60pt+10pt]{}\par \pbox[-30pt/2*3]{}\par % natural width % robustness \section{\pbox<t>[60pt]{}} \section{\pbox<t>[-30pt]{}} \end{document}
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.cpp Label Definition File: <API key>.label.xml Template File: <API key>.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new * GoodSource: Allocate data using malloc() * Sinks: * GoodSink: Deallocate data using delete * BadSink : Deallocate data using free() * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "<API key>.h" namespace <API key> { <API key>::<API key>(long * dataCopy) { data = dataCopy; /* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */ data = new long; } <API key>::~<API key>() { /* FIX: Deallocate the memory using delete */ delete data; } } #endif /* OMITGOOD */
'use strict'; angular.module("ngLocale", [], ["$provide", function ($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "ERANAMES": [ "Before Christ", "Anno Domini" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 6, "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "STANDALONEMONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "d/M/yy h:mm a", "shortDate": "d/M/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "en-jm", "localeID": "en_JM", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER; } }); }]);
#ifndef <API key> #define <API key> #include <FL/gl.h> /* GLfloat GLubyte GLuint GLenum */ #include <FL/Fl.H> #include <FL/Fl_Gl_Window.H> #include <FL/Fl_Value_Input.H> #include <FL/Fl_Check_Button.H> class <API key> : public Fl_Gl_Window { public: <API key>(int x,int y ,int w,int h ,const char*l=0); void init_widget_set( const int number ,Fl_Value_Input* valinp_hue_min ,Fl_Value_Input* valinp_hue_max ,Fl_Check_Button* chebut_enable_sw ,Fl_Check_Button* chebut_rotate360_sw ); void <API key>( const int number ,const bool is_max); void set_min_or_max(const bool is_max ); void set_reset(void); private: int mouse_x_when_push_ ,mouse_y_when_push_; /* Hue Color Wheel */ double x_offset_; double hue_offset_; /* Hue min,max */ class guide_widget_set_ { public: Fl_Value_Input* valinp_hue_min; Fl_Value_Input* valinp_hue_max; Fl_Check_Button* chebut_enable_sw; Fl_Check_Button* chebut_rotate360_sw; }; std::vector< guide_widget_set_ > guide_widget_sets_; int hue_range_number_; bool hue_range_is_max_; void draw(); void draw_object_(); int handle(int event); void handle_push_( const int mx ,const int my ); void <API key>( const int mx ,const int my ); void handle_keyboard_( const int key , const char* text ); double xpos_from_hue_(const double hue); double hue_from_xpos_(const double xpos); double limit_new_hue_( double hue_o_new ,bool& rotate360_sw ); void <API key>( const bool rot360_sw ); }; #endif /* !<API key> */
from django.apps import AppConfig class <API key>(AppConfig): name = "contentstore" def ready(self): import contentstore.signals contentstore.signals
#include "base/prefs/json_pref_store.h" #include <algorithm> #include "base/bind.h" #include "base/callback.h" #include "base/file_util.h" #include "base/json/<API key>.h" #include "base/json/<API key>.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop_proxy.h" #include "base/<API key>.h" #include "base/threading/<API key>.h" #include "base/values.h" namespace { // Some extensions we'll tack on to copies of the Preferences files. const base::FilePath::CharType* kBadExtension = FILE_PATH_LITERAL("bad"); // Differentiates file loading between origin thread and passed // (aka file) thread. class <API key> : public base::<API key><<API key>> { public: <API key>(JsonPrefStore* delegate, base::SequencedTaskRunner* <API key>) : no_dir_(false), error_(PersistentPrefStore::<API key>), delegate_(delegate), <API key>(<API key>), origin_loop_proxy_(base::MessageLoopProxy::current()) { } void Start(const base::FilePath& path) { DCHECK(origin_loop_proxy_-><API key>()); <API key>->PostTask( FROM_HERE, base::Bind(&<API key>::ReadFileAndReport, this, path)); } // Deserializes JSON on the sequenced task runner. void ReadFileAndReport(const base::FilePath& path) { DCHECK(<API key>-><API key>()); value_.reset(DoReading(path, &error_, &no_dir_)); origin_loop_proxy_->PostTask( FROM_HERE, base::Bind(&<API key>::<API key>, this)); } // Reports deserialization result on the origin thread. void <API key>() { DCHECK(origin_loop_proxy_-><API key>()); delegate_->OnFileRead(value_.release(), error_, no_dir_); } static base::Value* DoReading(const base::FilePath& path, PersistentPrefStore::PrefReadError* error, bool* no_dir) { int error_code; std::string error_msg; <API key> serializer(path); base::Value* value = serializer.Deserialize(&error_code, &error_msg); HandleErrors(value, path, error_code, error_msg, error); *no_dir = !base::PathExists(path.DirName()); return value; } static void HandleErrors(const base::Value* value, const base::FilePath& path, int error_code, const std::string& error_msg, PersistentPrefStore::PrefReadError* error); private: friend class base::<API key><<API key>>; ~<API key>() {} bool no_dir_; PersistentPrefStore::PrefReadError error_; scoped_ptr<base::Value> value_; const scoped_refptr<JsonPrefStore> delegate_; const scoped_refptr<base::SequencedTaskRunner> <API key>; const scoped_refptr<base::MessageLoopProxy> origin_loop_proxy_; }; // static void <API key>::HandleErrors( const base::Value* value, const base::FilePath& path, int error_code, const std::string& error_msg, PersistentPrefStore::PrefReadError* error) { *error = PersistentPrefStore::<API key>; if (!value) { DVLOG(1) << "Error while loading JSON file: " << error_msg << ", file: " << path.value(); switch (error_code) { case <API key>::JSON_ACCESS_DENIED: *error = PersistentPrefStore::<API key>; break; case <API key>::<API key>: *error = PersistentPrefStore::<API key>; break; case <API key>::JSON_FILE_LOCKED: *error = PersistentPrefStore::<API key>; break; case <API key>::JSON_NO_SUCH_FILE: *error = PersistentPrefStore::<API key>; break; default: *error = PersistentPrefStore::<API key>; // JSON errors indicate file corruption of some sort. // Since the file is corrupt, move it to the side and continue with // empty preferences. This will result in them losing their settings. // We keep the old file for possible support and debugging assistance // as well as to detect if they're seeing these errors repeatedly. // TODO(erikkay) Instead, use the last known good file. base::FilePath bad = path.ReplaceExtension(kBadExtension); // If they've ever had a parse error before, put them in another bucket. // TODO(erikkay) if we keep this error checking for very long, we may // want to differentiate between recent and long ago errors. if (base::PathExists(bad)) *error = PersistentPrefStore::<API key>; base::Move(path, bad); break; } } else if (!value->IsType(base::Value::TYPE_DICTIONARY)) { *error = PersistentPrefStore::<API key>; } } } // namespace scoped_refptr<base::SequencedTaskRunner> JsonPrefStore::<API key>( const base::FilePath& filename, base::SequencedWorkerPool* worker_pool) { std::string token("json_pref_store-"); token.append(filename.AsUTF8Unsafe()); return worker_pool-><API key>( worker_pool-><API key>(token), base::SequencedWorkerPool::BLOCK_SHUTDOWN); } JsonPrefStore::JsonPrefStore(const base::FilePath& filename, base::SequencedTaskRunner* <API key>) : path_(filename), <API key>(<API key>), prefs_(new base::DictionaryValue()), read_only_(false), writer_(filename, <API key>), initialized_(false), read_error_(<API key>) {} bool JsonPrefStore::GetValue(const std::string& key, const base::Value** result) const { base::Value* tmp = NULL; if (!prefs_->Get(key, &tmp)) return false; if (result) *result = tmp; return true; } void JsonPrefStore::AddObserver(PrefStore::Observer* observer) { observers_.AddObserver(observer); } void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) { observers_.RemoveObserver(observer); } bool JsonPrefStore::HasObservers() const { return observers_.<API key>(); } bool JsonPrefStore::<API key>() const { return initialized_; } bool JsonPrefStore::GetMutableValue(const std::string& key, base::Value** result) { return prefs_->Get(key, result); } void JsonPrefStore::SetValue(const std::string& key, base::Value* value) { DCHECK(value); scoped_ptr<base::Value> new_value(value); base::Value* old_value = NULL; prefs_->Get(key, &old_value); if (!old_value || !value->Equals(old_value)) { prefs_->Set(key, new_value.release()); ReportValueChanged(key); } } void JsonPrefStore::SetValueSilently(const std::string& key, base::Value* value) { DCHECK(value); scoped_ptr<base::Value> new_value(value); base::Value* old_value = NULL; prefs_->Get(key, &old_value); if (!old_value || !value->Equals(old_value)) { prefs_->Set(key, new_value.release()); if (!read_only_) writer_.ScheduleWrite(this); } } void JsonPrefStore::RemoveValue(const std::string& key) { if (prefs_->Remove(key, NULL)) ReportValueChanged(key); } void JsonPrefStore::MarkNeedsEmptyValue(const std::string& key) { <API key>.insert(key); } bool JsonPrefStore::ReadOnly() const { return read_only_; } PersistentPrefStore::PrefReadError JsonPrefStore::GetReadError() const { return read_error_; } PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() { if (path_.empty()) { OnFileRead(NULL, <API key>, false); return <API key>; } PrefReadError error; bool no_dir; base::Value* value = <API key>::DoReading(path_, &error, &no_dir); OnFileRead(value, error, no_dir); return error; } void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate *error_delegate) { initialized_ = false; error_delegate_.reset(error_delegate); if (path_.empty()) { OnFileRead(NULL, <API key>, false); return; } // Start async reading of the preferences file. It will delete itself // in the end. scoped_refptr<<API key>> deserializer( new <API key>(this, <API key>.get())); deserializer->Start(path_); } void JsonPrefStore::CommitPendingWrite() { if (writer_.HasPendingWrite() && !read_only_) writer_.DoScheduledWrite(); } void JsonPrefStore::ReportValueChanged(const std::string& key) { FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key)); if (!read_only_) writer_.ScheduleWrite(this); } void JsonPrefStore::OnFileRead(base::Value* value_owned, PersistentPrefStore::PrefReadError error, bool no_dir) { scoped_ptr<base::Value> value(value_owned); read_error_ = error; if (no_dir) { FOR_EACH_OBSERVER(PrefStore::Observer, observers_, <API key>(false)); return; } initialized_ = true; switch (error) { case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: read_only_ = true; break; case <API key>: DCHECK(value.get()); prefs_.reset(static_cast<base::DictionaryValue*>(value.release())); break; case <API key>: // If the file just doesn't exist, maybe this is first run. In any case // there's no harm in writing out default prefs in this case. break; case <API key>: case <API key>: break; default: NOTREACHED() << "Unknown error: " << error; } if (error_delegate_.get() && error != <API key>) error_delegate_->OnError(error); FOR_EACH_OBSERVER(PrefStore::Observer, observers_, <API key>(true)); } JsonPrefStore::~JsonPrefStore() { CommitPendingWrite(); } bool JsonPrefStore::SerializeData(std::string* output) { // TODO(tc): Do we want to prune webkit preferences that match the default // value? <API key> serializer(output); serializer.set_pretty_print(true); scoped_ptr<base::DictionaryValue> copy( prefs_-><API key>()); // Iterates |<API key>| and if the key exists in |prefs_|, // ensure its empty ListValue or DictonaryValue is preserved. for (std::set<std::string>::const_iterator it = <API key>.begin(); it != <API key>.end(); ++it) { const std::string& key = *it; base::Value* value = NULL; if (!prefs_->Get(key, &value)) continue; if (value->IsType(base::Value::TYPE_LIST)) { const base::ListValue* list = NULL; if (value->GetAsList(&list) && list->empty()) copy->Set(key, new base::ListValue); } else if (value->IsType(base::Value::TYPE_DICTIONARY)) { const base::DictionaryValue* dict = NULL; if (value->GetAsDictionary(&dict) && dict->empty()) copy->Set(key, new base::DictionaryValue); } } return serializer.Serialize(*(copy.get())); }