answer
stringlengths
15
1.25M
package eventstreamapi import ( "github.com/aws/aws-sdk-go/private/protocol" "github.com/aws/aws-sdk-go/private/protocol/eventstream" ) // Marshaler provides a marshaling interface for event types to event stream // messages. type Marshaler interface { MarshalEvent(protocol.PayloadMarshaler) (eventstream.Message, error) } // Encoder is an stream encoder that will encode an event stream message for // the transport. type Encoder interface { Encode(eventstream.Message) error } // EventWriter provides a wrapper around the underlying event stream encoder // for an io.WriteCloser. type EventWriter struct { encoder Encoder payloadMarshaler protocol.PayloadMarshaler eventTypeFor func(Marshaler) (string, error) } // NewEventWriter returns a new event stream writer, that will write to the // writer provided. Use the WriteEvent method to write an event to the stream. func NewEventWriter(encoder Encoder, pm protocol.PayloadMarshaler, eventTypeFor func(Marshaler) (string, error), ) *EventWriter { return &EventWriter{ encoder: encoder, payloadMarshaler: pm, eventTypeFor: eventTypeFor, } } // WriteEvent writes an event to the stream. Returns an error if the event // fails to marshal into a message, or writing to the underlying writer fails. func (w *EventWriter) WriteEvent(event Marshaler) error { msg, err := w.marshal(event) if err != nil { return err } return w.encoder.Encode(msg) } func (w *EventWriter) marshal(event Marshaler) (eventstream.Message, error) { eventType, err := w.eventTypeFor(event) if err != nil { return eventstream.Message{}, err } msg, err := event.MarshalEvent(w.payloadMarshaler) if err != nil { return eventstream.Message{}, err } msg.Headers.Set(EventTypeHeader, eventstream.StringValue(eventType)) return msg, nil }
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Sql.Models { using Newtonsoft.Json; using System.Linq; <summary> Represents recommended elastic pool metric. </summary> public partial class <API key> { <summary> Initializes a new instance of the <API key> class. </summary> public <API key>() { CustomInit(); } <summary> Initializes a new instance of the <API key> class. </summary> <param name="dateTime">The time of metric (ISO8601 format).</param> <param name="dtu">Gets or sets the DTUs (Database Transaction Units). See https://azure.microsoft.com/documentation/articles/<API key>/</param> <param name="sizeGB">Gets or sets size in gigabytes.</param> public <API key>(System.DateTime? dateTime = default(System.DateTime?), double? dtu = default(double?), double? sizeGB = default(double?)) { DateTime = dateTime; Dtu = dtu; SizeGB = sizeGB; CustomInit(); } <summary> An initialization method that performs custom operations like setting defaults </summary> partial void CustomInit(); <summary> Gets or sets the time of metric (ISO8601 format). </summary> [JsonProperty(PropertyName = "dateTime")] public System.DateTime? DateTime { get; set; } <summary> Gets or sets the DTUs (Database Transaction Units). See https://azure.microsoft.com/documentation/articles/<API key>/ </summary> [JsonProperty(PropertyName = "dtu")] public double? Dtu { get; set; } <summary> Gets or sets size in gigabytes. </summary> [JsonProperty(PropertyName = "sizeGB")] public double? SizeGB { get; set; } } }
<html><body><span wicket:id="label"><img alt="logo" src="../logo.png"><br>Some text<br>Some more text</span></body></html>
/ [<API key>.ts] // no errors expected class C<T extends Date> { constructor(public data: T) { } foo<U extends T>(x: U) { return x; } } interface Foo extends Date { foo: string; } var y: Foo = null; var c = new C(y); var r = c.foo(y); / [<API key>.js] // no errors expected var C = /** @class */ (function () { function C(data) { this.data = data; } C.prototype.foo = function (x) { return x; }; return C; }()); var y = null; var c = new C(y); var r = c.foo(y);
package proguard.classfile.attribute.annotation.target.visitor; import proguard.classfile.*; import proguard.classfile.attribute.CodeAttribute; import proguard.classfile.attribute.annotation.*; import proguard.classfile.attribute.annotation.target.*; /** * This interface specifies the methods for a visitor of <code>TargetInfo</code> * objects. * * @author Eric Lafortune */ public interface TargetInfoVisitor { public void <API key>( Clazz clazz, TypeAnnotation typeAnnotation, <API key> <API key>); public void <API key>( Clazz clazz, Method method, TypeAnnotation typeAnnotation, <API key> <API key>); public void <API key>( Clazz clazz, TypeAnnotation typeAnnotation, SuperTypeTargetInfo superTypeTargetInfo); public void <API key>(Clazz clazz, TypeAnnotation typeAnnotation, <API key> <API key>); public void <API key>(Clazz clazz, Field field, TypeAnnotation typeAnnotation, <API key> <API key>); public void <API key>(Clazz clazz, Method method, TypeAnnotation typeAnnotation, <API key> <API key>); public void <API key>( Clazz clazz, Field field, TypeAnnotation typeAnnotation, EmptyTargetInfo emptyTargetInfo); public void <API key>( Clazz clazz, Method method, TypeAnnotation typeAnnotation, EmptyTargetInfo emptyTargetInfo); public void <API key>( Clazz clazz, Method method, TypeAnnotation typeAnnotation, <API key> <API key>); public void <API key>( Clazz clazz, Method method, TypeAnnotation typeAnnotation, ThrowsTargetInfo throwsTargetInfo); public void <API key>( Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, <API key> <API key>); public void <API key>( Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, CatchTargetInfo catchTargetInfo); public void <API key>( Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, OffsetTargetInfo offsetTargetInfo); public void <API key>( Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, <API key> <API key>); }
/ [es6ClassTest8.ts] function f1(x:any) {return x;} class C { constructor() { var bar:any = (function() { return bar; // 'bar' should be resolvable }); var b = f1(f1(bar)); } } class Vector { static norm(v:Vector):Vector {return null;} static minus(v1:Vector, v2:Vector):Vector {return null;} static times(v1:Vector, v2:Vector):Vector {return null;} static cross(v1:Vector, v2:Vector):Vector {return null;} constructor(public x: number, public y: number, public z: number) { } static dot(v1:Vector, v2:Vector):Vector {return null;} } class Camera { public forward: Vector; public right: Vector; public up: Vector; constructor(public pos: Vector, lookAt: Vector) { var down = new Vector(0.0, -1.0, 0.0); this.forward = Vector.norm(Vector.minus(lookAt,this.pos)); this.right = Vector.times(down, Vector.norm(Vector.cross(this.forward, down))); this.up = Vector.times(down, Vector.norm(Vector.cross(this.forward, this.right))); } } / [es6ClassTest8.js] function f1(x) { return x; } var C = /** @class */ (function () { function C() { var bar = (function () { return bar; // 'bar' should be resolvable }); var b = f1(f1(bar)); } return C; }()); var Vector = /** @class */ (function () { function Vector(x, y, z) { this.x = x; this.y = y; this.z = z; } Vector.norm = function (v) { return null; }; Vector.minus = function (v1, v2) { return null; }; Vector.times = function (v1, v2) { return null; }; Vector.cross = function (v1, v2) { return null; }; Vector.dot = function (v1, v2) { return null; }; return Vector; }()); var Camera = /** @class */ (function () { function Camera(pos, lookAt) { this.pos = pos; var down = new Vector(0.0, -1.0, 0.0); this.forward = Vector.norm(Vector.minus(lookAt, this.pos)); this.right = Vector.times(down, Vector.norm(Vector.cross(this.forward, down))); this.up = Vector.times(down, Vector.norm(Vector.cross(this.forward, this.right))); } return Camera; }());
Long short-term memory unit (LSTM) recurrent network cell. The default non-peephole implementation is based on: http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf S. Hochreiter and J. Schmidhuber. "Long Short-Term Memory". Neural Computation, 9(8):1735-1780, 1997. The peephole implementation is based on: https://research.google.com/pubs/archive/43905.pdf Hasim Sak, Andrew Senior, and Francoise Beaufays. "Long short-term memory recurrent neural network architectures for large scale acoustic modeling." INTERSPEECH, 2014. The class uses optional peep-hole connections, optional cell clipping, and an optional projection layer. - - - # `tf.nn.rnn_cell.LSTMCell.__call__(inputs, state, scope=None)` {#LSTMCell.__call__} Run one step of LSTM. ## Args: * <b>`inputs`</b>: input Tensor, 2D, batch x num_units. * <b>`state`</b>: if `state_is_tuple` is False, this must be a state Tensor, `2-D, batch x state_size`. If `state_is_tuple` is True, this must be a tuple of state Tensors, both `2-D`, with column sizes `c_state` and `m_state`. * <b>`scope`</b>: VariableScope for the created subgraph; defaults to "LSTMCell". ## Returns: A tuple containing: - A `2-D, [batch x output_dim]`, Tensor representing the output of the LSTM after reading `inputs` when previous state was `state`. Here output_dim is: num_proj if num_proj was set, num_units otherwise. - Tensor(s) representing the new state of LSTM after reading `inputs` when the previous state was `state`. Same type and shape(s) as `state`. ## Raises: * <b>`ValueError`</b>: If input size cannot be inferred from inputs via static shape inference. - - - # `tf.nn.rnn_cell.LSTMCell.__init__(num_units, input_size=None, use_peepholes=False, cell_clip=None, initializer=None, num_proj=None, proj_clip=None, num_unit_shards=1, num_proj_shards=1, forget_bias=1.0, state_is_tuple=True, activation=tanh)` {#LSTMCell.__init__} Initialize the parameters for an LSTM cell. ## Args: * <b>`num_units`</b>: int, The number of units in the LSTM cell * <b>`input_size`</b>: Deprecated and unused. * <b>`use_peepholes`</b>: bool, set True to enable diagonal/peephole connections. * <b>`cell_clip`</b>: (optional) A float value, if provided the cell state is clipped by this value prior to the cell output activation. * <b>`initializer`</b>: (optional) The initializer to use for the weight and projection matrices. * <b>`num_proj`</b>: (optional) int, The output dimensionality for the projection matrices. If None, no projection is performed. * <b>`proj_clip`</b>: (optional) A float value. If `num_proj > 0` and `proj_clip` is provided, then the projected values are clipped elementwise to within `[-proj_clip, proj_clip]`. * <b>`num_unit_shards`</b>: How to split the weight matrix. If >1, the weight matrix is stored across num_unit_shards. * <b>`num_proj_shards`</b>: How to split the projection matrix. If >1, the projection matrix is stored across num_proj_shards. * <b>`forget_bias`</b>: Biases of the forget gate are initialized by default to 1 in order to reduce the scale of forgetting at the beginning of the training. * <b>`state_is_tuple`</b>: If True, accepted and returned states are 2-tuples of the `c_state` and `m_state`. If False, they are concatenated along the column axis. This latter behavior will soon be deprecated. * <b>`activation`</b>: Activation function of the inner states. - - - # `tf.nn.rnn_cell.LSTMCell.output_size` {#LSTMCell.output_size} - - - # `tf.nn.rnn_cell.LSTMCell.state_size` {#LSTMCell.state_size} - - - # `tf.nn.rnn_cell.LSTMCell.zero_state(batch_size, dtype)` {#LSTMCell.zero_state} Return zero-filled state tensor(s). ## Args: * <b>`batch_size`</b>: int, float, or unit Tensor representing the batch size. * <b>`dtype`</b>: the data type to use for the state. ## Returns: If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size x state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size x s]` for each s in `state_size`.
package io.cattle.platform.networking.host.dao.impl; import static io.cattle.platform.core.model.tables.HostTable.*; import static io.cattle.platform.core.model.tables.HostVnetMapTable.*; import static io.cattle.platform.core.model.tables.SubnetVnetMapTable.*; import static io.cattle.platform.core.model.tables.VnetTable.*; import java.util.List; import io.cattle.platform.core.model.Host; import io.cattle.platform.core.model.HostVnetMap; import io.cattle.platform.core.model.Network; import io.cattle.platform.core.model.Subnet; import io.cattle.platform.core.model.SubnetVnetMap; import io.cattle.platform.core.model.Vnet; import io.cattle.platform.core.model.tables.records.VnetRecord; import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao; import io.cattle.platform.networking.host.contants.HostOnlyConstants; import io.cattle.platform.networking.host.dao.HostOnlyDao; import io.cattle.platform.object.ObjectManager; import javax.inject.Inject; import org.jooq.Record; public class HostOnlyDaoImpl extends AbstractJooqDao implements HostOnlyDao { ObjectManager objectManager; @Override public Vnet getVnetForHost(Network network, Host host) { Long physicalHostId = host.getPhysicalHostId(); Record record = null; if ( physicalHostId == null ) { record = create() .select(VNET.fields()) .from(VNET) .join(HOST_VNET_MAP) .on(HOST_VNET_MAP.VNET_ID.eq(VNET.ID)) .where(VNET.NETWORK_ID.eq(network.getId()) .and(HOST_VNET_MAP.HOST_ID.eq(host.getId())) .and(HOST_VNET_MAP.REMOVED.isNull())) .fetchAny(); } else { record = create() .select(VNET.fields()) .from(VNET) .join(HOST_VNET_MAP) .on(HOST_VNET_MAP.VNET_ID.eq(VNET.ID)) .join(HOST) .on(HOST_VNET_MAP.HOST_ID.eq(HOST.ID)) .where(VNET.NETWORK_ID.eq(network.getId()) .and(HOST.PHYSICAL_HOST_ID.eq(physicalHostId)) .and(HOST_VNET_MAP.REMOVED.isNull())) .fetchAny(); } return record == null ? null : record.into(VnetRecord.class); } @Override public Vnet createVnetForHost(Network network, Host host, Subnet subnet, String uri) { if ( uri == null ) { uri = HostOnlyConstants.<API key>; } Vnet vnet = objectManager.create(Vnet.class, VNET.URI, uri, VNET.ACCOUNT_ID, network.getAccountId(), VNET.NETWORK_ID, network.getId()); objectManager.create(HostVnetMap.class, HOST_VNET_MAP.VNET_ID, vnet.getId(), HOST_VNET_MAP.HOST_ID, host.getId()); if ( subnet != null ) { objectManager.create(SubnetVnetMap.class, SUBNET_VNET_MAP.VNET_ID, vnet.getId(), SUBNET_VNET_MAP.SUBNET_ID, subnet.getId()); } return vnet; } @Override public HostVnetMap mapVnetToHost(Vnet vnet, Host host) { List<HostVnetMap> maps = objectManager.find(HostVnetMap.class, HOST_VNET_MAP.VNET_ID, vnet.getId(), HOST_VNET_MAP.HOST_ID, host.getId()); if ( maps.size() > 0 ) { return maps.get(0); } return objectManager.create(HostVnetMap.class, HOST_VNET_MAP.VNET_ID, vnet.getId(), HOST_VNET_MAP.HOST_ID, host.getId()); } public ObjectManager getObjectManager() { return objectManager; } @Inject public void setObjectManager(ObjectManager objectManager) { this.objectManager = objectManager; } }
using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Sql.Tests { public class UsageScenarioTests { [Fact] public void <API key>() { using (<API key> context = new <API key>(this)) { SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>(); // Get subscription usages for a location IEnumerable<SubscriptionUsage> subscriptionUsages = sqlClient.SubscriptionUsages.ListByLocation(<API key>.DefaultLocation); Assert.True(subscriptionUsages.Count() > 0); // Get a single subscription usage for a location SubscriptionUsage subscriptionUsage = sqlClient.SubscriptionUsages.Get(<API key>.DefaultLocation, "ServerQuota"); } } [Fact] public void TestGetUsageData() { using (<API key> context = new <API key>(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup(); Server server = context.CreateServer(resourceGroup); SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>(); // Get server Usages IEnumerable<ServerUsage> serverUsages = sqlClient.ServerUsages.ListByServer(resourceGroup.Name, server.Name); Assert.True(serverUsages.Count(s => s.ResourceName == server.Name) > 1); // Create a database and get usages string dbName = <API key>.GenerateName(); var dbInput = new Database() { Location = server.Location }; sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput); IEnumerable<DatabaseUsage> databaseUsages = sqlClient.DatabaseUsages.ListByDatabase(resourceGroup.Name, server.Name, dbName); Assert.True(databaseUsages.Where(db => db.ResourceName == dbName).Count() == 1); } } } }
module Fog module Compute class Ecloud class Real basic_request :<API key> end end end end
package org.asteriskjava.manager.event; public class DongleCENDEvent extends ManagerEvent { private static final long serialVersionUID = <API key>; private String device; private String endstatus; private String cccause; private String duration; private String callidx; public DongleCENDEvent(Object source) { super(source); } public String getDevice() { return this.device; } public void setDevice(String device) { this.device = device; } public String getCallidx() { return callidx; } public void setCallidx(String callidx) { this.callidx = callidx; } public String getCccause() { return cccause; } public void setCccause(String cccause) { this.cccause = cccause; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getEndstatus() { return endstatus; } public void setEndstatus(String endstatus) { this.endstatus = endstatus; } }
#if defined(MPI_VERSION) #if (MPI_VERSION > 3) || (MPI_VERSION == 3 && MPI_SUBVERSION >= 1) #define <API key> 1 #define <API key> 1 #define <API key> 1 #define <API key> 1 #define <API key> 1 #define <API key> 1 #endif #endif
PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,value LONGVARCHAR); INSERT INTO "meta" VALUES('version','43'); INSERT INTO "meta" VALUES('<API key>','43'); INSERT INTO "meta" VALUES('Default Search Provider ID','2'); INSERT INTO "meta" VALUES('Default Search Provider ID Backup','3'); INSERT INTO "meta" VALUES('Default Search Provider ID Backup Signature','Invalid signature'); INSERT INTO "meta" VALUES('Builtin Keyword Version','37'); CREATE TABLE keywords (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,<API key> INTEGER,<API key> INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,<API key> INTEGER DEFAULT 0,logo_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0, sync_guid VARCHAR); INSERT INTO "keywords" VALUES(2,'Google','google.com','http: CREATE TABLE keywords_backup (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,<API key> INTEGER,<API key> INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,<API key> INTEGER DEFAULT 0,logo_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0, sync_guid VARCHAR); INSERT INTO "keywords_backup" VALUES(2,'Google','google.com','http: CREATE TABLE logins (origin_url VARCHAR NOT NULL, action_url VARCHAR, username_element VARCHAR, username_value VARCHAR, password_element VARCHAR, password_value BLOB, submit_element VARCHAR, signon_realm VARCHAR NOT NULL,ssl_valid INTEGER NOT NULL,preferred INTEGER NOT NULL,date_created INTEGER NOT NULL,blacklisted_by_user INTEGER NOT NULL,scheme INTEGER NOT NULL,UNIQUE (origin_url, username_element, username_value, password_element, submit_element, signon_realm)); CREATE TABLE web_app_icons (url LONGVARCHAR,width int,height int,image BLOB, UNIQUE (url, width, height)); CREATE TABLE web_apps (url LONGVARCHAR UNIQUE,has_all_images INTEGER NOT NULL); CREATE TABLE autofill (name VARCHAR, value VARCHAR, value_lower VARCHAR, pair_id INTEGER PRIMARY KEY, count INTEGER DEFAULT 1); CREATE TABLE autofill_dates ( pair_id INTEGER DEFAULT 0, date_created INTEGER DEFAULT 0); CREATE TABLE autofill_profiles ( guid VARCHAR PRIMARY KEY, company_name VARCHAR, address_line_1 VARCHAR, address_line_2 VARCHAR, city VARCHAR, state VARCHAR, zipcode VARCHAR, country VARCHAR, country_code VARCHAR, date_modified INTEGER NOT NULL DEFAULT 0); CREATE TABLE <API key> ( guid VARCHAR, first_name VARCHAR, middle_name VARCHAR, last_name VARCHAR); CREATE TABLE <API key> ( guid VARCHAR, email VARCHAR); CREATE TABLE <API key> ( guid VARCHAR, type INTEGER DEFAULT 0, number VARCHAR); CREATE TABLE credit_cards ( guid VARCHAR PRIMARY KEY, name_on_card VARCHAR, expiration_month INTEGER, expiration_year INTEGER, <API key> BLOB, date_modified INTEGER NOT NULL DEFAULT 0); CREATE TABLE token_service (service VARCHAR PRIMARY KEY NOT NULL,encrypted_token BLOB); CREATE INDEX logins_signon ON logins (signon_realm); CREATE INDEX web_apps_url_index ON web_apps (url); CREATE INDEX autofill_name ON autofill (name); CREATE INDEX <API key> ON autofill (name, value_lower); CREATE INDEX <API key> ON autofill_dates (pair_id); COMMIT;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Larry's favorite LaTeX macros for making technical books. These have % been refined for years, starting with SIGGRAPH course notes in the % '90's, further refined for _Advanced RenderMan_. % % Please use or modify this at will. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Define typesetting commands for filenames and code % % Just like Advanced RenderMan -- all code in courier, keywords in text % courier but not bold. \def\codefont{\ttfamily} % font to use for code \def\ce{\codefont\bfseries} % emphasize something in code % % Define typesetting commands for filenames and code % \def\cf{\codefont} % abbreviation for \codefont \def\fn{\codefont} % in-line filenames & unix commands \def\kw{\codefont} % in-line keyword \newcommand{\var}[1]{{\kw \emph{#1}}} % variable \newcommand{\qkw}[1]{{\kw "#1"}} % quoted keyword \newcommand{\qkws}[1]{{\small \kw "#1"}} % quoted keyword, small \newcommand{\qkwf}[1]{{\footnotesize \kw "#1"}} % quoted keyword, tiny % Define some environments for easy typesetting of small amounts of % code. These are mostly just wrappers around verbatim, but the % different varieties also change font sizes. \newenvironment{code}{\small \verbatimtab}{\endverbatimtab} \newenvironment{smallcode}{\small \renewcommand{\baselinestretch}{0.8} \verbatimtab}{\endverbatimtab \renewcommand{\baselinestretch}{1}} \newenvironment{tinycode}{\footnotesize \renewcommand{\baselinestretch}{0.75} \verbatimtab}{\endverbatimtab \renewcommand{\baselinestretch}{1}} \begin{htmlonly} \renewenvironment{code}{\begin{verbatim}}{\end{verbatim}} \newenvironment{smallcode}{\begin{verbatim}}{\end{verbatim}} \newenvironment{tinycode}{\begin{verbatim}}{\end{verbatim}} \end{htmlonly} \newcommand{\includedcode}[1]{{\small \verbatimtabinput{ \newcommand{\smallincludedcode}[1]{{\small \renewcommand{\baselinestretch}{0.8} \verbatimtabinput{#1} \renewcommand{\baselinestretch}{1}}} \newcommand{\tinyincludedcode}[1]{{\footnotesize \renewcommand{\baselinestretch}{0.75} \verbatimtabinput{#1} \renewcommand{\baselinestretch}{1}}} % Also create a hyphenation list, essentially just to guarantee that % type names aren't hyphenated %\hyphenation{Attribute} % Handy for parameter lists \def\pl{{\rm\emph{...params...}\xspace}} \def\dotdotdot{{\rm\emph{...}\xspace}} \hyphenation{parameterlist} %begin{latexonly} \newenvironment{apilist}{\begin{list}{}{\medskip \item[]}}{\end{list}} \newcommand{\apiitem}[1]{\vspace{12pt} \noindent {\bf\tt #1} \vspace{-10pt}\begin{apilist}\nopagebreak[4]} \newcommand{\apiend}{\end{apilist}\medskip\pagebreak[2]} \def\bigspc{\makebox[72pt]{}} \def\spc{\makebox[24pt]{}} \def\halfspc{\makebox[12pt]{}} \def\neghalfspc{\hspace{-12pt}} \def\negspc{\hspace{-24pt}} \def\chapwidthbegin{} \def\chapwidthend{} %end{latexonly} \begin{htmlonly} \newcommand{\apiitem}[1]{\medskip \noindent {\bf #1} \begin{quote}} \newcommand{\apiend}{\end{quote}} \def\halfspc{\begin{rawhtml} &nbsp; &nbsp; \end{rawhtml}} \def\spc{\halfspc\halfspc} \pagecolor[named]{White} \def\chapwidthbegin{\begin{rawhtml}<p><table cellspacing=1><tr><td width=550>\end{rawhtml}} \def\chapwidthend{\begin{rawhtml}</td></tr></table>\end{rawhtml}} \end{htmlonly} \newcommand{\apibinding}[3]{\apiitem{#1\\[1ex]#2\\[1ex]#3}} \newcommand{\CPPBINDING}[1]{\par {\small C++ BINDING:}\par {\spc \codefont \newcommand{\PARAMETERS}{\par {\small PARAMETERS:} \par} \newcommand{\EXAMPLE}{\par {\small EXAMPLE:} \par} \newcommand{\EXAMPLES}{\par {\small EXAMPLES:} \par} \newcommand{\SEEALSO}{\par \hspace{-20pt} See Also: \par} % The \begin{algorithm} \end{algorithm} macros (in algorithm.sty) are % great for code that can fit all on one page. But when it can't, use % these macros. The first parameter is the caption, the second is the % label name. \newcommand{\longalgorithmbegin}[2]{\noindent\hrulefill \\ \refstepcounter{algorithm} \noindent {\bf Listing \arabic{chapter}.\arabic{algorithm}}: #1 \label{#2} \\ \addcontentsline{loa}{algorithm}{\numberline {\arabic{algorithm}} \noindent\hrulefill } \newcommand{\longalgorithmend}{\noindent\hrulefill \\} \def\NEW{\marginpar[\medskip\hfill~\fbox{\sffamily \Huge NEW!}~]{\medskip~\fbox{\sffamily \Huge NEW!}~}} \newcommand{\NEWdown}[1]{\marginpar[\vspace{#1}\hfill\fbox{\sffamily \Huge NEW!}]{\vspace{#1}\fbox{\sffamily \Huge NEW!}}} \def\DEPRECATED{\marginpar[\medskip\hfill~\fbox{\sffamily \Large Deprecated}]{\medskip~\fbox{\sffamily \Large Deprecated}}} \newcommand{\DEPRECATEDdown}[1]{\marginpar{\vspace{#1}\fbox{\sffamily \Large Deprecated}}} \def\CHANGED{\marginpar[\medskip\hfill~\fbox{\sffamily \huge CHANGED!}~]{\medskip~\fbox{\sffamily \huge CHANGED!}~}} \def\ENHANCED{\marginpar[\medskip\hfill~\fbox{\sffamily \huge ENHANCED}~]{\medskip~\fbox{\sffamily \huge ENHANCED}~}} \def\QUESTION{\marginpar[\medskip\hfill~\fbox{\sffamily \Huge ?}~~~~]{\medskip~\fbox{\sffamily \Huge ?}~~~~}} \newcommand{\indexapi}[1]{\index{#1@\tt#1\rm}} \newenvironment{annotate}{\medskip\sffamily\em\noindent}{\medskip} %\newenvironment{annotate}{\begin{comment}}{\end{comment}}
import shutil import tempfile from telemetry import decorators from telemetry.testing import <API key> from telemetry.testing import page_test_test_case from measurements import skpicture_printer class <API key>(page_test_test_case.PageTestTestCase): def setUp(self): self._options = <API key>.GetCopy() self._skp_outdir = tempfile.mkdtemp('_skp_test') def tearDown(self): shutil.rmtree(self._skp_outdir) @decorators.Disabled('android') def <API key>(self): ps = self.<API key>('blank.html') measurement = skpicture_printer.SkpicturePrinter(self._skp_outdir) results = self.RunMeasurement(measurement, ps, options=self._options) # Picture printing is not supported on all platforms. if results.failures: assert 'not supported' in results.failures[0].exc_info[1].message return saved_picture_count = results.<API key>( 'saved_picture_count') self.assertEquals(len(saved_picture_count), 1) self.assertGreater(saved_picture_count[0].<API key>(), 0)
<?php require_once 'Zend/Oauth/Signature/Plaintext.php'; class Zend_O<API key> extends <API key> { public function <API key><API key>() { $params = array( 'oauth_version' => '1.0', 'oauth_consumer_key' => 'dpf43f3p2l4k3l03', 'o<API key> => 'PLAINTEXT', 'oauth_timestamp' => '1191242090', 'oauth_nonce' => 'hsu94j3884jdopsl', 'oauth_version' => '1.0' ); $signature = new Zend_O<API key>('1234567890'); $this->assertEquals('1234567890&', $signature->sign($params)); } public function <API key><API key>() { $params = array( 'oauth_version' => '1.0', 'oauth_consumer_key' => 'dpf43f3p2l4k3l03', 'o<API key> => 'PLAINTEXT', 'oauth_timestamp' => '1191242090', 'oauth_nonce' => 'hsu94j3884jdopsl', 'oauth_version' => '1.0' ); $signature = new Zend_O<API key>('1234567890', '0987654321'); $this->assertEquals('1234567890&0987654321', $signature->sign($params)); } }
/** * @constructor * @param {!Element} relativeToElement * @param {!WebInspector.DialogDelegate} delegate */ WebInspector.Dialog = function(relativeToElement, delegate) { this._delegate = delegate; this._relativeToElement = relativeToElement; this._glassPane = new WebInspector.GlassPane(/** @type {!Document} */ (relativeToElement.ownerDocument)); WebInspector.GlassPane.<API key>.push(this); // Install glass pane capturing events. this._glassPane.element.tabIndex = 0; this._glassPane.element.addEventListener("focus", this._onGlassPaneFocus.bind(this), false); this._element = this._glassPane.element.createChild("div"); this._element.tabIndex = 0; this._element.addEventListener("focus", this._onFocus.bind(this), false); this._element.addEventListener("keydown", this._onKeyDown.bind(this), false); this._closeKeys = [ WebInspector.KeyboardShortcut.Keys.Enter.code, WebInspector.KeyboardShortcut.Keys.Esc.code, ]; delegate.show(this._element); this._position(); this._delegate.focus(); } /** * @return {?WebInspector.Dialog} */ WebInspector.Dialog.currentInstance = function() { return WebInspector.Dialog._instance; } /** * @param {!Element} relativeToElement * @param {!WebInspector.DialogDelegate} delegate */ WebInspector.Dialog.show = function(relativeToElement, delegate) { if (WebInspector.Dialog._instance) return; WebInspector.Dialog._instance = new WebInspector.Dialog(relativeToElement, delegate); } WebInspector.Dialog.hide = function() { if (!WebInspector.Dialog._instance) return; WebInspector.Dialog._instance._hide(); } WebInspector.Dialog.prototype = { focus: function() { this._element.focus(); }, _hide: function() { if (this._isHiding) return; this._isHiding = true; this._delegate.willHide(); delete WebInspector.Dialog._instance; WebInspector.GlassPane.<API key>.pop(); this._glassPane.dispose(); }, _onGlassPaneFocus: function(event) { this._hide(); }, _onFocus: function(event) { this._delegate.focus(); }, _position: function() { this._delegate.position(this._element, this._relativeToElement); }, _onKeyDown: function(event) { if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Tab.code) { event.preventDefault(); return; } if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Enter.code) this._delegate.onEnter(event); if (!event.handled && this._closeKeys.indexOf(event.keyCode) >= 0) { this._hide(); event.consume(true); } } }; /** * @constructor * @extends {WebInspector.Object} */ WebInspector.DialogDelegate = function() { /** @type {!Element} */ this.element; } WebInspector.DialogDelegate.prototype = { /** * @param {!Element} element */ show: function(element) { element.appendChild(this.element); this.element.classList.add("dialog-contents"); element.classList.add("dialog"); }, /** * @param {!Element} element * @param {!Element} relativeToElement */ position: function(element, relativeToElement) { var container = WebInspector.Dialog._modalHostView.element; var box = relativeToElement.boxInWindow(window).relativeToElement(container); var positionX = box.x + (relativeToElement.offsetWidth - element.offsetWidth) / 2; positionX = Number.constrain(positionX, 0, container.offsetWidth - element.offsetWidth); var positionY = box.y + (relativeToElement.offsetHeight - element.offsetHeight) / 2; positionY = Number.constrain(positionY, 0, container.offsetHeight - element.offsetHeight); element.style.position = "absolute"; element.positionAt(positionX, positionY, container); }, focus: function() { }, onEnter: function(event) { }, willHide: function() { }, __proto__: WebInspector.Object.prototype } /** @type {?WebInspector.View} */ WebInspector.Dialog._modalHostView = null; /** * @param {!WebInspector.View} view */ WebInspector.Dialog.setModalHostView = function(view) { WebInspector.Dialog._modalHostView = view; }; /** * FIXME: make utility method in Dialog, so clients use it instead of this getter. * Method should be like Dialog.showModalElement(position params, reposition callback). * @return {?WebInspector.View} */ WebInspector.Dialog.modalHostView = function() { return WebInspector.Dialog._modalHostView; }; WebInspector.Dialog.<API key> = function() { if (WebInspector.Dialog._instance) WebInspector.Dialog._instance._position(); };
// <API key>: Apache-2.0 WITH LLVM-exception // This file implements the ModuleFile class, which describes a module that // has been loaded from an AST file. #include "clang/Serialization/ModuleFile.h" #include "ASTReaderInternals.h" #include "clang/Serialization/ContinuousRangeMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace serialization; using namespace reader; ModuleFile::~ModuleFile() { delete static_cast<<API key> *>(<API key>); delete static_cast<<API key> *>(HeaderFileInfoTable); delete static_cast<<API key> *>(SelectorLookupTable); } template<typename Key, typename Offset, unsigned InitialCapacity> static void dumpLocalRemap(StringRef Name, const ContinuousRangeMap<Key, Offset, InitialCapacity> &Map) { if (Map.begin() == Map.end()) return; using MapType = ContinuousRangeMap<Key, Offset, InitialCapacity>; llvm::errs() << " " << Name << ":\n"; for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); I != IEnd; ++I) { llvm::errs() << " " << I->first << " -> " << I->second << "\n"; } } LLVM_DUMP_METHOD void ModuleFile::dump() { llvm::errs() << "\nModule: " << FileName << "\n"; if (!Imports.empty()) { llvm::errs() << " Imports: "; for (unsigned I = 0, N = Imports.size(); I != N; ++I) { if (I) llvm::errs() << ", "; llvm::errs() << Imports[I]->FileName; } llvm::errs() << "\n"; } // Remapping tables. llvm::errs() << " Base source location offset: " << SLocEntryBaseOffset << '\n'; dumpLocalRemap("Source location offset local -> global map", SLocRemap); llvm::errs() << " Base identifier ID: " << BaseIdentifierID << '\n' << " Number of identifiers: " << LocalNumIdentifiers << '\n'; dumpLocalRemap("Identifier ID local -> global map", IdentifierRemap); llvm::errs() << " Base macro ID: " << BaseMacroID << '\n' << " Number of macros: " << LocalNumMacros << '\n'; dumpLocalRemap("Macro ID local -> global map", MacroRemap); llvm::errs() << " Base submodule ID: " << BaseSubmoduleID << '\n' << " Number of submodules: " << LocalNumSubmodules << '\n'; dumpLocalRemap("Submodule ID local -> global map", SubmoduleRemap); llvm::errs() << " Base selector ID: " << BaseSelectorID << '\n' << " Number of selectors: " << LocalNumSelectors << '\n'; dumpLocalRemap("Selector ID local -> global map", SelectorRemap); llvm::errs() << " Base preprocessed entity ID: " << <API key> << '\n' << " Number of preprocessed entities: " << <API key> << '\n'; dumpLocalRemap("Preprocessed entity ID local -> global map", <API key>); llvm::errs() << " Base type index: " << BaseTypeIndex << '\n' << " Number of types: " << LocalNumTypes << '\n'; dumpLocalRemap("Type index local -> global map", TypeRemap); llvm::errs() << " Base decl ID: " << BaseDeclID << '\n' << " Number of decls: " << LocalNumDecls << '\n'; dumpLocalRemap("Decl ID local -> global map", DeclRemap); }
#include <linux/platform_device.h> #include <linux/fsl_devices.h> #include "ehci-fsl.h" /* FIXME: Power Managment is un-ported so temporarily disable it */ #undef CONFIG_PM /* PCI-based HCs are common, but plenty of non-PCI HCs are used too */ /* configure so an HC device and id are always provided */ /* always called with process context; sleeping is OK */ /** * usb_hcd_fsl_probe - initialize FSL-based HCDs * @drvier: Driver to be used for this HCD * @pdev: USB Host Controller being probed * Context: !in_interrupt() * * Allocates basic resources for this USB host controller. * */ int usb_hcd_fsl_probe(const struct hc_driver *driver, struct platform_device *pdev) { struct <API key> *pdata; struct usb_hcd *hcd; struct resource *res; int irq; int retval; unsigned int temp; pr_debug("initializing FSL-SOC USB Controller\n"); /* Need platform data for setup */ pdata = (struct <API key> *)pdev->dev.platform_data; if (!pdata) { dev_err(&pdev->dev, "No platform data for %s.\n", pdev->dev.bus_id); return -ENODEV; } /* * This is a host mode driver, verify that we're supposed to be * in host mode. */ if (!((pdata->operating_mode == FSL_USB2_DR_HOST) || (pdata->operating_mode == FSL_USB2_MPH_HOST))) { dev_err(&pdev->dev, "Non Host Mode configured for %s. Wrong driver linked.\n", pdev->dev.bus_id); return -ENODEV; } res = <API key>(pdev, IORESOURCE_IRQ, 0); if (!res) { dev_err(&pdev->dev, "Found HC with no IRQ. Check %s setup!\n", pdev->dev.bus_id); return -ENODEV; } irq = res->start; hcd = usb_create_hcd(driver, &pdev->dev, pdev->dev.bus_id); if (!hcd) { retval = -ENOMEM; goto err1; } res = <API key>(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "Found HC with no register addr. Check %s setup!\n", pdev->dev.bus_id); retval = -ENODEV; goto err2; } hcd->rsrc_start = res->start; hcd->rsrc_len = res->end - res->start + 1; if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len, driver->description)) { dev_dbg(&pdev->dev, "controller already in use\n"); retval = -EBUSY; goto err2; } hcd->regs = ioremap(hcd->rsrc_start, hcd->rsrc_len); if (hcd->regs == NULL) { dev_dbg(&pdev->dev, "error mapping memory\n"); retval = -EFAULT; goto err3; } /* Enable USB controller */ temp = in_be32(hcd->regs + 0x500); out_be32(hcd->regs + 0x500, temp | 0x4); /* Set to Host mode */ temp = in_le32(hcd->regs + 0x1a8); out_le32(hcd->regs + 0x1a8, temp | 0x3); retval = usb_add_hcd(hcd, irq, IRQF_SHARED); if (retval != 0) goto err4; return retval; err4: iounmap(hcd->regs); err3: release_mem_region(hcd->rsrc_start, hcd->rsrc_len); err2: usb_put_hcd(hcd); err1: dev_err(&pdev->dev, "init %s fail, %d\n", pdev->dev.bus_id, retval); return retval; } /* may be called without controller electrically present */ /* may be called with controller, bus, and devices active */ /** * usb_hcd_fsl_remove - shutdown processing for FSL-based HCDs * @dev: USB Host Controller being removed * Context: !in_interrupt() * * Reverses the effect of usb_hcd_fsl_probe(). * */ void usb_hcd_fsl_remove(struct usb_hcd *hcd, struct platform_device *pdev) { usb_remove_hcd(hcd); iounmap(hcd->regs); release_mem_region(hcd->rsrc_start, hcd->rsrc_len); usb_put_hcd(hcd); } static void mpc83xx_setup_phy(struct ehci_hcd *ehci, enum fsl_usb2_phy_modes phy_mode, unsigned int port_offset) { u32 portsc = 0; switch (phy_mode) { case FSL_USB2_PHY_ULPI: portsc |= PORT_PTS_ULPI; break; case FSL_USB2_PHY_SERIAL: portsc |= PORT_PTS_SERIAL; break; case <API key>: portsc |= PORT_PTS_PTW; /* fall through */ case FSL_USB2_PHY_UTMI: portsc |= PORT_PTS_UTMI; break; case FSL_USB2_PHY_NONE: break; } ehci_writel(ehci, portsc, &ehci->regs->port_status[port_offset]); } static void mpc83xx_usb_setup(struct usb_hcd *hcd) { struct ehci_hcd *ehci = hcd_to_ehci(hcd); struct <API key> *pdata; void __iomem *non_ehci = hcd->regs; pdata = (struct <API key> *)hcd->self.controller-> platform_data; /* Enable PHY interface in the control reg. */ out_be32(non_ehci + FSL_SOC_USB_CTRL, 0x00000004); out_be32(non_ehci + FSL_SOC_USB_SNOOP1, 0x0000001b); #if defined(CONFIG_PPC32) && !defined(<API key>) /* * Turn on cache snooping hardware, since some PowerPC platforms * wholly rely on hardware to deal with cache coherent */ /* Setup Snooping for all the 4GB space */ /* SNOOP1 starts from 0x0, size 2G */ out_be32(non_ehci + FSL_SOC_USB_SNOOP1, 0x0 | SNOOP_SIZE_2GB); /* SNOOP2 starts from 0x80000000, size 2G */ out_be32(non_ehci + FSL_SOC_USB_SNOOP2, 0x80000000 | SNOOP_SIZE_2GB); #endif if (pdata->operating_mode == FSL_USB2_DR_HOST) mpc83xx_setup_phy(ehci, pdata->phy_mode, 0); if (pdata->operating_mode == FSL_USB2_MPH_HOST) { unsigned int chip, rev, svr; svr = mfspr(SPRN_SVR); chip = svr >> 16; rev = (svr >> 4) & 0xf; /* Deal with USB Erratum #14 on MPC834x Rev 1.0 & 1.1 chips */ if ((rev == 1) && (chip >= 0x8050) && (chip <= 0x8055)) ehci->has_fsl_port_bug = 1; if (pdata->port_enables & <API key>) mpc83xx_setup_phy(ehci, pdata->phy_mode, 0); if (pdata->port_enables & <API key>) mpc83xx_setup_phy(ehci, pdata->phy_mode, 1); } /* put controller in host mode. */ ehci_writel(ehci, 0x00000003, non_ehci + FSL_SOC_USB_USBMODE); out_be32(non_ehci + FSL_SOC_USB_PRICTRL, 0x0000000c); out_be32(non_ehci + <API key>, 0x00000040); out_be32(non_ehci + FSL_SOC_USB_SICTRL, 0x00000001); } /* called after powerup, by probe or system-pm "wakeup" */ static int ehci_fsl_reinit(struct ehci_hcd *ehci) { mpc83xx_usb_setup(ehci_to_hcd(ehci)); ehci_port_power(ehci, 0); return 0; } /* called during probe() after chip reset completes */ static int ehci_fsl_setup(struct usb_hcd *hcd) { struct ehci_hcd *ehci = hcd_to_ehci(hcd); int retval; /* EHCI registers start at offset 0x100 */ ehci->caps = hcd->regs + 0x100; ehci->regs = hcd->regs + 0x100 + HC_LENGTH(ehci_readl(ehci, &ehci->caps->hc_capbase)); dbg_hcs_params(ehci, "reset"); dbg_hcc_params(ehci, "reset"); /* cache this readonly data; minimize chip reads */ ehci->hcs_params = ehci_readl(ehci, &ehci->caps->hcs_params); retval = ehci_halt(ehci); if (retval) return retval; /* data structure init */ retval = ehci_init(hcd); if (retval) return retval; ehci->is_tdi_rh_tt = 1; ehci->sbrn = 0x20; ehci_reset(ehci); retval = ehci_fsl_reinit(ehci); return retval; } static const struct hc_driver ehci_fsl_hc_driver = { .description = hcd_name, .product_desc = "Freescale On-Chip EHCI Host Controller", .hcd_priv_size = sizeof(struct ehci_hcd), /* * generic hardware linkage */ .irq = ehci_irq, .flags = HCD_USB2, /* * basic lifecycle operations */ .reset = ehci_fsl_setup, .start = ehci_run, #ifdef CONFIG_PM .suspend = ehci_bus_suspend, .resume = ehci_bus_resume, #endif .stop = ehci_stop, .shutdown = ehci_shutdown, /* * managing i/o requests and associated device resources */ .urb_enqueue = ehci_urb_enqueue, .urb_dequeue = ehci_urb_dequeue, .endpoint_disable = <API key>, /* * scheduling support */ .get_frame_number = ehci_get_frame, /* * root hub support */ .hub_status_data = <API key>, .hub_control = ehci_hub_control, .bus_suspend = ehci_bus_suspend, .bus_resume = ehci_bus_resume, }; static int ehci_fsl_drv_probe(struct platform_device *pdev) { if (usb_disabled()) return -ENODEV; return usb_hcd_fsl_probe(&ehci_fsl_hc_driver, pdev); } static int ehci_fsl_drv_remove(struct platform_device *pdev) { struct usb_hcd *hcd = <API key>(pdev); usb_hcd_fsl_remove(hcd, pdev); return 0; } MODULE_ALIAS("fsl-ehci"); static struct platform_driver ehci_fsl_driver = { .probe = ehci_fsl_drv_probe, .remove = ehci_fsl_drv_remove, .shutdown = <API key>, .driver = { .name = "fsl-ehci", }, };
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- #include "preamble_patcher.h" #include "mini_disassembler.h" // compatibility shims #include "base/logging.h" // Definitions of assembly statements we need #define ASM_JMP32REL 0xE9 #define ASM_INT3 0xCC #define ASM_JMP32ABS_0 0xFF #define ASM_JMP32ABS_1 0x25 #define ASM_JMP8REL 0xEB #define ASM_JCC32REL_0 0x0F #define ASM_JCC32REL_1_MASK 0x80 #define ASM_NOP 0x90 // X64 opcodes #define ASM_REXW 0x48 #define ASM_MOVRAX_IMM 0xB8 #define ASM_JMP 0xFF #define ASM_JMP_RAX 0xE0 namespace sidestep { PreamblePatcher::PreamblePage* PreamblePatcher::preamble_pages_ = NULL; long PreamblePatcher::granularity_ = 0; long PreamblePatcher::pagesize_ = 0; bool PreamblePatcher::initialized_ = false; static const unsigned int kPreamblePageMagic = 0x4347414D; // "MAGC" // Handle a special case that we see with functions that point into an // IAT table (including functions linked statically into the // application): these function already starts with ASM_JMP32*. For // instance, malloc() might be implemented as a JMP to __malloc(). // This function follows the initial JMPs for us, until we get to the // place where the actual code is defined. If we get to STOP_BEFORE, // we return the address before stop_before. The <API key> // flag is used in 64-bit mode. If true, we will return the address // before a trampoline is detected. Trampolines are defined as: // nop // mov rax, <<API key>> // jmp rax // See PreamblePatcher::RawPatchWithStub for more information. void* PreamblePatcher::ResolveTargetImpl(unsigned char* target, unsigned char* stop_before, bool <API key>) { if (target == NULL) return NULL; while (1) { unsigned char* new_target; if (target[0] == ASM_JMP32REL) { // target[1-4] holds the place the jmp goes to, but it's // relative to the next instruction. int relative_offset; // Windows guarantees int is 4 bytes SIDESTEP_ASSERT(sizeof(relative_offset) == 4); memcpy(reinterpret_cast<void*>(&relative_offset), reinterpret_cast<void*>(target + 1), 4); new_target = target + 5 + relative_offset; } else if (target[0] == ASM_JMP8REL) { // Visual Studio 7.1 implements new[] as an 8 bit jump to new signed char relative_offset; memcpy(reinterpret_cast<void*>(&relative_offset), reinterpret_cast<void*>(target + 1), 1); new_target = target + 2 + relative_offset; } else if (target[0] == ASM_JMP32ABS_0 && target[1] == ASM_JMP32ABS_1) { jmp32rel: // Visual studio seems to sometimes do it this way instead of the // previous way. Not sure what the rules are, but it was happening // with operator new in some binaries. void** new_target_v; if (kIs64BitBinary) { // In 64-bit mode JMPs are RIP-relative, not absolute int target_offset; memcpy(reinterpret_cast<void*>(&target_offset), reinterpret_cast<void*>(target + 2), 4); new_target_v = reinterpret_cast<void**>(target + target_offset + 6); } else { SIDESTEP_ASSERT(sizeof(new_target) == 4); memcpy(&new_target_v, reinterpret_cast<void*>(target + 2), 4); } new_target = reinterpret_cast<unsigned char*>(*new_target_v); } else if (kIs64BitBinary && target[0] == ASM_REXW && target[1] == ASM_JMP32ABS_0 && target[2] == ASM_JMP32ABS_1) { // in Visual Studio 2012 we're seeing jump like that: // rex.W jmpq *0x11d019(%rip) // according to docs I have, rex prefix is actually unneeded and // can be ignored. I.e. docs say for jumps like that operand // already defaults to 64-bit. But clearly it breaks abs. jump // detection above and we just skip rex target++; goto jmp32rel; } else { break; } if (new_target == stop_before) break; if (<API key> && *new_target == ASM_NOP && new_target[1] == ASM_REXW && new_target[2] == ASM_MOVRAX_IMM) break; target = new_target; } return target; } // Special case scoped_ptr to avoid dependency on scoped_ptr below. class <API key> { public: <API key>(unsigned char* array) : array_(array) { } ~<API key>() { if (array_) { PreamblePatcher::FreePreambleBlock(array_); } } unsigned char* Release() { unsigned char* temp = array_; array_ = NULL; return temp; } private: unsigned char* array_; }; SideStepError PreamblePatcher::<API key>( void* target_function, void *<API key>, unsigned char* preamble_stub, unsigned long stub_size, unsigned long* bytes_needed) { // We need to be able to write to a process-local copy of the first // <API key> bytes of target_function DWORD <API key> = 0; BOOL succeeded = ::VirtualProtect(reinterpret_cast<void*>(target_function), <API key>, <API key>, &<API key>); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to make page containing target function " "copy-on-write."); return <API key>; } SideStepError error_code = RawPatchWithStub(target_function, <API key>, preamble_stub, stub_size, bytes_needed); // Restore the protection of the first <API key> bytes of // pTargetFunction to what they were before we started goofing around. // We do this regardless of whether the patch succeeded or not. succeeded = ::VirtualProtect(reinterpret_cast<void*>(target_function), <API key>, <API key>, &<API key>); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to restore protection to target function."); // We must not return an error here because the function has // likely actually been patched, and returning an error might // cause our client code not to unpatch it. So we just keep // going. } if (SIDESTEP_SUCCESS != error_code) { // Testing RawPatchWithStub, above SIDESTEP_ASSERT(false); return error_code; } // Flush the instruction cache to make sure the processor doesn't execute the // old version of the instructions (before our patch). // <API key> is actually a no-op at least on // single-processor XP machines. I'm not sure why this is so, but // it is, yet I want to keep the call to the API here for // correctness in case there is a difference in some variants of // Windows/hardware. succeeded = ::<API key>(::GetCurrentProcess(), target_function, <API key>); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); // We must not return an error here because the function has actually // been patched, and returning an error would likely cause our client // code not to unpatch it. So we just keep going. } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::RawPatch(void* target_function, void* <API key>, void** <API key>) { if (!target_function || !<API key> || !<API key> || (*<API key>) || target_function == <API key>) { SIDESTEP_ASSERT(false && "Preconditions not met"); return <API key>; } BOOL succeeded = FALSE; // First, deal with a special case that we see with functions that // point into an IAT table (including functions linked statically // into the application): these function already starts with // ASM_JMP32REL. For instance, malloc() might be implemented as a // JMP to __malloc(). In that case, we replace the destination of // the JMP (__malloc), rather than the JMP itself (malloc). This // way we get the correct behavior no matter how malloc gets called. void* new_target = ResolveTarget(target_function); if (new_target != target_function) { target_function = new_target; } // In 64-bit mode, preamble_stub must be within 2GB of target function // so that if target contains a jump, we can translate it. unsigned char* preamble_stub = <API key>(target_function); if (!preamble_stub) { SIDESTEP_ASSERT(false && "Unable to allocate preamble-stub."); return <API key>; } // Frees the array at end of scope. <API key> guard_preamble_stub(preamble_stub); SideStepError error_code = <API key>( target_function, <API key>, preamble_stub, <API key>, NULL); if (SIDESTEP_SUCCESS != error_code) { SIDESTEP_ASSERT(false); return error_code; } // Flush the instruction cache to make sure the processor doesn't execute the // old version of the instructions (before our patch). // <API key> is actually a no-op at least on // single-processor XP machines. I'm not sure why this is so, but // it is, yet I want to keep the call to the API here for // correctness in case there is a difference in some variants of // Windows/hardware. succeeded = ::<API key>(::GetCurrentProcess(), target_function, <API key>); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); // We must not return an error here because the function has actually // been patched, and returning an error would likely cause our client // code not to unpatch it. So we just keep going. } SIDESTEP_LOG("PreamblePatcher::RawPatch successfully patched."); // detach the scoped pointer so the memory is not freed *<API key> = reinterpret_cast<void*>(guard_preamble_stub.Release()); return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::Unpatch(void* target_function, void* <API key>, void* <API key>) { SIDESTEP_ASSERT(target_function && <API key> && <API key>); if (!target_function || !<API key> || !<API key>) { return <API key>; } // Before unpatching, target_function should be a JMP to // <API key>. If it's not, then either it's an error, or // we're falling into the case where the original instruction was a // JMP, and we patched the jumped_to address rather than the JMP // itself. (For instance, if malloc() is just a JMP to __malloc(), // we patched __malloc() and not malloc().) unsigned char* target = reinterpret_cast<unsigned char*>(target_function); target = reinterpret_cast<unsigned char*>( ResolveTargetImpl( target, reinterpret_cast<unsigned char*>(<API key>), true)); // We should end at the function we patched. When we patch, we insert // a ASM_JMP32REL instruction, so look for that as a sanity check. if (target[0] != ASM_JMP32REL) { SIDESTEP_ASSERT(false && "target_function does not look like it was patched."); return <API key>; } const unsigned int <API key> = 5; // We need to be able to write to a process-local copy of the first // <API key> bytes of target_function DWORD <API key> = 0; BOOL succeeded = ::VirtualProtect(reinterpret_cast<void*>(target), <API key>, <API key>, &<API key>); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to make page containing target function " "copy-on-write."); return <API key>; } unsigned char* preamble_stub = reinterpret_cast<unsigned char*>( <API key>); // Disassemble the preamble of stub and copy the bytes back to target. // If we've done any conditional jumps in the preamble we need to convert // them back to the original REL8 jumps in the target. MiniDisassembler disassembler; unsigned int preamble_bytes = 0; unsigned int target_bytes = 0; while (target_bytes < <API key>) { unsigned int cur_bytes = 0; InstructionType instruction_type = disassembler.Disassemble(preamble_stub + preamble_bytes, cur_bytes); if (IT_JUMP == instruction_type) { unsigned int jump_bytes = 0; SideStepError jump_ret = <API key>; if (<API key>(preamble_stub + preamble_bytes, cur_bytes) || IsNearRelativeJump(preamble_stub + preamble_bytes, cur_bytes) || IsNearAbsoluteCall(preamble_stub + preamble_bytes, cur_bytes) || IsNearRelativeCall(preamble_stub + preamble_bytes, cur_bytes)) { jump_ret = PatchNearJumpOrCall(preamble_stub + preamble_bytes, cur_bytes, target + target_bytes, &jump_bytes, <API key>); } if (jump_ret == <API key>) { SIDESTEP_ASSERT(false && "Found unsupported jump instruction in stub!!"); return <API key>; } target_bytes += jump_bytes; } else if (IT_GENERIC == instruction_type) { if (<API key>(preamble_stub + preamble_bytes, cur_bytes)) { unsigned int mov_bytes = 0; if (<API key>(preamble_stub + preamble_bytes, cur_bytes, target + target_bytes, &mov_bytes, <API key>) != SIDESTEP_SUCCESS) { SIDESTEP_ASSERT(false && "Found unsupported generic instruction in stub!!"); return <API key>; } } else { memcpy(reinterpret_cast<void*>(target + target_bytes), reinterpret_cast<void*>(reinterpret_cast<unsigned char*>( <API key>) + preamble_bytes), cur_bytes); target_bytes += cur_bytes; } } else { SIDESTEP_ASSERT(false && "Found unsupported instruction in stub!!"); return <API key>; } preamble_bytes += cur_bytes; } FreePreambleBlock(reinterpret_cast<unsigned char*>(<API key>)); // Restore the protection of the first <API key> bytes of // target to what they were before we started goofing around. succeeded = ::VirtualProtect(reinterpret_cast<void*>(target), <API key>, <API key>, &<API key>); // Flush the instruction cache to make sure the processor doesn't execute the // old version of the instructions (before our patch). // See comment on <API key> elsewhere in this file. succeeded = ::<API key>(::GetCurrentProcess(), target, <API key>); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); return SIDESTEP_UNEXPECTED; } SIDESTEP_LOG("PreamblePatcher::Unpatch successfully unpatched."); return SIDESTEP_SUCCESS; } void PreamblePatcher::Initialize() { if (!initialized_) { SYSTEM_INFO si = { 0 }; ::GetSystemInfo(&si); granularity_ = si.<API key>; pagesize_ = si.dwPageSize; initialized_ = true; } } unsigned char* PreamblePatcher::<API key>(void* target) { PreamblePage* preamble_page = preamble_pages_; while (preamble_page != NULL) { if (preamble_page->free_ != NULL) { __int64 val = reinterpret_cast<__int64>(preamble_page) - reinterpret_cast<__int64>(target); if ((val > 0 && val + pagesize_ <= INT_MAX) || (val < 0 && val >= INT_MIN)) { break; } } preamble_page = preamble_page->next_; } // The free_ member of the page is used to store the next available block // of memory to use or NULL if there are no chunks available, in which case // we'll allocate a new page. if (preamble_page == NULL || preamble_page->free_ == NULL) { // Create a new preamble page and initialize the free list preamble_page = reinterpret_cast<PreamblePage*>(AllocPageNear(target)); SIDESTEP_ASSERT(preamble_page != NULL && "Could not allocate page!"); void** pp = &preamble_page->free_; unsigned char* ptr = reinterpret_cast<unsigned char*>(preamble_page) + <API key>; unsigned char* limit = reinterpret_cast<unsigned char*>(preamble_page) + pagesize_; while (ptr < limit) { *pp = ptr; pp = reinterpret_cast<void**>(ptr); ptr += <API key>; } *pp = NULL; // Insert the new page into the list preamble_page->magic_ = kPreamblePageMagic; preamble_page->next_ = preamble_pages_; preamble_pages_ = preamble_page; } unsigned char* ret = reinterpret_cast<unsigned char*>(preamble_page->free_); preamble_page->free_ = *(reinterpret_cast<void**>(preamble_page->free_)); return ret; } void PreamblePatcher::FreePreambleBlock(unsigned char* block) { SIDESTEP_ASSERT(block != NULL); SIDESTEP_ASSERT(granularity_ != 0); uintptr_t ptr = reinterpret_cast<uintptr_t>(block); ptr -= ptr & (granularity_ - 1); PreamblePage* preamble_page = reinterpret_cast<PreamblePage*>(ptr); SIDESTEP_ASSERT(preamble_page->magic_ == kPreamblePageMagic); *(reinterpret_cast<void**>(block)) = preamble_page->free_; preamble_page->free_ = block; } void* PreamblePatcher::AllocPageNear(void* target) { <API key> mbi = { 0 }; if (!::VirtualQuery(target, &mbi, sizeof(mbi))) { SIDESTEP_ASSERT(false && "VirtualQuery failed on target address"); return 0; } if (initialized_ == false) { PreamblePatcher::Initialize(); SIDESTEP_ASSERT(initialized_); } void* pv = NULL; unsigned char* allocation_base = reinterpret_cast<unsigned char*>( mbi.AllocationBase); __int64 i = 1; bool high_target = reinterpret_cast<__int64>(target) > UINT_MAX; while (pv == NULL) { __int64 val = reinterpret_cast<__int64>(allocation_base) - (i * granularity_); if (high_target && reinterpret_cast<__int64>(target) - val > INT_MAX) { // We're further than 2GB from the target break; } else if (val <= 0) { // Less than 0 break; } pv = ::VirtualAlloc(reinterpret_cast<void*>(allocation_base - (i++ * granularity_)), pagesize_, MEM_COMMIT | MEM_RESERVE, <API key>); } // We couldn't allocate low, try to allocate high if (pv == NULL) { i = 1; // Round up to the next multiple of page granularity allocation_base = reinterpret_cast<unsigned char*>( (reinterpret_cast<__int64>(target) & (~(granularity_ - 1))) + granularity_); while (pv == NULL) { __int64 val = reinterpret_cast<__int64>(allocation_base) + (i * granularity_) - reinterpret_cast<__int64>(target); if (val > INT_MAX || val < 0) { // We're too far or we overflowed break; } pv = ::VirtualAlloc(reinterpret_cast<void*>(allocation_base + (i++ * granularity_)), pagesize_, MEM_COMMIT | MEM_RESERVE, <API key>); } } return pv; } bool PreamblePatcher::<API key>( unsigned char* target, unsigned int instruction_size) { return (*(target) & 0x70) == 0x70 && instruction_size == 2; } bool PreamblePatcher::IsShortJump( unsigned char* target, unsigned int instruction_size) { return target[0] == 0xeb && instruction_size == 2; } bool PreamblePatcher::<API key>( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xf && (*(target + 1) & 0x80) == 0x80 && instruction_size == 6; } bool PreamblePatcher::IsNearRelativeJump( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xe9 && instruction_size == 5; } bool PreamblePatcher::IsNearAbsoluteCall( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xff && (*(target + 1) & 0x10) == 0x10 && instruction_size == 6; } bool PreamblePatcher::IsNearRelativeCall( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xe8 && instruction_size == 5; } bool PreamblePatcher::<API key>( unsigned char* target, unsigned int instruction_size) { // In this case, the ModRM byte's mod field will be 0 and r/m will be 101b (5) return instruction_size == 7 && *target == 0x48 && *(target + 1) == 0x8b && (*(target + 2) >> 6) == 0 && (*(target + 2) & 0x7) == 5; } SideStepError PreamblePatcher::<API key>( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { // note: rel8 offset is signed. Thus we need to ask for signed char // to negative offsets right unsigned char* original_jump_dest = (source + 2) + static_cast<signed char>(source[1]); unsigned char* stub_jump_from = target + 6; __int64 fixup_jump_offset = original_jump_dest - stub_jump_from; if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up short jump because target" " is too far away."); return <API key>; } *target_bytes = 6; if (target_size > *target_bytes) { // Convert the short jump to a near jump. // 0f 8x xx xx xx xx = Jcc rel32off unsigned short jmpcode = ((0x80 | (source[0] & 0xf)) << 8) | 0x0f; memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(&jmpcode), 2); memcpy(reinterpret_cast<void*>(target + 2), reinterpret_cast<void*>(&fixup_jump_offset), 4); } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::PatchShortJump( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { // note: rel8 offset is _signed_. Thus we need signed char here. unsigned char* original_jump_dest = (source + 2) + static_cast<signed char>(source[1]); unsigned char* stub_jump_from = target + 5; __int64 fixup_jump_offset = original_jump_dest - stub_jump_from; if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up short jump because target" " is too far away."); return <API key>; } *target_bytes = 5; if (target_size > *target_bytes) { // Convert the short jump to a near jump. // e9 xx xx xx xx = jmp rel32off target[0] = 0xe9; memcpy(reinterpret_cast<void*>(target + 1), reinterpret_cast<void*>(&fixup_jump_offset), 4); } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::PatchNearJumpOrCall( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { SIDESTEP_ASSERT(instruction_size == 5 || instruction_size == 6); unsigned int <API key> = instruction_size == 5 ? 1 : 2; unsigned char* original_jump_dest = reinterpret_cast<unsigned char *>( reinterpret_cast<__int64>(source + instruction_size) + *(reinterpret_cast<int*>(source + <API key>))); unsigned char* stub_jump_from = target + instruction_size; __int64 fixup_jump_offset = original_jump_dest - stub_jump_from; if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up near jump because target" " is too far away."); return <API key>; } if ((fixup_jump_offset < SCHAR_MAX && fixup_jump_offset > SCHAR_MIN)) { *target_bytes = 2; if (target_size > *target_bytes) { // If the new offset is in range, use a short jump instead of a near jump. if (source[0] == ASM_JCC32REL_0 && (source[1] & ASM_JCC32REL_1_MASK) == ASM_JCC32REL_1_MASK) { unsigned short jmpcode = (static_cast<unsigned char>( fixup_jump_offset) << 8) | (0x70 | (source[1] & 0xf)); memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(&jmpcode), 2); } else { target[0] = ASM_JMP8REL; target[1] = static_cast<unsigned char>(fixup_jump_offset); } } } else { *target_bytes = instruction_size; if (target_size > *target_bytes) { memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(source), <API key>); memcpy(reinterpret_cast<void*>(target + <API key>), reinterpret_cast<void*>(&fixup_jump_offset), 4); } } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::<API key>( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { SIDESTEP_ASSERT(instruction_size == 7); const int <API key> = 3; // 0x48 0x8b 0x0d <offset> unsigned char* original_mov_dest = reinterpret_cast<unsigned char*>( reinterpret_cast<__int64>(source + instruction_size) + *(reinterpret_cast<int*>(source + <API key>))); unsigned char* stub_mov_from = target + instruction_size; __int64 fixup_mov_offset = original_mov_dest - stub_mov_from; if (fixup_mov_offset > INT_MAX || fixup_mov_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up near MOV because target is too far away."); return SIDESTEP_UNEXPECTED; } *target_bytes = instruction_size; if (target_size > *target_bytes) { memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(source), <API key>); memcpy(reinterpret_cast<void*>(target + <API key>), reinterpret_cast<void*>(&fixup_mov_offset), 4); } return SIDESTEP_SUCCESS; } }; // namespace sidestep
// Use of this source code is governed by a BSD-style // +build !go1.5 // Package oracle contains the implementation of the oracle tool whose // command-line is provided by golang.org/x/tools/cmd/oracle. package oracle // import "golang.org/x/tools/oracle" // This file defines oracle.Query, the entry point for the oracle tool. // The actual executable is defined in cmd/oracle. // TODO(adonovan): new queries // - show all statements that may update the selected lvalue // (local, global, field, etc). // - show all places where an object of type T is created // (&T{}, var t T, new(T), new(struct{array [3]T}), etc. import ( "fmt" "go/ast" "go/build" "go/parser" "go/token" "io" "path/filepath" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/loader" "golang.org/x/tools/go/pointer" "golang.org/x/tools/go/ssa" "golang.org/x/tools/go/types" "golang.org/x/tools/oracle/serial" ) type printfFunc func(pos interface{}, format string, args ...interface{}) // queryResult is the interface of each query-specific result type. type queryResult interface { toSerial(res *serial.Result, fset *token.FileSet) display(printf printfFunc) } // A QueryPos represents the position provided as input to a query: // a textual extent in the program's source code, the AST node it // corresponds to, and the package to which it belongs. type queryPos struct { fset *token.FileSet start, end token.Pos // source extent of query path []ast.Node // AST path from query node to root of ast.File exact bool // 2nd result of <API key> info *loader.PackageInfo // type info for the queried package (nil for fastQueryPos) } // TypeString prints type T relative to the query position. func (qpos *queryPos) typeString(T types.Type) string { return types.TypeString(T, types.RelativeTo(qpos.info.Pkg)) } // ObjectString prints object obj relative to the query position. func (qpos *queryPos) objectString(obj types.Object) string { return types.ObjectString(obj, types.RelativeTo(qpos.info.Pkg)) } // SelectionString prints selection sel relative to the query position. func (qpos *queryPos) selectionString(sel *types.Selection) string { return types.SelectionString(sel, types.RelativeTo(qpos.info.Pkg)) } // A Query specifies a single oracle query. type Query struct { Mode string // query mode ("callers", etc) Pos string // query position Build *build.Context // package loading configuration // pointer analysis options Scope []string // main packages in (*loader.Config).FromArgs syntax PTALog io.Writer // (optional) pointer-analysis log file Reflection bool // model reflection soundly (currently slow). // Populated during Run() Fset *token.FileSet result queryResult } // Serial returns an instance of serial.Result, which implements the // {xml,json}.Marshaler interfaces so that query results can be // serialized as JSON or XML. func (q *Query) Serial() *serial.Result { resj := &serial.Result{Mode: q.Mode} q.result.toSerial(resj, q.Fset) return resj } // WriteTo writes the oracle query result res to out in a compiler diagnostic format. func (q *Query) WriteTo(out io.Writer) { printf := func(pos interface{}, format string, args ...interface{}) { fprintf(out, q.Fset, pos, format, args...) } q.result.display(printf) } // Run runs an oracle query and populates its Fset and Result. func Run(q *Query) error { switch q.Mode { case "callees": return callees(q) case "callers": return callers(q) case "callstack": return callstack(q) case "peers": return peers(q) case "pointsto": return pointsto(q) case "whicherrs": return whicherrs(q) case "definition": return definition(q) case "describe": return describe(q) case "freevars": return freevars(q) case "implements": return implements(q) case "referrers": return referrers(q) case "what": return what(q) default: return fmt.Errorf("invalid mode: %q", q.Mode) } } func setPTAScope(lconf *loader.Config, scope []string) error { if len(scope) == 0 { return fmt.Errorf("no packages specified for pointer analysis scope") } // Determine initial packages for PTA. args, err := lconf.FromArgs(scope, true) if err != nil { return err } if len(args) > 0 { return fmt.Errorf("surplus arguments: %q", args) } return nil } // Create a pointer.Config whose scope is the initial packages of lprog // and their dependencies. func setupPTA(prog *ssa.Program, lprog *loader.Program, ptaLog io.Writer, reflection bool) (*pointer.Config, error) { // TODO(adonovan): the body of this function is essentially // duplicated in all go/pointer clients. Refactor. // For each initial package (specified on the command line), // if it has a main function, analyze that, // otherwise analyze its tests, if any. var testPkgs, mains []*ssa.Package for _, info := range lprog.InitialPackages() { initialPkg := prog.Package(info.Pkg) // Add package to the pointer analysis scope. if initialPkg.Func("main") != nil { mains = append(mains, initialPkg) } else { testPkgs = append(testPkgs, initialPkg) } } if testPkgs != nil { if p := prog.<API key>(testPkgs...); p != nil { mains = append(mains, p) } } if mains == nil { return nil, fmt.Errorf("analysis scope has no main and no tests") } return &pointer.Config{ Log: ptaLog, Reflection: reflection, Mains: mains, }, nil } // importQueryPackage finds the package P containing the // query position and tells conf to import it. // It returns the package's path. func importQueryPackage(pos string, conf *loader.Config) (string, error) { fqpos, err := fastQueryPos(pos) if err != nil { return "", err // bad query } filename := fqpos.fset.File(fqpos.start).Name() // This will not work for ad-hoc packages // such as $GOROOT/src/net/http/triv.go. // TODO(adonovan): ensure we report a clear error. _, importPath, err := guessImportPath(filename, conf.Build) if err != nil { return "", err // can't find GOPATH dir } if importPath == "" { return "", fmt.Errorf("can't guess import path from %s", filename) } // Check that it's possible to load the queried package. // (e.g. oracle tests contain different 'package' decls in same dir.) // Keep consistent with logic in loader/util.go! cfg2 := *conf.Build cfg2.CgoEnabled = false bp, err := cfg2.Import(importPath, "", 0) if err != nil { return "", err // no files for package } switch pkgContainsFile(bp, filename) { case 'T': conf.ImportWithTests(importPath) case 'X': conf.ImportWithTests(importPath) importPath += "_test" // for TypeCheckFuncBodies case 'G': conf.Import(importPath) default: return "", fmt.Errorf("package %q doesn't contain file %s", importPath, filename) } conf.TypeCheckFuncBodies = func(p string) bool { return p == importPath } return importPath, nil } // pkgContainsFile reports whether file was among the packages Go // files, Test files, eXternal test files, or not found. func pkgContainsFile(bp *build.Package, filename string) byte { for i, files := range [][]string{bp.GoFiles, bp.TestGoFiles, bp.XTestGoFiles} { for _, file := range files { if sameFile(filepath.Join(bp.Dir, file), filename) { return "GTX"[i] } } } return 0 // not found } // ParseQueryPos parses the source query position pos and returns the // AST node of the loaded program lprog that it identifies. // If needExact, it must identify a single AST subtree; // this is appropriate for queries that allow fairly arbitrary syntax, // e.g. "describe". func parseQueryPos(lprog *loader.Program, posFlag string, needExact bool) (*queryPos, error) { filename, startOffset, endOffset, err := parsePosFlag(posFlag) if err != nil { return nil, err } start, end, err := findQueryPos(lprog.Fset, filename, startOffset, endOffset) if err != nil { return nil, err } info, path, exact := lprog.<API key>(start, end) if path == nil { return nil, fmt.Errorf("no syntax here") } if needExact && !exact { return nil, fmt.Errorf("ambiguous selection within %s", astutil.NodeDescription(path[0])) } return &queryPos{lprog.Fset, start, end, path, exact, info}, nil } // allowErrors causes type errors to be silently ignored. // (Not suitable if SSA construction follows.) func allowErrors(lconf *loader.Config) { ctxt := *lconf.Build // copy ctxt.CgoEnabled = false lconf.Build = &ctxt lconf.AllowErrors = true // AllErrors makes the parser always return an AST instead of // bailing out after 10 errors and returning an empty ast.File. lconf.ParserMode = parser.AllErrors lconf.TypeChecker.Error = func(err error) {} } // ptrAnalysis runs the pointer analysis and returns its result. func ptrAnalysis(conf *pointer.Config) *pointer.Result { result, err := pointer.Analyze(conf) if err != nil { panic(err) // pointer analysis internal error } return result } func unparen(e ast.Expr) ast.Expr { return astutil.Unparen(e) } // deref returns a pointer's element type; otherwise it returns typ. func deref(typ types.Type) types.Type { if p, ok := typ.Underlying().(*types.Pointer); ok { return p.Elem() } return typ } // fprintf prints to w a message of the form "location: message\n" // where location is derived from pos. // pos must be one of: // - a token.Pos, denoting a position // - an ast.Node, denoting an interval // - anything with a Pos() method: // ssa.Member, ssa.Value, ssa.Instruction, types.Object, pointer.Label, etc. // - a QueryPos, denoting the extent of the user's query. // - nil, meaning no position at all. // The output format is is compatible with the 'gnu' // <API key> in Emacs' compilation mode. // TODO(adonovan): support other editors. func fprintf(w io.Writer, fset *token.FileSet, pos interface{}, format string, args ...interface{}) { var start, end token.Pos switch pos := pos.(type) { case ast.Node: start = pos.Pos() end = pos.End() case token.Pos: start = pos end = start case interface { Pos() token.Pos }: start = pos.Pos() end = start case *queryPos: start = pos.start end = pos.end case nil: // no-op default: panic(fmt.Sprintf("invalid pos: %T", pos)) } if sp := fset.Position(start); start == end { // (prints "-: " for token.NoPos) fmt.Fprintf(w, "%s: ", sp) } else { ep := fset.Position(end) // The -1 below is a concession to Emacs's broken use of // inclusive (not half-open) intervals. // Other editors may not want it. // TODO(adonovan): add an -editor=vim|emacs|acme|auto // flag; auto uses EMACS=t / VIM=... / etc env vars. fmt.Fprintf(w, "%s:%d.%d-%d.%d: ", sp.Filename, sp.Line, sp.Column, ep.Line, ep.Column-1) } fmt.Fprintf(w, format, args...) io.WriteString(w, "\n") }
module ShowRepoEvents where import qualified Github.Issues.Events as Github import Data.List (intercalate) import Data.Maybe (fromJust) main = do possibleEvents <- Github.eventsForRepo "thoughtbot" "paperclip" case possibleEvents of (Left error) -> putStrLn $ "Error: " ++ show error (Right events) -> do putStrLn $ intercalate "\n" $ map formatEvent events formatEvent event = "Issue #" ++ issueNumber event ++ ": " ++ formatEvent' event (Github.eventType event) where formatEvent' event Github.Closed = "closed on " ++ createdAt event ++ " by " ++ loginName event ++ withCommitId event (\commitId -> " in the commit " ++ commitId) formatEvent' event Github.Reopened = "reopened on " ++ createdAt event ++ " by " ++ loginName event formatEvent' event Github.Subscribed = loginName event ++ " is subscribed to receive notifications" formatEvent' event Github.Unsubscribed = loginName event ++ " is unsubscribed from notifications" formatEvent' event Github.Merged = "merged by " ++ loginName event ++ " on " ++ createdAt event ++ (withCommitId event $ \commitId -> " in the commit " ++ commitId) formatEvent' event Github.Referenced = withCommitId event $ \commitId -> "referenced from " ++ commitId ++ " by " ++ loginName event formatEvent' event Github.Mentioned = loginName event ++ " was mentioned in the issue's body" formatEvent' event Github.Assigned = "assigned to " ++ loginName event ++ " on " ++ createdAt event loginName = Github.githubOwnerLogin . Github.eventActor createdAt = show . Github.fromGithubDate . Github.eventCreatedAt withCommitId event f = maybe "" f (Github.eventCommitId event) issueNumber = show . Github.issueNumber . fromJust . Github.eventIssue
/* -*- buffer-read-only: t -*- * !!!!!!! DO NOT EDIT THIS FILE !!!!!!! * This file is built by regen/mk_PL_charclass.pl from property definitions * and lib/unicore/CaseFolding.txt. * Any changes made here will be lost! */ /* U+00 NUL */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+01 SOH */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+02 STX */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+03 ETX */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+04 EOT */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+05 ENQ */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+06 ACK */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+07 BEL */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+08 BS */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+09 HT */ _CC_BLANK_A|_CC_BLANK_L1|_CC_CNTRL_A|_CC_CNTRL_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_SPACE_A|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+0A LF */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_SPACE_A|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+0B VT */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_QUOTEMETA, /* U+0C FF */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_SPACE_A|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+0D CR */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_SPACE_A|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+0E SO */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+0F SI */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+10 DLE */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+11 DC1 */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+12 DC2 */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+13 DC3 */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+14 DC4 */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+15 NAK */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+16 SYN */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+17 ETB */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+18 CAN */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+19 EOM */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1A SUB */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1B ESC */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1C FS */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1D GS */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1E RS */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1F US */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+20 SPACE */ _CC_BLANK_A|_CC_BLANK_L1|_CC_CHARNAME_CONT|_CC_PRINT_A|_CC_PRINT_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_SPACE_A|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+21 '!' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+22 '"' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+23 '#' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+24 '$' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+25 '%' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+26 '&' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA,
var fs = require('fs') , child_process = require('child_process') , _glob = require('glob') , bunch = require('./bunch') ; exports.loadEnv = function loadEnv(env, cb) { var loaders = [] function load(name, cb) { fs.readFile(env[name], function(error, data) { env[name] = env[name].match(/.*\.json$/) ? JSON.parse(data) : data; cb(error, data) }) } for (var name in env) { loaders.push([load, name]) } bunch(loaders, cb) } exports.commandActor = function command(executable) { return function command(args, opts, cb) { if (!cb) { cb = opts; opts = {} } var cmd = child_process.spawn(executable, args, opts); function log(b) { console.log(b.toString()) } cmd.stdout.on('data', log); cmd.stderr.on('data', log); cmd.on('exit', function(code) { if (code) { cb(new Error(executable + ' exited with status ' + code)); } else { cb(); } }); return cmd; } } exports.jsonParse = function(str, cb) { try { cb(null, JSON.parse(str)); } catch (ex) { cb(ex); } } exports.jsonStringify = function(obj, cb) { try { cb(null, JSON.stringify(obj)); } catch (ex) { cb(ex); } } exports.glob = function glob(pattern, cb) { console.log('pattern', pattern); _glob(pattern, function(error, files) { cb(error, [files]); }); }
Function.prototype.bind = Function.prototype.bind || function (target) { var self = this; return function (args) { if (!(args instanceof Array)) { args = [args]; } self.apply(target, args); }; };
#if NET45 using System; using System.Runtime.InteropServices; namespace Microsoft.DotNet.<API key>.Native { internal static partial class NativeMethods { public static class Unix { public unsafe static string GetUname() { // Utsname shouldn't be larger than 2K var buf = stackalloc byte[2048]; try { if (uname((IntPtr)buf) == 0) { return Marshal.PtrToStringAnsi((IntPtr)buf); } } catch (Exception ex) { throw new <API key>("Error reading Unix name", ex); } throw new <API key>("Unknown error reading Unix name"); } [DllImport("libc")] private static extern int uname(IntPtr utsname); } } } #endif
from __future__ import print_function import soco """ Prints the name of each discovered player in the network. """ for zone in soco.discover(): print(zone.player_name)
// DATA_TEMPLATE: js_data oTest.fnStart( "oLanguage.oPaginate" ); /* Note that the paging language information only has relevence in full numbers */ $(document).ready( function () { /* Check the default */ var oTable = $('#example').dataTable( { "aaData": gaaData, "sPaginationType": "full_numbers" } ); var oSettings = oTable.fnSettings(); oTest.fnTest( "oLanguage.oPaginate defaults", null, function () { var bReturn = oSettings.oLanguage.oPaginate.sFirst == "First" && oSettings.oLanguage.oPaginate.sPrevious == "Previous" && oSettings.oLanguage.oPaginate.sNext == "Next" && oSettings.oLanguage.oPaginate.sLast == "Last"; return bReturn; } ); oTest.fnTest( "oLanguage.oPaginate defaults are in the DOM", null, function () { var bReturn = $('#example_paginate .first').html() == "First" && $('#example_paginate .previous').html() == "Previous" && $('#example_paginate .next').html() == "Next" && $('#example_paginate .last').html() == "Last"; return bReturn; } ); oTest.fnTest( "oLanguage.oPaginate can be defined", function () { oSession.fnRestore(); oTable = $('#example').dataTable( { "aaData": gaaData, "sPaginationType": "full_numbers", "oLanguage": { "oPaginate": { "sFirst": "unit1", "sPrevious": "test2", "sNext": "unit3", "sLast": "test4" } } } ); oSettings = oTable.fnSettings(); }, function () { var bReturn = oSettings.oLanguage.oPaginate.sFirst == "unit1" && oSettings.oLanguage.oPaginate.sPrevious == "test2" && oSettings.oLanguage.oPaginate.sNext == "unit3" && oSettings.oLanguage.oPaginate.sLast == "test4"; return bReturn; } ); oTest.fnTest( "oLanguage.oPaginate definitions are in the DOM", null, function () { var bReturn = $('#example_paginate .first').html() == "unit1" && $('#example_paginate .previous').html() == "test2" && $('#example_paginate .next').html() == "unit3" && $('#example_paginate .last').html() == "test4"; return bReturn; } ); oTest.fnComplete(); } );
{% include vars.html %} <nav class="navbar navbar-full navbar-fixed-top navbar-dark"> <div class="container"> <a class="navbar-brand" href="{{url_base}}/"> {% include svg/logo-flow-nav.svg %} <span class="sr-only">Flow</span> </a> <div class="clearfix hidden-lg-up"> <button class="navbar-toggler float-xs-right" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="exCollapsingNavbar2" aria-expanded="false" aria-label="Toggle navigation"> <!-- &#9776; --> </button> </div> <div class="collapse <API key>" id="navbar"> <ul class="nav navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{{url_base}}/docs/getting-started/">{{i18n.<API key>}}</a> </li> <li class="nav-item"> <a class="nav-link" href="{{url_base}}/docs/">{{i18n.<API key>}}</a> </li> <li class="nav-item"> <a class="nav-link" href="{{base_url}}/try/">{{i18n.navbar_try}}</a> </li> <li class="nav-item"> <a class="nav-link" href="{{base_url}}/blog/">{{i18n.navbar_blog}}</a> </li> </ul> <ul class="nav navbar-nav float-lg-right"> {% assign path = page.url | split: '/' %} {% unless true || path[1] == 'blog' %} <li class="nav-item dropdown"> <a id="dropdownNavLanguage" class="nav-link dropdown-toggle" role="button" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% include svg/icon-language.svg class="navbar-icon" %} <span class="<API key>">{{lang.name}}</span> </a> <div class="dropdown-menu" aria-labelledby="dropdownNavLanguage"> {% for language in site.data.languages %} {% if language.enabled %} <a href="{{site.baseurl}}/{{language.tag}}/{{url_relative}}" class="dropdown-item{% if lang.tag == language.tag %} active{% endif %}" data-lang="{{language.accept_languages[0]}}"> {{language.name}} </a> {% endif %} {% endfor %} </div> </li> {% endunless %} <li class="nav-item"> <a class="nav-link" href="https://twitter.com/flowtype"> {% include svg/icon-twitter.svg class="navbar-icon" %} <span class="sr-only">{{i18n.navbar_twitter}}</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="http://stackoverflow.com/questions/tagged/flowtype"> {% include svg/icon-stackoverflow.svg class="navbar-icon" %} <span class="sr-only">{{i18n.<API key>}}</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://github.com/facebook/flow"> {% include svg/icon-github.svg class="navbar-icon" %} <span class="sr-only">{{i18n.navbar_github}}</span> </a> </li> </ul> </div> </div> </nav>
namespace Simple.Data.UnitTest { using System; using System.Collections.Generic; using NUnit.Framework; [TestFixture] public class AdapterFactoryTest { private static AdapterFactory CreateTarget() { return new <API key>(new StubComposer()); } [Test] [ExpectedException(typeof(ArgumentException))] public void <API key>() { CreateTarget().Create(new { X = "" }); } [Test] public void CreateWithName() { var actual = CreateTarget().Create("Stub", null); Assert.IsNotNull(actual); } } class StubComposer : Composer { public override T Compose<T>() { return (T) Create(); } public override T Compose<T>(string contractName) { return (T)Create(); } private object Create() { return new StubAdapter(); } } class StubAdapter : Adapter { public override IDictionary<string, object> GetKey(string tableName, IDictionary<string, object> record) { throw new <API key>(); } public override IList<string> GetKeyNames(string tableName) { throw new <API key>(); } public override IDictionary<string, object> Get(string tableName, params object[] keyValues) { throw new <API key>(); } public override IEnumerable<IDictionary<string, object>> Find(string tableName, SimpleExpression criteria) { throw new <API key>(); } public override IEnumerable<IDictionary<string, object>> RunQuery(SimpleQuery query, out IEnumerable<<API key>> unhandledClauses) { throw new <API key>(); } public override IDictionary<string, object> Insert(string tableName, IDictionary<string, object> data, bool resultRequired) { throw new <API key>(); } public override int Update(string tableName, IDictionary<string, object> data, SimpleExpression criteria) { throw new <API key>(); } public override int Delete(string tableName, SimpleExpression criteria) { throw new <API key>(); } public override IEnumerable<IEnumerable<IDictionary<string, object>>> RunQueries(SimpleQuery[] queries, List<IEnumerable<<API key>>> unhandledClauses) { throw new <API key>(); } public override bool <API key>(string functionName, params object[] args) { throw new <API key>(); } } }
<div>Does not close properly<div>Nested same level as next div</div></div><div>Will be nested, but should be top level</div>
module.exports={title:"Google Hangouts",hex:"0C9D58",source:"https://material.google.com/resources/<API key>.html
#include <linux/dmi.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/spinlock.h> #include <linux/pm.h> #include <linux/pci.h> #include <linux/acpi.h> #include <linux/slab.h> #include <linux/interrupt.h> #define PREFIX "ACPI: " #define _COMPONENT ACPI_PCI_COMPONENT ACPI_MODULE_NAME("pci_irq"); struct acpi_prt_entry { struct acpi_pci_id id; u8 pin; acpi_handle link; u32 index; /* GSI, or link _CRS index */ }; static inline char pin_name(int pin) { return 'A' + pin - 1; } static const struct dmi_system_id medion_md9580[] = { { .ident = "Medion MD9580-F laptop", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "MEDIONNB"), DMI_MATCH(DMI_PRODUCT_NAME, "A555"), }, }, { } }; static const struct dmi_system_id dell_optiplex[] = { { .ident = "Dell Optiplex GX1", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Computer Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex GX1 600S+"), }, }, { } }; static const struct dmi_system_id hp_t5710[] = { { .ident = "HP t5710", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "hp t5000 series"), DMI_MATCH(DMI_BOARD_NAME, "098Ch"), }, }, { } }; struct prt_quirk { const struct dmi_system_id *system; unsigned int segment; unsigned int bus; unsigned int device; unsigned char pin; const char *source; /* according to BIOS */ const char *actual_source; }; #define PCI_INTX_PIN(c) (c - 'A' + 1) /* * These systems have incorrect _PRT entries. The BIOS claims the PCI * interrupt at the listed segment/bus/device/pin is connected to the first * link device, but it is actually connected to the second. */ static const struct prt_quirk prt_quirks[] = { { medion_md9580, 0, 0, 9, PCI_INTX_PIN('A'), "\\_SB_.PCI0.ISA_.LNKA", "\\_SB_.PCI0.ISA_.LNKB"}, { dell_optiplex, 0, 0, 0xd, PCI_INTX_PIN('A'), "\\_SB_.LNKB", "\\_SB_.LNKA"}, { hp_t5710, 0, 0, 1, PCI_INTX_PIN('A'), "\\_SB_.PCI0.LNK1", "\\_SB_.PCI0.LNK3"}, }; static void do_prt_fixups(struct acpi_prt_entry *entry, struct <API key> *prt) { int i; const struct prt_quirk *quirk; for (i = 0; i < ARRAY_SIZE(prt_quirks); i++) { quirk = &prt_quirks[i]; /* All current quirks involve link devices, not GSIs */ if (dmi_check_system(quirk->system) && entry->id.segment == quirk->segment && entry->id.bus == quirk->bus && entry->id.device == quirk->device && entry->pin == quirk->pin && !strcmp(prt->source, quirk->source) && strlen(prt->source) >= strlen(quirk->actual_source)) { printk(KERN_WARNING PREFIX "firmware reports " "%04x:%02x:%02x PCI INT %c connected to %s; " "changing to %s\n", entry->id.segment, entry->id.bus, entry->id.device, pin_name(entry->pin), prt->source, quirk->actual_source); strcpy(prt->source, quirk->actual_source); } } } static int <API key>(acpi_handle handle, struct pci_dev *dev, int pin, struct <API key> *prt, struct acpi_prt_entry **entry_ptr) { int segment = pci_domain_nr(dev->bus); int bus = dev->bus->number; int device = pci_ari_enabled(dev->bus) ? 0 : PCI_SLOT(dev->devfn); struct acpi_prt_entry *entry; if (((prt->address >> 16) & 0xffff) != device || prt->pin + 1 != pin) return -ENODEV; entry = kzalloc(sizeof(struct acpi_prt_entry), GFP_KERNEL); if (!entry) return -ENOMEM; /* * Note that the _PRT uses 0=INTA, 1=INTB, etc, while PCI uses * 1=INTA, 2=INTB. We use the PCI encoding throughout, so convert * it here. */ entry->id.segment = segment; entry->id.bus = bus; entry->id.device = (prt->address >> 16) & 0xFFFF; entry->pin = prt->pin + 1; do_prt_fixups(entry, prt); entry->index = prt->source_index; if (prt->source[0]) acpi_get_handle(handle, prt->source, &entry->link); <API key>((ACPI_DB_INFO, " %04x:%02x:%02x[%c] -> %s[%d]\n", entry->id.segment, entry->id.bus, entry->id.device, pin_name(entry->pin), prt->source, entry->index)); *entry_ptr = entry; return 0; } static int <API key>(struct pci_dev *dev, int pin, struct acpi_prt_entry **entry_ptr) { acpi_status status; struct acpi_buffer buffer = { <API key>, NULL }; struct <API key> *entry; acpi_handle handle = NULL; if (dev->bus->bridge) handle = ACPI_HANDLE(dev->bus->bridge); if (!handle) return -ENODEV; /* 'handle' is the _PRT's parent (root bridge or PCI-PCI bridge) */ status = <API key>(handle, &buffer); if (ACPI_FAILURE(status)) { kfree(buffer.pointer); return -ENODEV; } entry = buffer.pointer; while (entry && (entry->length > 0)) { if (!<API key>(handle, dev, pin, entry, entry_ptr)) break; entry = (struct <API key> *) ((unsigned long)entry + entry->length); } kfree(buffer.pointer); return 0; } #ifdef CONFIG_X86_IO_APIC extern int noioapicquirk; extern int noioapicreroute; static int <API key>(struct pci_bus *bus) { struct pci_bus *bus_it; for (bus_it = bus ; bus_it ; bus_it = bus_it->parent) { if (!bus_it->self) return 0; if (bus_it->self->irq_reroute_variant) return bus_it->self->irq_reroute_variant; } return 0; } /* * Some chipsets (e.g. Intel 6700PXH) generate a legacy INTx when the IRQ * entry in the chipset's IO-APIC is masked (as, e.g. the RT kernel does * during interrupt handling). When this INTx generation cannot be disabled, * we reroute these interrupts to their legacy equivalent to get rid of * spurious interrupts. */ static int <API key>(struct pci_dev *dev, struct acpi_prt_entry *entry) { if (noioapicquirk || noioapicreroute) { return 0; } else { switch (<API key>(dev->bus)) { case 0: /* no rerouting necessary */ return 0; case <API key>: /* * Remap according to INTx routing table in 6700PXH * specs, intel order number 302628-002, section * 2.15.2. Other chipsets (80332, ...) have the same * mapping and are handled here as well. */ dev_info(&dev->dev, "PCI IRQ %d -> rerouted to legacy " "IRQ %d\n", entry->index, (entry->index % 4) + 16); entry->index = (entry->index % 4) + 16; return 1; default: dev_warn(&dev->dev, "Cannot reroute IRQ %d to legacy " "IRQ: unknown mapping\n", entry->index); return -1; } } } #endif /* CONFIG_X86_IO_APIC */ static struct acpi_prt_entry *acpi_pci_irq_lookup(struct pci_dev *dev, int pin) { struct acpi_prt_entry *entry = NULL; struct pci_dev *bridge; u8 bridge_pin, orig_pin = pin; int ret; ret = <API key>(dev, pin, &entry); if (!ret && entry) { #ifdef CONFIG_X86_IO_APIC <API key>(dev, entry); #endif /* CONFIG_X86_IO_APIC */ ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Found %s[%c] _PRT entry\n", pci_name(dev), pin_name(pin))); return entry; } /* * Attempt to derive an IRQ for this device from a parent bridge's * PCI interrupt routing entry (eg. yenta bridge and add-in card bridge). */ bridge = dev->bus->self; while (bridge) { pin = <API key>(dev, pin); if ((bridge->class >> 8) == <API key>) { /* PC card has the same IRQ as its cardbridge */ bridge_pin = bridge->pin; if (!bridge_pin) { ACPI_DEBUG_PRINT((ACPI_DB_INFO, "No interrupt pin configured for device %s\n", pci_name(bridge))); return NULL; } pin = bridge_pin; } ret = <API key>(bridge, pin, &entry); if (!ret && entry) { ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Derived GSI for %s INT %c from %s\n", pci_name(dev), pin_name(orig_pin), pci_name(bridge))); return entry; } dev = bridge; bridge = dev->bus->self; } dev_warn(&dev->dev, "can't derive routing for PCI INT %c\n", pin_name(orig_pin)); return NULL; } #if IS_ENABLED(CONFIG_ISA) || IS_ENABLED(CONFIG_EISA) static int <API key>(struct pci_dev *dev) { u32 dev_gsi; /* Interrupt Line values above 0xF are forbidden */ if (dev->irq > 0 && (dev->irq <= 0xF) && <API key>(dev->irq) && (acpi_isa_irq_to_gsi(dev->irq, &dev_gsi) == 0)) { dev_warn(&dev->dev, "PCI INT %c: no GSI - using ISA IRQ %d\n", pin_name(dev->pin), dev->irq); acpi_register_gsi(&dev->dev, dev_gsi, <API key>, ACPI_ACTIVE_LOW); return 0; } return -EINVAL; } #else static inline int <API key>(struct pci_dev *dev) { return -ENODEV; } #endif static inline bool acpi_pci_irq_valid(struct pci_dev *dev, u8 pin) { #ifdef CONFIG_X86 /* * On x86 irq line 0xff means "unknown" or "no connection" * (PCI 3.0, Section 6.2.4, footnote on page 223). */ if (dev->irq == 0xff) { dev->irq = IRQ_NOTCONNECTED; dev_warn(&dev->dev, "PCI INT %c: not connected\n", pin_name(pin)); return false; } #endif return true; } int acpi_pci_irq_enable(struct pci_dev *dev) { struct acpi_prt_entry *entry; int gsi; u8 pin; int triggering = <API key>; /* * On ARM systems with the GIC interrupt model, level interrupts * are always polarity high by specification; PCI legacy * IRQs lines are inverted before reaching the interrupt * controller and must therefore be considered active high * as default. */ int polarity = acpi_irq_model == ACPI_IRQ_MODEL_GIC ? ACPI_ACTIVE_HIGH : ACPI_ACTIVE_LOW; char *link = NULL; char link_desc[16]; int rc; pin = dev->pin; if (!pin) { ACPI_DEBUG_PRINT((ACPI_DB_INFO, "No interrupt pin configured for device %s\n", pci_name(dev))); return 0; } if (dev->irq_managed && dev->irq > 0) return 0; entry = acpi_pci_irq_lookup(dev, pin); if (!entry) { /* * IDE legacy mode controller IRQs are magic. Why do compat * extensions always make such a nasty mess. */ if (dev->class >> 8 == <API key> && (dev->class & 0x05) == 0) return 0; } if (entry) { if (entry->link) gsi = <API key>(entry->link, entry->index, &triggering, &polarity, &link); else gsi = entry->index; } else gsi = -1; if (gsi < 0) { /* * No IRQ known to the ACPI subsystem - maybe the BIOS / * driver reported one, then use it. Exit in any case. */ if (!acpi_pci_irq_valid(dev, pin)) { kfree(entry); return 0; } if (<API key>(dev)) dev_warn(&dev->dev, "PCI INT %c: no GSI\n", pin_name(pin)); kfree(entry); return 0; } rc = acpi_register_gsi(&dev->dev, gsi, triggering, polarity); if (rc < 0) { dev_warn(&dev->dev, "PCI INT %c: failed to register GSI\n", pin_name(pin)); kfree(entry); return rc; } dev->irq = rc; dev->irq_managed = 1; if (link) snprintf(link_desc, sizeof(link_desc), " -> Link[%s]", link); else link_desc[0] = '\0'; dev_dbg(&dev->dev, "PCI INT %c%s -> GSI %u (%s, %s) -> IRQ %d\n", pin_name(pin), link_desc, gsi, (triggering == <API key>) ? "level" : "edge", (polarity == ACPI_ACTIVE_LOW) ? "low" : "high", dev->irq); kfree(entry); return 0; } void <API key>(struct pci_dev *dev) { struct acpi_prt_entry *entry; int gsi; u8 pin; pin = dev->pin; if (!pin || !dev->irq_managed || dev->irq <= 0) return; /* Keep IOAPIC pin configuration when suspending */ if (dev->dev.power.is_prepared) return; #ifdef CONFIG_PM if (dev->dev.power.runtime_status == RPM_SUSPENDING) return; #endif entry = acpi_pci_irq_lookup(dev, pin); if (!entry) return; if (entry->link) gsi = <API key>(entry->link); else gsi = entry->index; kfree(entry); /* * TBD: It might be worth clearing dev->irq by magic constant * (e.g. PCI_UNDEFINED_IRQ). */ dev_dbg(&dev->dev, "PCI INT %c disabled\n", pin_name(pin)); if (gsi >= 0) { acpi_unregister_gsi(gsi); dev->irq_managed = 0; } }
// This file is part of par2cmdline (a PAR 2.0 compatible file verification and // par2cmdline is free software; you can redistribute it and/or modify // (at your option) any later version. // par2cmdline is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #ifndef <API key> #define <API key> // The <API key> object is used during verification and repair // to record details about a particular source file and the data blocks // for that file. class <API key> { public: // Construct the object and set the description and verification packets <API key>(PAR1FILEENTRY *fileentry, string searchpath); ~<API key>(void); string FileName(void) const {return filename;} u64 FileSize(void) const {return filesize;} const MD5Hash& HashFull(void) const {return hashfull;} const MD5Hash& Hash16k(void) const {return hash16k;} // Set/Get which DiskFile will contain the final repaired version of the file void SetTargetFile(DiskFile *diskfile); DiskFile* GetTargetFile(void) const; // Set/Get whether or not the target file actually exists void SetTargetExists(bool exists); bool GetTargetExists(void) const; // Set/Get which DiskFile contains a full undamaged version of the source file void SetCompleteFile(DiskFile *diskfile); DiskFile* GetCompleteFile(void) const; void SetTargetBlock(DiskFile *diskfile); DataBlock* SourceBlock(void) {return &sourceblock;} DataBlock* TargetBlock(void) {return &targetblock;} protected: string filename; u64 filesize; MD5Hash hashfull; MD5Hash hash16k; DataBlock sourceblock; DataBlock targetblock; bool targetexists; // Whether the target file exists DiskFile *targetfile; // The final version of the file DiskFile *completefile; // A complete version of the file }; #endif // <API key>
<?php /** * @file * Contains \Drupal\Console\Generator\Generator. */ namespace Drupal\Console\Generator; use Drupal\Console\Helper\HelperTrait; use Drupal\Console\Style\DrupalStyle; class Generator { use HelperTrait; /** * @var array */ private $files; /** * @var bool */ private $learning = false; /** * @var array */ private $helperSet; /** * @var DrupalStyle $io */ protected $io; /** * @param string $template * @param string $target * @param array $parameters * @param null $flag * * @return bool */ protected function renderFile($template, $target, $parameters, $flag = null) { if (!is_dir(dirname($target))) { mkdir(dirname($target), 0777, true); } if (file_put_contents($target, $this->getRenderHelper()->render($template, $parameters), $flag)) { $this->files[] = str_replace($this->getDrupalHelper()->getRoot().'/', '', $target); return true; } return false; } /** * @param $helperSet */ public function setHelperSet($helperSet) { $this->helperSet = $helperSet; } /** * @return array */ public function getHelperSet() { return $this->helperSet; } /** * @return array */ public function getFiles() { return $this->files; } /** * @param $learning */ public function setLearning($learning) { $this->learning = $learning; } /** * @return bool */ public function isLearning() { return $this->learning; } /** * @param DrupalStyle $io */ public function setIo($io) { $this->io = $io; } }
#ifndef <API key> #define <API key> #include "common/scummsys.h" #include "sherlock/tattoo/widget_base.h" #include "sherlock/saveload.h" namespace Sherlock { class SherlockEngine; namespace Tattoo { enum FilesRenderMode { RENDER_ALL, RENDER_NAMES, <API key> }; class WidgetFiles: public WidgetBase, public SaveManager { private: SherlockEngine *_vm; SaveMode _fileMode; int _selector, _oldSelector; /** * Render the dialog */ void render(FilesRenderMode mode); /** * Show the ScummVM Save Game dialog */ void <API key>(); /** * Show the ScummVM Load Game dialog */ void <API key>(); /** * Prompt the user for a savegame name in the currently selected slot */ bool getFilename(); /** * Return the area of a widget that the scrollbar will be drawn in */ virtual Common::Rect getScrollBarBounds() const; public: WidgetFiles(SherlockEngine *vm, const Common::String &target); /** * Prompt the user whether to quit */ void show(SaveMode mode); /** * Handle event processing */ virtual void handleEvents(); }; } // End of namespace Tattoo } // End of namespace Sherlock #endif
option( OKULAR_FORCE_DRM "Forces okular to check for DRM to decide if you can copy/print protected pdf. (default=no)" OFF ) if (OKULAR_FORCE_DRM) set(_OKULAR_FORCE_DRM 1) else (OKULAR_FORCE_DRM) set(_OKULAR_FORCE_DRM 0) endif (OKULAR_FORCE_DRM) # at the end, output the configuration configure_file( ${<API key>}/config-okular.h.cmake ${<API key>}/config-okular.h )
#include <setjmp.h> #include <jmpbuf-offsets.h> #include <stdint.h> #include <unwind.h> #include <bits/wordsize.h> #include <sysdep.h> /* Test if longjmp to JMPBUF would unwind the frame containing a local variable at ADDRESS. */ #define _JMPBUF_UNWINDS(jmpbuf, address, demangle) \ ((void *) (address) < (void *) demangle ((jmpbuf)->__gregs[__JB_GPR15])) /* On s390{,x}, CFA is always 96 (resp. 160) bytes above actual %r15. */ #define <API key>(_jmpbuf, _context, _adj) \ _JMPBUF_UNWINDS_ADJ (_jmpbuf, \ (void *) (_Unwind_GetCFA (_context) \ - 32 - 2 * __WORDSIZE), _adj) static inline uintptr_t __attribute__ ((unused)) _jmpbuf_sp (__jmp_buf regs) { void *sp = (void *) (uintptr_t) regs[0].__gregs[__JB_GPR15]; #ifdef PTR_DEMANGLE PTR_DEMANGLE (sp); #endif return (uintptr_t) sp; } #define _JMPBUF_UNWINDS_ADJ(_jmpbuf, _address, _adj) \ ((uintptr_t) (_address) - (_adj) < _jmpbuf_sp (_jmpbuf) - (_adj)) /* We use the normal longjmp for unwinding. */ #define <API key>(buf, val) __libc_longjmp (buf, val)
// { dg-do compile } // { dg-options "-O -w -Wno-psabi" } typedef int vec __attribute__((vector_size(32))); vec fn1() { vec x, zero{}; vec one = zero + 1; return x < zero ? one : zero; }
/** * Creates a notification instance. * * @-x-less Notification.less * @class tinymce.ui.Notification * @extends tinymce.ui.Container * @mixes tinymce.ui.Movable */ define("tinymce/ui/Notification", [ "tinymce/ui/Control", "tinymce/ui/Movable", "tinymce/ui/Progress", "tinymce/util/Delay" ], function(Control, Movable, Progress, Delay) { return Control.extend({ Mixins: [Movable], Defaults: { classes: 'widget notification' }, init: function(settings) { var self = this; self._super(settings); if (settings.text) { self.text(settings.text); } if (settings.icon) { self.icon = settings.icon; } if (settings.color) { self.color = settings.color; } if (settings.type) { self.classes.add('notification-' + settings.type); } if (settings.timeout && (settings.timeout < 0 || settings.timeout > 0) && !settings.closeButton) { self.closeButton = false; } else { self.classes.add('has-close'); self.closeButton = true; } if (settings.progressBar) { self.progressBar = new Progress(); } self.on('click', function(e) { if (e.target.className.indexOf(self.classPrefix + 'close') != -1) { self.close(); } }); }, /** * Renders the control as a HTML string. * * @method renderHtml * @return {String} HTML representing the control. */ renderHtml: function() { var self = this, prefix = self.classPrefix, icon = '', closeButton = '', progressBar = '', notificationStyle = ''; if (self.icon) { icon = '<i class="' + prefix + 'ico' + ' ' + prefix + 'i-' + self.icon + '"></i>'; } if (self.color) { notificationStyle = ' style="background-color: ' + self.color + '"'; } if (self.closeButton) { closeButton = '<button type="button" class="' + prefix + 'close" aria-hidden="true">\u00d7</button>'; } if (self.progressBar) { progressBar = self.progressBar.renderHtml(); } return ( '<div id="' + self._id + '" class="' + self.classes + '"' + notificationStyle + ' role="presentation">' + icon + '<div class="' + prefix + 'notification-inner">' + self.state.get('text') + '</div>' + progressBar + closeButton + '</div>' ); }, postRender: function() { var self = this; Delay.setTimeout(function() { self.$el.addClass(self.classPrefix + 'in'); }); return self._super(); }, bindStates: function() { var self = this; self.state.on('change:text', function(e) { self.getEl().childNodes[1].innerHTML = e.value; }); if (self.progressBar) { self.progressBar.bindStates(); } return self._super(); }, close: function() { var self = this; if (!self.fire('close').isDefaultPrevented()) { self.remove(); } return self; }, /** * Repaints the control after a layout operation. * * @method repaint */ repaint: function() { var self = this, style, rect; style = self.getEl().style; rect = self._layoutRect; style.left = rect.x + 'px'; style.top = rect.y + 'px'; // Hardcoded arbitrary z-value because we want the // notifications under the other windows style.zIndex = 0xFFFF - 1; } }); });
<?php /** * Generic Slider super class. Extended by library specific classes. */ class MetaImageSlide extends MetaSlide { /** * Register slide type */ public function __construct() { add_filter( '<API key>', array( $this, 'get_slide' ), 10, 2 ); add_action( '<API key>', array( $this, 'save_slide' ), 5, 3 ); add_action( '<API key>', array( $this, 'ajax_create_slide' ) ); add_action( '<API key>', array( $this, 'ajax_resize_slide' ) ); } /** * Create a new slide and echo the admin HTML */ public function ajax_create_slide() { // security check if ( !wp_verify_nonce( $_REQUEST['_wpnonce'], 'metaslider_addslide' ) ) { echo "<tr><td colspan='2'>" . __( "Security check failed. Refresh page and try again.", 'metaslider' ) . "</td></tr>"; die(); } $slider_id = absint( $_POST['slider_id'] ); $selection = $_POST['selection']; if ( is_array( $selection ) && count( $selection ) && $slider_id > 0 ) { foreach ( $selection as $slide_id ) { $this->set_slide( $slide_id ); $this->set_slider( $slider_id ); if ( $this-><API key>( $slider_id, $slide_id ) ) { echo "<tr><td colspan='2'>ID: {$slide_id} \"" . get_the_title( $slide_id ) . "\" - " . __( "Failed to add slide. Slide already exists in slideshow.", 'metaslider' ) . "</td></tr>"; } else if ( !$this-><API key>( $slider_id, $slide_id ) ) { echo "<tr><td colspan='2'>ID: {$slide_id} \"" . get_the_title( $slide_id ) . "\" - " . __( "Failed to add slide. Slide is not of type 'image'.", 'metaslider' ) . "</td></tr>"; }else { $this->tag_slide_to_slider(); $this-><API key>( $slide_id, 'type', 'image' ); // override the width and height to kick off the AJAX image resizing on save $this->settings['width'] = 0; $this->settings['height'] = 0; echo $this->get_admin_slide(); } } } die(); } /** * Create a new slide and echo the admin HTML */ public function ajax_resize_slide() { check_admin_referer( 'metaslider_resize' ); $slider_id = absint( $_POST['slider_id'] ); $slide_id = absint( $_POST['slide_id'] ); $this->set_slide( $slide_id ); $this->set_slider( $slider_id ); $settings = get_post_meta( $slider_id, 'ml-slider_settings', true ); // create a copy of the correct sized image $imageHelper = new <API key>( $slide_id, $settings['width'], $settings['height'], isset( $settings['smartCrop'] ) ? $settings['smartCrop'] : 'false', $this->use_wp_image_editor() ); $url = $imageHelper->get_image_url(); echo $url . " (" . $settings['width'] . 'x' . $settings['height'] . ")"; die(); } /** * Return the HTML used to display this slide in the admin screen * * @return string slide html */ protected function get_admin_slide() { // get some slide settings $imageHelper = new <API key>( $this->slide->ID, 150, 150, 'false', $this->use_wp_image_editor() ); $thumb = $imageHelper->get_image_url(); $url = get_post_meta( $this->slide->ID, 'ml-slider_url', true ); $title = get_post_meta( $this->slide->ID, 'ml-slider_title', true ); $alt = get_post_meta( $this->slide->ID, '<API key>', true ); $target = get_post_meta( $this->slide->ID, '<API key>', true ) ? 'checked=checked' : ''; $caption = htmlentities( $this->slide->post_excerpt, ENT_QUOTES, 'UTF-8' ); // localisation $str_caption = __( "Caption", "metaslider" ); $str_new_window = __( "New Window", "metaslider" ); $str_url = __( "URL", "metaslider" ); $str_label = __( "Image Slide", "metaslider" ); $slide_label = apply_filters( "<API key>", $str_label, $this->slide, $this->settings ); // slide row HTML $row = "<tr class='slide image flex responsive nivo coin'>"; $row .= " <td class='col-1'>"; $row .= " <div class='thumb' style='background-image: url({$thumb})'>"; $row .= " <a class='delete-slide confirm' href='?page=metaslider&amp;id={$this->slider->ID}&amp;deleteSlide={$this->slide->ID}'>x</a>"; $row .= " <span class='slide-details'>" . $slide_label . "</span>"; $row .= " </div>"; $row .= " </td>"; $row .= " <td class='col-2'>"; $row .= " <ul class='tabs'>"; $row .= " <li class='selected' rel='tab-1'>" . __( "General", "metaslider" ) . "</li>"; $row .= " <li rel='tab-2'>" . __( "SEO", "metaslider" ) . "</li>"; $row .= " </ul>"; $row .= " <div class='tabs-content'>"; $row .= " <div class='tab tab-1'>"; if ( !$this->is_valid_image() ) { $row .= "<div class='warning'>" . __( "Warning: Image data does not exist. Please re-upload the image.", "metaslider" ) . "</div>"; } $row .= " <textarea name='attachment[{$this->slide->ID}][post_excerpt]' placeholder='{$str_caption}'>{$caption}</textarea>"; $row .= " <input class='url' type='text' name='attachment[{$this->slide->ID}][url]' placeholder='{$str_url}' value='{$url}' />"; $row .= " <div class='new_window'>"; $row .= " <label>{$str_new_window}<input type='checkbox' name='attachment[{$this->slide->ID}][new_window]' {$target} /></label>"; $row .= " </div>"; $row .= " </div>"; $row .= " <div class='tab tab-2' style='display: none;'>"; $row .= " <div class='row'><label>" . __( "Image Title Text", "metaslider" ) . "</label></div>"; $row .= " <div class='row'><input type='text' size='50' name='attachment[{$this->slide->ID}][title]' value='{$title}' /></div>"; $row .= " <div class='row'><label>" . __( "Image Alt Text", "metaslider" ) . "</label></div>"; $row .= " <div class='row'><input type='text' size='50' name='attachment[{$this->slide->ID}][alt]' value='{$alt}' /></div>"; $row .= " </div>"; $row .= " </div>"; $row .= " <input type='hidden' name='attachment[{$this->slide->ID}][type]' value='image' />"; $row .= " <input type='hidden' class='menu_order' name='attachment[{$this->slide->ID}][menu_order]' value='{$this->slide->menu_order}' />"; $row .= " <input type='hidden' name='resize_slide_id' data-slide_id='{$this->slide->ID}' data-width='{$this->settings['width']}' data-height='{$this->settings['height']}' />"; $row .= " </td>"; $row .= "</tr>"; return $row; } /** * Check to see if metadata exists for this image. Assume the image is * valid if metadata and a size exists for it (generated during initial * upload to WordPress). * * @return bool, true if metadata and size exists. */ public function is_valid_image() { $meta = <API key>( $this->slide->ID ); return isset( $meta['width'], $meta['height'] ); } /** * Disable/enable image editor * * @return bool */ public function use_wp_image_editor() { return apply_filters( '<API key>', $this->is_valid_image() ); } /** * Returns the HTML for the public slide * * @return string slide html */ protected function get_public_slide() { // get the image url (and handle cropping) // disable wp_image_editor if metadata does not exist for the slide $imageHelper = new <API key>( $this->slide->ID, $this->settings['width'], $this->settings['height'], isset( $this->settings['smartCrop'] ) ? $this->settings['smartCrop'] : 'false', $this->use_wp_image_editor() ); $thumb = $imageHelper->get_image_url(); // store the slide details $slide = array( 'id' => $this->slide->ID, 'url' => __( get_post_meta( $this->slide->ID, 'ml-slider_url', true ) ), 'title' => __( get_post_meta( $this->slide->ID, 'ml-slider_title', true ) ), 'target' => get_post_meta( $this->slide->ID, '<API key>', true ) ? '_blank' : '_self', 'src' => $thumb, 'thumb' => $thumb, // backwards compatibility with Vantage 'width' => $this->settings['width'], 'height' => $this->settings['height'], 'alt' => __( get_post_meta( $this->slide->ID, '<API key>', true ) ), 'caption' => __( html_entity_decode( do_shortcode( $this->slide->post_excerpt ), ENT_NOQUOTES, 'UTF-8' ) ), 'caption_raw' => __( do_shortcode( $this->slide->post_excerpt ) ), 'class' => "slider-{$this->slider->ID} slide-{$this->slide->ID}", 'rel' => "", 'data-thumb' => "" ); // fix slide URLs if ( strpos( $slide['url'], 'www.' ) === 0 ) { $slide['url'] = 'http://' . $slide['url']; } $slide = apply_filters( '<API key>', $slide, $this->slider->ID, $this->settings ); // return the slide HTML switch ( $this->settings['type'] ) { case "coin": return $this-><API key>( $slide ); case "flex": return $this-><API key>( $slide ); case "nivo": return $this-><API key>( $slide ); case "responsive": return $this-><API key>( $slide ); default: return $this-><API key>( $slide ); } } /** * Generate nivo slider markup * * @return string slide html */ private function <API key>( $slide ) { $attributes = apply_filters( '<API key>', array( 'src' => $slide['src'], 'height' => $slide['height'], 'width' => $slide['width'], 'data-title' => htmlentities( $slide['caption_raw'], ENT_QUOTES, 'UTF-8' ), 'data-thumb' => $slide['data-thumb'], 'title' => $slide['title'], 'alt' => $slide['alt'], 'rel' => $slide['rel'], 'class' => $slide['class'] ), $slide, $this->slider->ID ); $html = $this->build_image_tag( $attributes ); $anchor_attributes = apply_filters( '<API key>', array( 'href' => $slide['url'], 'target' => $slide['target'] ), $slide, $this->slider->ID ); if ( strlen( $anchor_attributes['href'] ) ) { $html = $this->build_anchor_tag( $anchor_attributes, $html ); } return apply_filters( '<API key>', $html, $slide, $this->settings ); } /** * Generate flex slider markup * * @return string slide html */ private function <API key>( $slide ) { $attributes = apply_filters( '<API key>', array( 'src' => $slide['src'], 'height' => $slide['height'], 'width' => $slide['width'], 'alt' => $slide['alt'], 'rel' => $slide['rel'], 'class' => $slide['class'], 'title' => $slide['title'] ), $slide, $this->slider->ID ); $html = $this->build_image_tag( $attributes ); $anchor_attributes = apply_filters( '<API key>', array( 'href' => $slide['url'], 'target' => $slide['target'] ), $slide, $this->slider->ID ); if ( strlen( $anchor_attributes['href'] ) ) { $html = $this->build_anchor_tag( $anchor_attributes, $html ); } // add caption if ( strlen( $slide['caption'] ) ) { $html .= '<div class="caption-wrap"><div class="caption">' . $slide['caption'] . '</div></div>'; } $thumb = isset( $slide['data-thumb'] ) && strlen( $slide['data-thumb'] ) ? " data-thumb=\"{$slide['data-thumb']}\"" : ""; $html = '<li style="display: none; float: left; width: 100%;"' . $thumb . '>' . $html . '</li>'; return apply_filters( '<API key>', $html, $slide, $this->settings ); } /** * Generate coin slider markup * * @return string slide html */ private function <API key>( $slide ) { $attributes = apply_filters( '<API key>', array( 'src' => $slide['src'], 'height' => $slide['height'], 'width' => $slide['width'], 'alt' => $slide['alt'], 'rel' => $slide['rel'], 'class' => $slide['class'], 'title' => $slide['title'], 'style' => 'display: none;' ), $slide, $this->slider->ID ); $html = $this->build_image_tag( $attributes ); if ( strlen( $slide['caption'] ) ) { $html .= "<span>{$slide['caption']}</span>"; } $attributes = apply_filters( '<API key>', array( 'href' => strlen( $slide['url'] ) ? $slide['url'] : 'javascript:void(0)' ), $slide, $this->slider->ID ); $html = $this->build_anchor_tag( $attributes, $html ); return apply_filters( '<API key>', $html, $slide, $this->settings ); } /** * Generate responsive slides markup * * @return string slide html */ private function <API key>( $slide ) { $attributes = apply_filters( '<API key>', array( 'src' => $slide['src'], 'height' => $slide['height'], 'width' => $slide['width'], 'alt' => $slide['alt'], 'rel' => $slide['rel'], 'class' => $slide['class'], 'title' => $slide['title'] ), $slide, $this->slider->ID ); $html = $this->build_image_tag( $attributes ); if ( strlen( $slide['caption'] ) ) { $html .= '<div class="caption-wrap"><div class="caption">' . $slide['caption'] . '</div></div>'; } $anchor_attributes = apply_filters( '<API key>', array( 'href' => $slide['url'], 'target' => $slide['target'] ), $slide, $this->slider->ID ); if ( strlen( $anchor_attributes['href'] ) ) { $html = $this->build_anchor_tag( $anchor_attributes, $html ); } return apply_filters( '<API key>', $html, $slide, $this->settings ); } /** * Save */ protected function save( $fields ) { // update the slide wp_update_post( array( 'ID' => $this->slide->ID, 'post_excerpt' => $fields['post_excerpt'], 'menu_order' => $fields['menu_order'] ) ); // store the URL as a meta field against the attachment $this-><API key>( $this->slide->ID, 'url', $fields['url'] ); $this-><API key>( $this->slide->ID, 'title', $fields['title'] ); if ( isset( $fields['alt'] ) ) { update_post_meta( $this->slide->ID, '<API key>', $fields['alt'] ); } // store the 'new window' setting $new_window = isset( $fields['new_window'] ) && $fields['new_window'] == 'on' ? 'true' : 'false'; $this-><API key>( $this->slide->ID, 'new_window', $new_window ); } } ?>
#include "precompiled.hpp" #include "classfile/symbolTable.hpp" #include "gc_implementation/parallelScavenge/cardTableExtension.hpp" #include "gc_implementation/parallelScavenge/gcTaskManager.hpp" #include "gc_implementation/parallelScavenge/generationSizer.hpp" #include "gc_implementation/parallelScavenge/<API key>.hpp" #include "gc_implementation/parallelScavenge/<API key>.hpp" #include "gc_implementation/parallelScavenge/psMarkSweep.hpp" #include "gc_implementation/parallelScavenge/psParallelCompact.hpp" #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp" #include "gc_implementation/parallelScavenge/psTasks.hpp" #include "gc_implementation/shared/isGCActiveMark.hpp" #include "gc_implementation/shared/spaceDecorator.hpp" #include "gc_interface/gcCause.hpp" #include "memory/collectorPolicy.hpp" #include "memory/gcLocker.inline.hpp" #include "memory/referencePolicy.hpp" #include "memory/referenceProcessor.hpp" #include "memory/resourceArea.hpp" #include "oops/oop.inline.hpp" #include "oops/oop.psgc.inline.hpp" #include "runtime/biasedLocking.hpp" #include "runtime/fprofiler.hpp" #include "runtime/handles.inline.hpp" #include "runtime/threadCritical.hpp" #include "runtime/vmThread.hpp" #include "runtime/vm_operations.hpp" #include "services/memoryService.hpp" #include "utilities/stack.inline.hpp" HeapWord* PSScavenge::<API key> = NULL; int PSScavenge::<API key> = 0; ReferenceProcessor* PSScavenge::_ref_processor = NULL; CardTableExtension* PSScavenge::_card_table = NULL; bool PSScavenge::_survivor_overflow = false; int PSScavenge::_tenuring_threshold = 0; HeapWord* PSScavenge::<API key> = NULL; elapsedTimer PSScavenge::_accumulated_time; Stack<markOop> PSScavenge::<API key>; Stack<oop> PSScavenge::<API key>; CollectorCounters* PSScavenge::_counters = NULL; bool PSScavenge::_promotion_failed = false; // Define before use class PSIsAliveClosure: public BoolObjectClosure { public: void do_object(oop p) { assert(false, "Do not call."); } bool do_object_b(oop p) { return (!PSScavenge::is_obj_in_young((HeapWord*) p)) || p->is_forwarded(); } }; PSIsAliveClosure PSScavenge::_is_alive_closure; class PSKeepAliveClosure: public OopClosure { protected: MutableSpace* _to_space; PSPromotionManager* _promotion_manager; public: PSKeepAliveClosure(PSPromotionManager* pm) : _promotion_manager(pm) { <API key>* heap = (<API key>*)Universe::heap(); assert(heap->kind() == CollectedHeap::<API key>, "Sanity"); _to_space = heap->young_gen()->to_space(); assert(_promotion_manager != NULL, "Sanity"); } template <class T> void do_oop_work(T* p) { assert (!oopDesc::is_null(*p), "expected non-null ref"); assert ((oopDesc::<API key>(p))->is_oop(), "expected an oop while scanning weak refs"); // Weak refs may be visited more than once. if (PSScavenge::should_scavenge(p, _to_space)) { PSScavenge::<API key>(_promotion_manager, p); } } virtual void do_oop(oop* p) { PSKeepAliveClosure::do_oop_work(p); } virtual void do_oop(narrowOop* p) { PSKeepAliveClosure::do_oop_work(p); } }; class <API key>: public VoidClosure { private: PSPromotionManager* _promotion_manager; public: <API key>(PSPromotionManager* pm) : _promotion_manager(pm) {} virtual void do_void() { assert(_promotion_manager != NULL, "Sanity"); _promotion_manager->drain_stacks(true); guarantee(_promotion_manager->stacks_empty(), "stacks should be empty at this point"); } }; class <API key> : public ObjectClosure { virtual void do_object(oop obj) { if (obj->is_forwarded()) { obj->init_mark(); } } }; class PSRefProcTaskProxy: public GCTask { typedef <API key>::ProcessTask ProcessTask; ProcessTask & _rp_task; uint _work_id; public: PSRefProcTaskProxy(ProcessTask & rp_task, uint work_id) : _rp_task(rp_task), _work_id(work_id) { } private: virtual char* name() { return (char *)"Process referents by policy in parallel"; } virtual void do_it(GCTaskManager* manager, uint which); }; void PSRefProcTaskProxy::do_it(GCTaskManager* manager, uint which) { PSPromotionManager* promotion_manager = PSPromotionManager::<API key>(which); assert(promotion_manager != NULL, "sanity check"); PSKeepAliveClosure keep_alive(promotion_manager); <API key> evac_followers(promotion_manager); PSIsAliveClosure is_alive; _rp_task.work(_work_id, is_alive, keep_alive, evac_followers); } class <API key>: public GCTask { typedef <API key>::EnqueueTask EnqueueTask; EnqueueTask& _enq_task; uint _work_id; public: <API key>(EnqueueTask& enq_task, uint work_id) : _enq_task(enq_task), _work_id(work_id) { } virtual char* name() { return (char *)"Enqueue reference objects in parallel"; } virtual void do_it(GCTaskManager* manager, uint which) { _enq_task.work(_work_id); } }; class <API key>: public <API key> { virtual void execute(ProcessTask& task); virtual void execute(EnqueueTask& task); }; void <API key>::execute(ProcessTask& task) { GCTaskQueue* q = GCTaskQueue::create(); for(uint i=0; i<ParallelGCThreads; i++) { q->enqueue(new PSRefProcTaskProxy(task, i)); } <API key> terminator( <API key>::gc_task_manager()->workers(), (TaskQueueSetSuper*) PSPromotionManager::stack_array_depth()); if (task.marks_oops_alive() && ParallelGCThreads > 1) { for (uint j=0; j<ParallelGCThreads; j++) { q->enqueue(new StealTask(&terminator)); } } <API key>::gc_task_manager()->execute_and_wait(q); } void <API key>::execute(EnqueueTask& task) { GCTaskQueue* q = GCTaskQueue::create(); for(uint i=0; i<ParallelGCThreads; i++) { q->enqueue(new <API key>(task, i)); } <API key>::gc_task_manager()->execute_and_wait(q); } // This method contains all heap specific policy for invoking scavenge. // PSScavenge::invoke_no_policy() will do nothing but attempt to // scavenge. It will not clean up after failed promotions, bail out if // we've exceeded policy time limits, or any other special behavior. // All such policy should be placed here. // Note that this method should only be called from the vm_thread while // at a safepoint! void PSScavenge::invoke() { assert(<API key>::is_at_safepoint(), "should be at safepoint"); assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); assert(!Universe::heap()->is_gc_active(), "not reentrant"); <API key>* heap = (<API key>*)Universe::heap(); assert(heap->kind() == CollectedHeap::<API key>, "Sanity"); <API key>* policy = heap->size_policy(); IsGCActiveMark mark; bool scavenge_was_done = PSScavenge::invoke_no_policy(); <API key>* counters = heap->gc_policy_counters(); if (UsePerfData) counters-><API key>(0); if (!scavenge_was_done || policy->should_full_GC(heap->old_gen()->free_in_bytes())) { if (UsePerfData) counters-><API key>(<API key>); GCCauseSetter gccs(heap, GCCause::<API key>); CollectorPolicy* cp = heap->collector_policy(); const bool clear_all_softrefs = cp-><API key>(); if (UseParallelOldGC) { PSParallelCompact::invoke_no_policy(clear_all_softrefs); } else { PSMarkSweep::invoke_no_policy(clear_all_softrefs); } } } // This method contains no policy. You should probably // be calling invoke() instead. bool PSScavenge::invoke_no_policy() { assert(<API key>::is_at_safepoint(), "should be at safepoint"); assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); assert(<API key>.is_empty(), "should be empty"); assert(<API key>.is_empty(), "should be empty"); TimeStamp scavenge_entry; TimeStamp scavenge_midpoint; TimeStamp scavenge_exit; scavenge_entry.update(); if (GC_locker::<API key>()) { return false; } <API key>* heap = (<API key>*)Universe::heap(); GCCause::Cause gc_cause = heap->gc_cause(); assert(heap->kind() == CollectedHeap::<API key>, "Sanity"); // Check for potential problems. if (!<API key>()) { return false; } bool <API key> = false; PSYoungGen* young_gen = heap->young_gen(); PSOldGen* old_gen = heap->old_gen(); PSPermGen* perm_gen = heap->perm_gen(); <API key>* size_policy = heap->size_policy(); heap-><API key>(); <API key>(size_policy, heap->total_collections()); if ((gc_cause != GCCause::<API key>) || <API key>) { // Gather the feedback data for eden occupancy. young_gen->eden_space()-><API key>(); } if (ZapUnusedHeapArea) { // Save information needed to minimize mangling heap-><API key>(); } if (PrintHeapAtGC) { Universe::<API key>(); } assert(!NeverTenure || _tenuring_threshold == markOopDesc::max_age + 1, "Sanity"); assert(!AlwaysTenure || _tenuring_threshold == 0, "Sanity"); size_t prev_used = heap->used(); assert(promotion_failed() == false, "Sanity"); // Fill in TLABs heap-><API key>(); heap->ensure_parsability(true); // retire TLABs if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) { HandleMark hm; // Discard invalid handles created during verification gclog_or_tty->print(" VerifyBeforeGC:"); Universe::verify(true); } { ResourceMark rm; HandleMark hm; gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps); TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); TraceTime t1("GC", PrintGC, !PrintGCDetails, gclog_or_tty); TraceCollectorStats tcs(counters()); <API key> tms(false /* not full GC */,gc_cause); if (TraceGen0Time) accumulated_time()->start(); // Let the size policy know we're starting size_policy-><API key>(); // Verify the object start arrays. if (<API key> && VerifyBeforeGC) { old_gen-><API key>(); perm_gen-><API key>(); } // Verify no unmarked old->young roots if (<API key>) { CardTableExtension::<API key>(); } if (!<API key>) { assert(young_gen->to_space()->is_empty(), "Attempt to scavenge with live objects in to_space"); young_gen->to_space()->clear(SpaceDecorator::Mangle); } else if (ZapUnusedHeapArea) { young_gen->to_space()->mangle_unused_area(); } <API key>(); NOT_PRODUCT(reference_processor()-><API key>()); COMPILER2_PRESENT(DerivedPointerTable::clear()); reference_processor()->enable_discovery(); reference_processor()->setup_policy(false); // We track how much was promoted to the next generation for // the AdaptiveSizePolicy. size_t old_gen_used_before = old_gen->used_in_bytes(); // For PrintGCDetails size_t <API key> = young_gen->used_in_bytes(); // Reset our survivor overflow. <API key>(false); // We need to save the old/perm top values before // creating the promotion_manager. We pass the top // values to the card_table, to prevent it from // straying into the promotion labs. HeapWord* old_top = old_gen->object_space()->top(); HeapWord* perm_top = perm_gen->object_space()->top(); // Release all previously held resources gc_task_manager()-><API key>(); PSPromotionManager::pre_scavenge(); // We'll use the promotion manager again later. PSPromotionManager* promotion_manager = PSPromotionManager::<API key>(); { // TraceTime("Roots"); <API key>::ParStrongRootsScope psrs; GCTaskQueue* q = GCTaskQueue::create(); for(uint i=0; i<ParallelGCThreads; i++) { q->enqueue(new OldToYoungRootsTask(old_gen, old_top, i)); } q->enqueue(new <API key>(perm_gen, perm_top)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::universe)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::jni_handles)); // We scan the thread roots in parallel Threads::<API key>(q); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::object_synchronizer)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::flat_profiler)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::management)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::system_dictionary)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::jvmti)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::code_cache)); <API key> terminator( gc_task_manager()->workers(), (TaskQueueSetSuper*) promotion_manager->stack_array_depth()); if (ParallelGCThreads>1) { for (uint j=0; j<ParallelGCThreads; j++) { q->enqueue(new StealTask(&terminator)); } } gc_task_manager()->execute_and_wait(q); } scavenge_midpoint.update(); // Process reference objects discovered during scavenge { reference_processor()->setup_policy(false); // not always_clear PSKeepAliveClosure keep_alive(promotion_manager); <API key> evac_followers(promotion_manager); if (reference_processor()->processing_is_mt()) { <API key> task_executor; reference_processor()-><API key>( &_is_alive_closure, &keep_alive, &evac_followers, &task_executor); } else { reference_processor()-><API key>( &_is_alive_closure, &keep_alive, &evac_followers, NULL); } } // Enqueue reference objects discovered during scavenge. if (reference_processor()->processing_is_mt()) { <API key> task_executor; reference_processor()-><API key>(&task_executor); } else { reference_processor()-><API key>(NULL); } if (!JavaObjectsInPerm) { // Unlink any dead interned Strings StringTable::unlink(&_is_alive_closure); // Process the remaining live ones <API key> root_closure(promotion_manager); StringTable::oops_do(&root_closure); } // Finally, flush the promotion_manager's labs, and deallocate its stacks. PSPromotionManager::post_scavenge(); <API key> = promotion_failed(); if (<API key>) { <API key>(); if (PrintGC) { gclog_or_tty->print(" } } // Let the size policy know we're done. Note that we count promotion // failure cleanup time as part of the collection (otherwise, we're // implicitly saying it's mutator time). size_policy-><API key>(gc_cause); if (!<API key>) { // Swap the survivor spaces. young_gen->eden_space()->clear(SpaceDecorator::Mangle); young_gen->from_space()->clear(SpaceDecorator::Mangle); young_gen->swap_spaces(); size_t survived = young_gen->from_space()->used_in_bytes(); size_t promoted = old_gen->used_in_bytes() - old_gen_used_before; size_policy->update_averages(_survivor_overflow, survived, promoted); // A successful scavenge should restart the GC time limit count which is // for full GC's. size_policy-><API key>(); if (<API key>) { // Calculate the new survivor size and tenuring threshold if (<API key>) { gclog_or_tty->print("AdaptiveSizeStart: "); gclog_or_tty->stamp(); gclog_or_tty->print_cr(" collection: %d ", heap->total_collections()); if (Verbose) { gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d" " perm_gen_capacity: %d ", old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes(), perm_gen->capacity_in_bytes()); } } if (UsePerfData) { <API key>* counters = heap->gc_policy_counters(); counters-><API key>( size_policy-><API key>()); counters-><API key>( size_policy-><API key>()); counters->update_old_capacity(old_gen->capacity_in_bytes()); counters-><API key>(young_gen->capacity_in_bytes()); counters->update_survived(survived); counters->update_promoted(promoted); counters-><API key>(_survivor_overflow); } size_t survivor_limit = size_policy->max_survivor_size(young_gen->max_size()); _tenuring_threshold = size_policy-><API key>( _survivor_overflow, _tenuring_threshold, survivor_limit); if (<API key>) { gclog_or_tty->cr(); gclog_or_tty->print_cr("Desired survivor size %ld bytes, new threshold %d (max %d)", size_policy-><API key>(), _tenuring_threshold, <API key>); } if (UsePerfData) { <API key>* counters = heap->gc_policy_counters(); counters-><API key>(_tenuring_threshold); counters-><API key>(); } // Do call at minor collections? // Don't check if the size_policy is ready at this // level. Let the size_policy check that internally. if (<API key> && <API key> && ((gc_cause != GCCause::<API key>) || <API key>)) { // Calculate optimial free space amounts assert(young_gen->max_size() > young_gen->from_space()->capacity_in_bytes() + young_gen->to_space()->capacity_in_bytes(), "Sizes of space in young gen are out-of-bounds"); size_t max_eden_size = young_gen->max_size() - young_gen->from_space()->capacity_in_bytes() - young_gen->to_space()->capacity_in_bytes(); size_policy-><API key>(young_gen->used_in_bytes(), young_gen->eden_space()->used_in_bytes(), old_gen->used_in_bytes(), perm_gen->used_in_bytes(), young_gen->eden_space()->capacity_in_bytes(), old_gen->max_gen_size(), max_eden_size, false /* full gc*/, gc_cause, heap->collector_policy()); } // Resize the young generation at every collection // even if new sizes have not been calculated. This is // to allow resizes that may have been inhibited by the // relative location of the "to" and "from" spaces. // Resizing the old gen at minor collects can cause increases // that don't feed back to the generation sizing policy until // a major collection. Don't resize the old gen here. heap->resize_young_gen(size_policy-><API key>(), size_policy-><API key>()); if (<API key>) { gclog_or_tty->print_cr("AdaptiveSizeStop: collection: %d ", heap->total_collections()); } } // Update the structure of the eden. With NUMA-eden CPU hotplugging or offlining can // cause the change of the heap layout. Make sure eden is reshaped if that's the case. // Also update() will case adaptive NUMA chunk resizing. assert(young_gen->eden_space()->is_empty(), "eden space should be empty now"); young_gen->eden_space()->update(); heap->gc_policy_counters()->update_counters(); heap->resize_all_tlabs(); assert(young_gen->to_space()->is_empty(), "to space should be empty now"); } COMPILER2_PRESENT(DerivedPointerTable::update_pointers()); NOT_PRODUCT(reference_processor()-><API key>()); // Re-verify object start arrays if (<API key> && VerifyAfterGC) { old_gen-><API key>(); perm_gen-><API key>(); } // Verify all old -> young cards are now precise if (<API key>) { // Precise verification will give false positives. Until this is fixed, // use imprecise verification. // CardTableExtension::<API key>(); CardTableExtension::<API key>(); } if (TraceGen0Time) accumulated_time()->stop(); if (PrintGC) { if (PrintGCDetails) { // Don't print a GC timestamp here. This is after the GC so // would be confusing. young_gen->print_used_change(<API key>); } heap->print_heap_change(prev_used); } // Track memory usage and detect low memory MemoryService::track_memory_usage(); heap->update_counters(); } if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) { HandleMark hm; // Discard invalid handles created during verification gclog_or_tty->print(" VerifyAfterGC:"); Universe::verify(false); } if (PrintHeapAtGC) { Universe::print_heap_after_gc(); } if (ZapUnusedHeapArea) { young_gen->eden_space()-><API key>(); young_gen->from_space()-><API key>(); young_gen->to_space()-><API key>(); } scavenge_exit.update(); if (<API key>) { tty->print_cr("VM-Thread " INT64_FORMAT " " INT64_FORMAT " " INT64_FORMAT, scavenge_entry.ticks(), scavenge_midpoint.ticks(), scavenge_exit.ticks()); gc_task_manager()-><API key>(); } #ifdef TRACESPINNING <API key>::<API key>(); #endif return !<API key>; } // This method iterates over all objects in the young generation, // unforwarding markOops. It then restores any preserved mark oops, // and clears the <API key>. void PSScavenge::<API key>() { <API key>* heap = (<API key>*)Universe::heap(); assert(heap->kind() == CollectedHeap::<API key>, "Sanity"); assert(promotion_failed(), "Sanity"); PSYoungGen* young_gen = heap->young_gen(); { ResourceMark rm; // Unforward all pointers in the young gen. <API key> unforward_closure; young_gen->object_iterate(&unforward_closure); if (PrintGC && Verbose) { gclog_or_tty->print_cr("Restoring %d marks", <API key>.size()); } // Restore any saved marks. while (!<API key>.is_empty()) { oop obj = <API key>.pop(); markOop mark = <API key>.pop(); obj->set_mark(mark); } // Clear the preserved mark and oop stack caches. <API key>.clear(true); <API key>.clear(true); _promotion_failed = false; } // Reset the <API key> counters. NOT_PRODUCT(Universe::heap()-><API key>();) } // This method is called whenever an attempt to promote an object // fails. Some markOops will need preservation, some will not. Note // that the entire eden is traversed after a failed promotion, with // all forwarded headers replaced by the default markOop. This means // it is not neccessary to preserve most markOops. void PSScavenge::<API key>(oop obj, markOop obj_mark) { _promotion_failed = true; if (obj_mark-><API key>(obj)) { // Should use per-worker private stakcs hetre rather than // locking a common pair of stacks. ThreadCritical tc; <API key>.push(obj); <API key>.push(obj_mark); } } bool PSScavenge::<API key>() { <API key>* heap = (<API key>*)Universe::heap(); assert(heap->kind() == CollectedHeap::<API key>, "Sanity"); <API key>* counters = heap->gc_policy_counters(); if (UsePerfData) { counters-><API key>(not_skipped); } PSYoungGen* young_gen = heap->young_gen(); PSOldGen* old_gen = heap->old_gen(); if (!<API key>) { // Do not attempt to promote unless to_space is empty if (!young_gen->to_space()->is_empty()) { <API key>++; if (UsePerfData) { counters-><API key>(to_space_not_empty); } return false; } } // Test to see if the scavenge will likely fail. <API key>* policy = heap->size_policy(); // A similar test is done in the policy's should_full_GC(). If this is // changed, decide if that test should also be changed. size_t avg_promoted = (size_t) policy-><API key>(); size_t promotion_estimate = MIN2(avg_promoted, young_gen->used_in_bytes()); bool result = promotion_estimate < old_gen->free_in_bytes(); if (PrintGCDetails && Verbose) { gclog_or_tty->print(result ? " do scavenge: " : " skip scavenge: "); gclog_or_tty->print_cr(" average_promoted " SIZE_FORMAT " <API key> " SIZE_FORMAT " free in old gen " SIZE_FORMAT, (size_t) policy-><API key>(), (size_t) policy-><API key>(), old_gen->free_in_bytes()); if (young_gen->used_in_bytes() < (size_t) policy-><API key>()) { gclog_or_tty->print_cr(" <API key> is greater" " than maximum promotion = " SIZE_FORMAT, young_gen->used_in_bytes()); } } if (result) { <API key> = 0; } else { <API key>++; if (UsePerfData) { counters-><API key>(promoted_too_large); } } return result; } // Used to add tasks GCTaskManager* const PSScavenge::gc_task_manager() { assert(<API key>::gc_task_manager() != NULL, "shouldn't return NULL"); return <API key>::gc_task_manager(); } void PSScavenge::initialize() { // Arguments must have been parsed if (AlwaysTenure) { _tenuring_threshold = 0; } else if (NeverTenure) { _tenuring_threshold = markOopDesc::max_age + 1; } else { // We want to smooth out our startup times for the AdaptiveSizePolicy _tenuring_threshold = (<API key>) ? <API key> : <API key>; } <API key>* heap = (<API key>*)Universe::heap(); assert(heap->kind() == CollectedHeap::<API key>, "Sanity"); PSYoungGen* young_gen = heap->young_gen(); PSOldGen* old_gen = heap->old_gen(); PSPermGen* perm_gen = heap->perm_gen(); // Set boundary between young_gen and old_gen assert(perm_gen->reserved().end() <= old_gen->object_space()->bottom(), "perm above old"); assert(old_gen->reserved().end() <= young_gen->eden_space()->bottom(), "old above young"); <API key> = young_gen->eden_space()->bottom(); // Initialize ref handling object for scavenging. MemRegion mr = young_gen->reserved(); _ref_processor = new ReferenceProcessor(mr, // span <API key> && (ParallelGCThreads > 1), // mt processing (int) ParallelGCThreads, // mt processing degree true, // mt discovery (int) ParallelGCThreads, // mt discovery degree true, // atomic_discovery NULL, // header provides liveness info false); // next field updates do not need write barrier // Cache the cardtable BarrierSet* bs = Universe::heap()->barrier_set(); assert(bs->kind() == BarrierSet::CardTableModRef, "Wrong barrier set kind"); _card_table = (CardTableExtension*)bs; _counters = new CollectorCounters("PSScavenge", 0); }
<?PHP // THIS FILE IS DEPRECATED! PLEASE DO NOT MAKE CHANGES TO IT! // IT IS USED ONLY FOR UPGRADES FROM BEFORE MOODLE 1.7, ALL // LATER CHANGES SHOULD USE upgrade.php IN THIS DIRECTORY. function wiki_upgrade($oldversion) { This function does anything necessary to upgrade older versions to match current functionality global $CFG, $db; if ($oldversion < 2004040200) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` DROP `allowstudentstowiki`'); } if ($oldversion < 2004040700) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` CHANGE `ewikiallowsafehtml` `htmlmode` TINYINT( 4 ) DEFAULT \'0\' NOT NULL'); } if ($oldversion < 2004042100) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `pagename` VARCHAR( 255 ) AFTER `summary`'); execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_entries` CHANGE `name` `pagename` VARCHAR( 255 ) NOT NULL'); if ($wikis = get_records('wiki')) { foreach ($wikis as $wiki) { if (empty($wiki->pagename)) { set_field('wiki', 'pagename', $wiki->name, 'id', $wiki->id); } } } } if ($oldversion < 2004053100) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` CHANGE `initialcontent` `initialcontent` VARCHAR( 255 ) NOT NULL DEFAULT \'\''); // Remove obsolete 'initialcontent' values. if ($wikis = get_records('wiki')) { foreach ($wikis as $wiki) { if (!empty($wiki->initialcontent)) { set_field('wiki', 'initialcontent', null, 'id', $wiki->id); } } } } if ($oldversion < 2004061300) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki`' .' ADD `setpageflags` TINYINT DEFAULT \'1\' NOT NULL AFTER `ewikiacceptbinary`,' .' ADD `strippages` TINYINT DEFAULT \'1\' NOT NULL AFTER `setpageflags`,' .' ADD `removepages` TINYINT DEFAULT \'1\' NOT NULL AFTER `strippages`,' .' ADD `revertchanges` TINYINT DEFAULT \'1\' NOT NULL AFTER `removepages`'); } if ($oldversion < 2004062400) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki`' .' ADD `disablecamelcase` TINYINT DEFAULT \'0\' NOT NULL AFTER `ewikiacceptbinary`'); } if ($oldversion < 2004082200) { table_column('wiki_pages', '', 'userid', "integer", "10", "unsigned", "0", "not null", "author"); } if ($oldversion < 2004082303) { // Try to update userid for old records if ($pages = get_records('wiki_pages', 'userid', 0, 'pagename', 'lastmodified,author,pagename,version')) { foreach ($pages as $page) { $name = explode('(', $page->author); $name = trim($name[0]); $name = explode(' ', $name); $firstname = $name[0]; unset($name[0]); $lastname = trim(implode(' ', $name)); if ($user = get_record('user', 'firstname', $firstname, 'lastname', $lastname)) { set_field('wiki_pages', 'userid', $user->id, 'pagename', addslashes($page->pagename), 'version', $page->version); } } } } if ($oldversion < 2004111200) { execute_sql("ALTER TABLE {$CFG->prefix}wiki DROP INDEX course;",false); execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX course;",false); execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX userid;",false); execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX groupid;",false); execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX wikiid;",false); execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX pagename;",false); modify_database('','ALTER TABLE prefix_wiki ADD INDEX course (course);'); modify_database('','ALTER TABLE prefix_wiki_entries ADD INDEX course (course);'); modify_database('','ALTER TABLE prefix_wiki_entries ADD INDEX userid (userid);'); modify_database('','ALTER TABLE prefix_wiki_entries ADD INDEX groupid (groupid);'); modify_database('','ALTER TABLE prefix_wiki_entries ADD INDEX wikiid (wikiid);'); modify_database('','ALTER TABLE prefix_wiki_entries ADD INDEX pagename (pagename);'); } if ($oldversion < 2005022000) { // recreating the wiki_pages table completelly (missing id, bug 2608) if ($rows = count_records("wiki_pages")) { // we need to use the temp stuff modify_database("","CREATE TABLE `<API key>` ( `pagename` VARCHAR(160) NOT NULL, `version` INT(10) UNSIGNED NOT NULL DEFAULT 0, `flags` INT(10) UNSIGNED DEFAULT 0, `content` MEDIUMTEXT, `author` VARCHAR(100) DEFAULT 'ewiki', `userid` INT(10) UNSIGNED NOT NULL DEFAULT 0, `created` INT(10) UNSIGNED DEFAULT 0, `lastmodified` INT(10) UNSIGNED DEFAULT 0, `refs` MEDIUMTEXT, `meta` MEDIUMTEXT, `hits` INT(10) UNSIGNED DEFAULT 0, `wiki` INT(10) UNSIGNED NOT NULL);"); execute_sql("INSERT INTO {$CFG->prefix}wiki_pages_tmp (pagename, version, flags, content, author, userid, created, lastmodified, refs, meta, hits, wiki) SELECT pagename, version, flags, content, author, userid, created, lastmodified, refs, meta, hits, wiki FROM {$CFG->prefix}wiki_pages"); $insertafter = true; } execute_sql("DROP TABLE {$CFG->prefix}wiki_pages"); modify_database("","CREATE TABLE `prefix_wiki_pages` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `pagename` VARCHAR(160) NOT NULL, `version` INT(10) UNSIGNED NOT NULL DEFAULT 0, `flags` INT(10) UNSIGNED DEFAULT 0, `content` MEDIUMTEXT, `author` VARCHAR(100) DEFAULT 'ewiki', `userid` INT(10) UNSIGNED NOT NULL DEFAULT 0, `created` INT(10) UNSIGNED DEFAULT 0, `lastmodified` INT(10) UNSIGNED DEFAULT 0, `refs` MEDIUMTEXT, `meta` MEDIUMTEXT, `hits` INT(10) UNSIGNED DEFAULT 0, `wiki` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `wiki_pages_uk` (`pagename`,`version`,`wiki`)) TYPE=MyISAM COMMENT='Holds the Wiki-Pages';"); if (!empty($insertafter)) { execute_sql("INSERT INTO {$CFG->prefix}wiki_pages (pagename, version, flags, content, author, userid, created, lastmodified, refs, meta, hits, wiki) SELECT pagename, version, flags, content, author, userid, created, lastmodified, refs, meta, hits, wiki FROM {$CFG->prefix}wiki_pages_tmp"); execute_sql("DROP TABLE {$CFG->prefix}wiki_pages_tmp"); } } if ($oldversion < 2006042800) { execute_sql("UPDATE {$CFG->prefix}wiki SET summary='' WHERE summary IS NULL"); table_column('wiki','summary','summary','text','','','','not null'); execute_sql("UPDATE {$CFG->prefix}wiki SET pagename='' WHERE pagename IS NULL"); table_column('wiki','pagename','pagename','varchar','255','','','not null'); execute_sql("UPDATE {$CFG->prefix}wiki SET initialcontent='' WHERE initialcontent IS NULL"); table_column('wiki','initialcontent','initialcontent','varchar','255','','','not null'); } if ($oldversion < 2006092502) { modify_database(""," CREATE TABLE prefix_wiki_locks ( id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, wikiid INT(10) UNSIGNED NOT NULL, pagename VARCHAR(160) NOT NULL DEFAULT '', lockedby INT(10) NOT NULL DEFAULT 0, lockedsince INT(10) NOT NULL DEFAULT 0, lockedseen INT(10) NOT NULL DEFAULT 0, PRIMARY KEY(id), UNIQUE INDEX wiki_locks_uk(wikiid,pagename), INDEX wiki_locks_ix(lockedseen) );"); } /// DO NOT ADD NEW THINGS HERE!! USE upgrade.php and the lib/ddllib.php functions. return true; } ?>
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <title>com.qualcomm.robotcore.util</title> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.qualcomm.robotcore.util"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/qualcomm/robotcore/hardware/package-summary.html">Prev Package</a></li> <li><a href="../../../../org/firstinspires/ftc/robotcore/external/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/qualcomm/robotcore/util/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h1 title="Package" class="title">Package&nbsp;com.qualcomm.robotcore.util</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html" title="class in com.qualcomm.robotcore.util">ElapsedTime</a></td> <td class="colLast"> <div class="block">The <a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html" title="class in com.qualcomm.robotcore.util"><code>ElapsedTime</code></a> class provides a simple handy timer to measure elapsed time intervals.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../com/qualcomm/robotcore/util/Range.html" title="class in com.qualcomm.robotcore.util">Range</a></td> <td class="colLast"> <div class="block">Utility class for performing range operations</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../com/qualcomm/robotcore/util/SerialNumber.html" title="class in com.qualcomm.robotcore.util">SerialNumber</a></td> <td class="colLast"> <div class="block">Instances of <a href="../../../../com/qualcomm/robotcore/util/SerialNumber.html" title="class in com.qualcomm.robotcore.util"><code>SerialNumber</code></a> represent serial numbers of devices on the USB bus.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../com/qualcomm/robotcore/util/TypeConversion.html" title="class in com.qualcomm.robotcore.util">TypeConversion</a></td> <td class="colLast"> <div class="block">Utility class for performing type conversions</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation"> <caption><span>Enum Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Enum</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.Resolution.html" title="enum in com.qualcomm.robotcore.util">ElapsedTime.Resolution</a></td> <td class="colLast"> <div class="block">An indicator of the resolution of a timer.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/qualcomm/robotcore/hardware/package-summary.html">Prev Package</a></li> <li><a href="../../../../org/firstinspires/ftc/robotcore/external/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/qualcomm/robotcore/util/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
/* aes256_dec.c */ #include "aes.h" #include "aes_dec.h" void aes256_dec(void* buffer, aes256_ctx_t* ctx){ aes_decrypt_core(buffer, (aes_genctx_t*)ctx, 14); }
<p><b><img alt="" src="<?php echo $CFG->wwwroot; ?>/mod/turnitintool/icon.gif" />&nbsp;Turnitin Uppgifter&nbsp;-&nbsp;Uppgiftsdelar</b></p> <p>Bestämmer huruvida delarna av denna uppgift är namngivna delar eller om den här uppgiften är en portfoliouppgift.</p>
<?php /** * <API key> */ require_once 'Zend/Http/UserAgent/Features/Adapter.php'; class <API key> implements <API key> { /** * Get features from request * * @param array $request $_SERVER variable * @return array */ public static function getFromRequest($request, array $config) { if (!class_exists('Mobi_Mtld_DA_Api')) { if (!isset($config['deviceatlas'])) { require_once 'Zend/Http/UserAgent/Features/Exception.php'; throw new <API key>('"DeviceAtlas" configuration is not defined'); } } $config = $config['deviceatlas']; if (!class_exists('Mobi_Mtld_DA_Api')) { if (empty($config['deviceatlas_lib_dir'])) { require_once 'Zend/Http/UserAgent/Features/Exception.php'; throw new <API key>('The "deviceatlas_lib_dir" parameter is not defined'); } // Include the Device Atlas file from the specified lib_dir require_once ($config['deviceatlas_lib_dir'] . '/Mobi/Mtld/DA/Api.php'); } if (empty($config['deviceatlas_data'])) { require_once 'Zend/Http/UserAgent/Features/Exception.php'; throw new <API key>('The "deviceatlas_data" parameter is not defined'); } //load the device data-tree : e.g. 'json/DeviceAtlas.json $tree = Mobi_Mtld_DA_Api::getTreeFromFile($config['deviceatlas_data']); $properties = Mobi_Mtld_DA_Api::getProperties($tree, $request['http_user_agent']); return $properties; } }
module RGen module MetamodelBuilder module DataTypes # An enum object is used to describe possible attribute values within a # MetamodelBuilder attribute definition. An attribute defined this way can only # take the values specified when creating the Enum object. # Literal values can only be symbols or true or false. # Optionally a name may be specified for the enum object. # Examples: # Enum.new(:name => "AnimalEnum", :literals => [:cat, :dog]) # Enum.new(:literals => [:cat, :dog]) # Enum.new([:cat, :dog]) class Enum attr_reader :name, :literals # Creates a new named enum type object consisting of the elements passed as arguments. def initialize(params) MetamodelBuilder::ConstantOrderHelper.enumCreated(self) if params.is_a?(Array) @literals = params @name = "anonymous" elsif params.is_a?(Hash) raise StandardError.new("Hash entry :literals is missing") unless params[:literals] @literals = params[:literals] @name = params[:name] || "anonymous" else raise StandardError.new("Pass an Array or a Hash") end end # This method can be used to check if an object can be used as value for # variables having this enum object as type. def validLiteral?(l) literals.include?(l) end def literals_as_strings literals.collect do |l| if l.is_a?(Symbol) if l.to_s =~ /^\d|\W/ ":'"+l.to_s+"'" else ":"+l.to_s end elsif l.is_a?(TrueClass) || l.is_a?(FalseClass) l.to_s else raise StandardError.new("Literal values can only be symbols or true/false") end end end def to_s # :nodoc: name end end # Boolean is a predefined enum object having Ruby's true and false singletons # as possible values. Boolean = Enum.new(:name => "Boolean", :literals => [true, false]) # Long represents a 64-bit Integer # This constant is merely a marker for keeping this information in the Ruby version of the metamodel, # values of this type will always be instances of Integer or Bignum; # Setting it to a string value ensures that it responds to "to_s" which is used in the metamodel generator Long = "Long" end end end
package com.puppycrawl.tools.checkstyle.checks.whitespace.emptylineseparator; public class <API key> { }
package route53 import ( "net/url" "regexp" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol/restxml" ) func init() { initClient = func(c *client.Client) { c.Handlers.Build.PushBack(sanitizeURL) } initRequest = func(r *request.Request) { switch r.Operation.Name { case <API key>: r.Handlers.UnmarshalError.Remove(restxml.<API key>) r.Handlers.UnmarshalError.PushBack(<API key>) } } } var reSanitizeURL = regexp.MustCompile(`\/%2F\w+%2F`) func sanitizeURL(r *request.Request) { r.HTTPRequest.URL.RawPath = reSanitizeURL.ReplaceAllString(r.HTTPRequest.URL.RawPath, "/") // Update Path so that it reflects the cleaned RawPath updated, err := url.Parse(r.HTTPRequest.URL.RawPath) if err != nil { r.Error = awserr.New(request.<API key>, "failed to clean Route53 URL", err) return } // Take the updated path so the requests's URL Path has parity with RawPath. r.HTTPRequest.URL.Path = updated.Path }
// of patent rights can be found in the PATENTS file in the same directory. #pragma once #include <map> #include <queue> #include <string> #include <thread> #include "port/port.h" #include "rocksdb/status.h" namespace rocksdb { class Env; class Logger; class SstFileManagerImpl; // DeleteScheduler allows the DB to enforce a rate limit on file deletion, // Instead of deleteing files immediately, files are moved to trash_dir // and deleted in a background thread that apply sleep penlty between deletes // if they are happening in a rate faster than rate_bytes_per_sec, // Rate limiting can be turned off by setting rate_bytes_per_sec = 0, In this // case DeleteScheduler will delete files immediately. class DeleteScheduler { public: DeleteScheduler(Env* env, const std::string& trash_dir, int64_t rate_bytes_per_sec, Logger* info_log, SstFileManagerImpl* sst_file_manager); ~DeleteScheduler(); // Return delete rate limit in bytes per second int64_t <API key>() { return rate_bytes_per_sec_; } // Move file to trash directory and schedule it's deletion Status DeleteFile(const std::string& fname); // Wait for all files being deleteing in the background to finish or for // destructor to be called. void WaitForEmptyTrash(); // Return a map containing errors that happened in <API key> // file_path => error status std::map<std::string, Status> GetBackgroundErrors(); private: Status MoveToTrash(const std::string& file_path, std::string* path_in_trash); Status DeleteTrashFile(const std::string& path_in_trash, uint64_t* deleted_bytes); void <API key>(); Env* env_; // Path to the trash directory std::string trash_dir_; // Maximum number of bytes that should be deleted per second int64_t rate_bytes_per_sec_; // Mutex to protect queue_, pending_files_, bg_errors_, closing_ port::Mutex mu_; // Queue of files in trash that need to be deleted std::queue<std::string> queue_; // Number of files in trash that are waiting to be deleted int32_t pending_files_; // Errors that happened in <API key> (file_path => error) std::map<std::string, Status> bg_errors_; // Set to true in ~DeleteScheduler() to force <API key> to stop bool closing_; // Condition variable signaled in these conditions // - pending_files_ value change from 0 => 1 // - pending_files_ value change from 1 => 0 // - closing_ value is set to true port::CondVar cv_; // Background thread running <API key> std::unique_ptr<std::thread> bg_thread_; // Mutex to protect threads from file name conflicts port::Mutex file_move_mu_; Logger* info_log_; SstFileManagerImpl* sst_file_manager_; static const uint64_t kMicrosInSecond = 1000 * 1000LL; }; } // namespace rocksdb
package com.thinkaurelius.titan.hadoop.compat.h1; import com.thinkaurelius.titan.graphdb.configuration.TitanConstants; import com.thinkaurelius.titan.hadoop.config.job.<API key>; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.<API key>; import org.apache.hadoop.mrunit.mapreduce.MapReduceDriver; import com.thinkaurelius.titan.hadoop.HadoopGraph; import com.thinkaurelius.titan.hadoop.compat.HadoopCompat; import com.thinkaurelius.titan.hadoop.compat.HadoopCompiler; public class Hadoop1Compat implements HadoopCompat { static final String <API key> = "mapred.map.tasks.speculative.execution"; static final String <API key> = "mapred.reduce.tasks.speculative.execution"; static final String CFG_JOB_JAR = "mapred.jar"; @Override public HadoopCompiler newCompiler(HadoopGraph g) { return new Hadoop1Compiler(g); } @Override public TaskAttemptContext newTask(Configuration c, TaskAttemptID t) { return new TaskAttemptContext(c, t); } @Override public String <API key>() { return <API key>; } @Override public String <API key>() { return <API key>; } @Override public String <API key>() { return CFG_JOB_JAR; } @Override public void <API key>(<API key> context, Enum<?> counter, long incr) { context.getCounter(counter).increment(incr); } @Override public Configuration <API key>(TaskAttemptContext context) { return context.getConfiguration(); } @Override public long getCounter(MapReduceDriver counters, Enum<?> e) { return counters.getCounters().findCounter(e).getValue(); } @Override public <API key> <API key>(String mapredJarPath) { return new MapredJarConfigurer(mapredJarPath); } @Override public <API key> <API key>() { return new DistCacheConfigurer("titan-hadoop-core-" + TitanConstants.VERSION + ".jar"); } @Override public Configuration <API key>(JobContext context) { return context.getConfiguration(); } @Override public Configuration <API key>(Configuration base) { return new <API key>(base); } }
const path = require('path'); const fs = require('fs'); const EventEmitter = require('events').EventEmitter; const Shard = require('./Shard'); const Collection = require('../util/Collection'); const Util = require('../util/Util'); /** * This is a utility class that can be used to help you spawn shards of your client. Each shard is completely separate * from the other. The Shard Manager takes a path to a file and spawns it under the specified amount of shards safely. * If you do not select an amount of shards, the manager will automatically decide the best amount. * @extends {EventEmitter} */ class ShardingManager extends EventEmitter { /** * @param {string} file Path to your shard script file * @param {Object} [options] Options for the sharding manager * @param {number|string} [options.totalShards='auto'] Number of shards to spawn, or "auto" * @param {boolean} [options.respawn=true] Whether shards should automatically respawn upon exiting * @param {string[]} [options.shardArgs=[]] Arguments to pass to the shard script when spawning * @param {string} [options.token] Token to use for automatic shard count and passing to shards */ constructor(file, options = {}) { super(); options = Util.mergeDefault({ totalShards: 'auto', respawn: true, shardArgs: [], token: null, }, options); /** * Path to the shard script file * @type {string} */ this.file = file; if (!file) throw new Error('File must be specified.'); if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file); const stats = fs.statSync(this.file); if (!stats.isFile()) throw new Error('File path does not point to a file.'); /** * Amount of shards that this manager is going to spawn * @type {number|string} */ this.totalShards = options.totalShards; if (this.totalShards !== 'auto') { if (typeof this.totalShards !== 'number' || isNaN(this.totalShards)) { throw new TypeError('Amount of shards must be a number.'); } if (this.totalShards < 1) throw new RangeError('Amount of shards must be at least 1.'); if (this.totalShards !== Math.floor(this.totalShards)) { throw new RangeError('Amount of shards must be an integer.'); } } /** * Whether shards should automatically respawn upon exiting * @type {boolean} */ this.respawn = options.respawn; /** * An array of arguments to pass to shards * @type {string[]} */ this.shardArgs = options.shardArgs; /** * Token to use for obtaining the automatic shard count, and passing to shards * @type {?string} */ this.token = options.token ? options.token.replace(/^Bot\s*/i, '') : null; /** * A collection of shards that this manager has spawned * @type {Collection<number, Shard>} */ this.shards = new Collection(); } /** * Spawns a single shard. * @param {number} id The ID of the shard to spawn. **This is usually not necessary** * @returns {Promise<Shard>} */ createShard(id = this.shards.size) { const shard = new Shard(this, id, this.shardArgs); this.shards.set(id, shard); /** * Emitted upon launching a shard. * @event ShardingManager#launch * @param {Shard} shard Shard that was launched */ this.emit('launch', shard); return Promise.resolve(shard); } /** * Spawns multiple shards. * @param {number} [amount=this.totalShards] Number of shards to spawn * @param {number} [delay=7500] How long to wait in between spawning each shard (in milliseconds) * @returns {Promise<Collection<number, Shard>>} */ spawn(amount = this.totalShards, delay = 7500) { if (amount === 'auto') { return Util.<API key>(this.token).then(count => { this.totalShards = count; return this._spawn(count, delay); }); } else { if (typeof amount !== 'number' || isNaN(amount)) throw new TypeError('Amount of shards must be a number.'); if (amount < 1) throw new RangeError('Amount of shards must be at least 1.'); if (amount !== Math.floor(amount)) throw new TypeError('Amount of shards must be an integer.'); return this._spawn(amount, delay); } } /** * Actually spawns shards, unlike that poser above >:( * @param {number} amount Number of shards to spawn * @param {number} delay How long to wait in between spawning each shard (in milliseconds) * @returns {Promise<Collection<number, Shard>>} * @private */ _spawn(amount, delay) { return new Promise(resolve => { if (this.shards.size >= amount) throw new Error(`Already spawned ${this.shards.size} shards.`); this.totalShards = amount; this.createShard(); if (this.shards.size >= this.totalShards) { resolve(this.shards); return; } if (delay <= 0) { while (this.shards.size < this.totalShards) this.createShard(); resolve(this.shards); } else { const interval = setInterval(() => { this.createShard(); if (this.shards.size >= this.totalShards) { clearInterval(interval); resolve(this.shards); } }, delay); } }); } /** * Send a message to all shards. * @param {*} message Message to be sent to the shards * @returns {Promise<Shard[]>} */ broadcast(message) { const promises = []; for (const shard of this.shards.values()) promises.push(shard.send(message)); return Promise.all(promises); } /** * Evaluates a script on all shards, in the context of the Clients. * @param {string} script JavaScript to run on each shard * @returns {Promise<Array>} Results of the script execution */ broadcastEval(script) { const promises = []; for (const shard of this.shards.values()) promises.push(shard.eval(script)); return Promise.all(promises); } /** * Fetches a client property value of each shard. * @param {string} prop Name of the client property to get, using periods for nesting * @returns {Promise<Array>} * @example * manager.fetchClientValues('guilds.size') * .then(results => { * console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`); * }) * .catch(console.error); */ fetchClientValues(prop) { if (this.shards.size === 0) return Promise.reject(new Error('No shards have been spawned.')); if (this.shards.size !== this.totalShards) return Promise.reject(new Error('Still spawning shards.')); const promises = []; for (const shard of this.shards.values()) promises.push(shard.fetchClientValue(prop)); return Promise.all(promises); } } module.exports = ShardingManager;
using System; using System.Collections.Generic; using System.Threading.Tasks; using Elasticsearch.Net; namespace Nest { public partial class ElasticClient { <inheritdoc /> public ISearchResponse<T> MoreLikeThis<T>(Func<<API key><T>, <API key><T>> mltSelector) where T : class { return this.Dispatcher.Dispatch<<API key><T>, <API key>, SearchResponse<T>>( mltSelector, (p, d) => { <API key> r = d; <API key>(d); return this.RawDispatch.MltDispatch<SearchResponse<T>>(p, r.Search); } ); } <inheritdoc /> public ISearchResponse<T> MoreLikeThis<T>(<API key> moreLikeThisRequest) where T : class { return this.Dispatcher.Dispatch<<API key>, <API key>, SearchResponse<T>>( moreLikeThisRequest, (p, d) => { <API key>(d); return this.RawDispatch.MltDispatch<SearchResponse<T>>(p, d.Search); } ); } <inheritdoc /> public Task<ISearchResponse<T>> MoreLikeThisAsync<T>(Func<<API key><T>, <API key><T>> mltSelector) where T : class { return this.Dispatcher.DispatchAsync<<API key><T>, <API key>, SearchResponse<T>, ISearchResponse<T>>( mltSelector, (p, d) => { <API key> r = d; <API key>(d); return this.RawDispatch.MltDispatchAsync<SearchResponse<T>>(p, r.Search); } ); } <inheritdoc /> public Task<ISearchResponse<T>> MoreLikeThisAsync<T>(<API key> moreLikeThisRequest) where T : class { return this.Dispatcher.DispatchAsync<<API key>, <API key>, SearchResponse<T>, ISearchResponse<T>>( moreLikeThisRequest, (p, d) => { <API key>(d); return this.RawDispatch.MltDispatchAsync<SearchResponse<T>>(p, d.Search); } ); } private static void <API key>(<API key> request) { if (request.Search == null) return; request.RequestParameters.<API key>(request.Search.QueryString); } } }
package featureflag_test import ( "errors" fakeflag "github.com/cloudfoundry/cli/cf/api/feature_flags/fakes" "github.com/cloudfoundry/cli/cf/command_registry" "github.com/cloudfoundry/cli/cf/configuration/core_config" testcmd "github.com/cloudfoundry/cli/testhelpers/commands" testconfig "github.com/cloudfoundry/cli/testhelpers/configuration" . "github.com/cloudfoundry/cli/testhelpers/matchers" testreq "github.com/cloudfoundry/cli/testhelpers/requirements" testterm "github.com/cloudfoundry/cli/testhelpers/terminal" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("enable-feature-flag command", func() { var ( ui *testterm.FakeUI requirementsFactory *testreq.FakeReqFactory configRepo core_config.Repository flagRepo *fakeflag.<API key> deps command_registry.Dependency ) <API key> := func(pluginCall bool) { deps.Ui = ui deps.RepoLocator = deps.RepoLocator.<API key>(flagRepo) deps.Config = configRepo command_registry.Commands.SetCommand(command_registry.Commands.FindCommand("enable-feature-flag").SetDependency(deps, pluginCall)) } BeforeEach(func() { ui = &testterm.FakeUI{} configRepo = testconfig.<API key>() requirementsFactory = &testreq.FakeReqFactory{LoginSuccess: true} flagRepo = &fakeflag.<API key>{} }) runCommand := func(args ...string) bool { return testcmd.RunCliCommand("enable-feature-flag", args, requirementsFactory, <API key>, false) } Describe("requirements", func() { It("requires the user to be logged in", func() { requirementsFactory.LoginSuccess = false Expect(runCommand()).ToNot(<API key>()) }) It("fails with usage if a single feature is not specified", func() { runCommand() Expect(ui.Outputs).To(ContainSubstrings( []string{"Incorrect Usage", "Requires an argument"}, )) }) }) Describe("when logged in", func() { BeforeEach(func() { flagRepo.UpdateReturns(nil) }) It("Sets the flag", func() { runCommand("user_org_creation") flag, set := flagRepo.UpdateArgsForCall(0) Expect(flag).To(Equal("user_org_creation")) Expect(set).To(BeTrue()) Expect(ui.Outputs).To(ContainSubstrings( []string{"Setting status of user_org_creation as my-user..."}, []string{"OK"}, []string{"Feature user_org_creation Enabled."}, )) }) Context("when an error occurs", func() { BeforeEach(func() { flagRepo.UpdateReturns(errors.New("An error occurred.")) }) It("fails with an error", func() { runCommand("i-dont-exist") Expect(ui.Outputs).To(ContainSubstrings( []string{"FAILED"}, []string{"An error occurred."}, )) }) }) }) })
package org.csstudio.swt.xygraph.util; import org.csstudio.swt.xygraph.figures.XYGraph; import org.eclipse.draw2d.FigureUtilities; import org.eclipse.draw2d.SWTGraphics; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Transform; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; public class <API key> extends SingleSourceHelper { @Override protected Cursor <API key>(Display display, ImageData imageData, int width, int height, int style) { return new Cursor(display, imageData, width, height); } @Override protected Image <API key>(String text, Font font, RGB color, boolean upToDown) { final Dimension titleSize = FigureUtilities.getTextExtents(text, font); final int w = titleSize.height; final int h = titleSize.width + 1; Image image = new Image(Display.getCurrent(), w, h); final GC gc = new GC(image); final Color titleColor = new Color(Display.getCurrent(), color); RGB transparentRGB = new RGB(240, 240, 240); gc.setBackground(XYGraphMediaFactory.getInstance().getColor( transparentRGB)); gc.fillRectangle(image.getBounds()); gc.setForeground(titleColor); gc.setFont(font); final Transform tr = new Transform(Display.getCurrent()); if (!upToDown) { tr.translate(0, h); tr.rotate(-90); gc.setTransform(tr); } else { tr.translate(w, 0); tr.rotate(90); gc.setTransform(tr); } gc.drawText(text, 0, 0); tr.dispose(); gc.dispose(); final ImageData imageData = image.getImageData(); image.dispose(); titleColor.dispose(); imageData.transparentPixel = imageData.palette.getPixel(transparentRGB); image = new Image(Display.getCurrent(), imageData); return image; } @Override protected Image <API key>(XYGraph xyGraph) { Rectangle bounds = xyGraph.getBounds(); Image image = new Image(null, bounds.width + 6, bounds.height + 6); GC gc = new GC(image); SWTGraphics graphics = new SWTGraphics(gc); graphics.translate(-bounds.x + 3, -bounds.y + 3); graphics.setForegroundColor(xyGraph.getForegroundColor()); graphics.setBackgroundColor(xyGraph.getBackgroundColor()); xyGraph.paint(graphics); gc.dispose(); return image; } @Override protected String <API key>() { FileDialog dialog = new FileDialog(Display.getDefault().getShells()[0], SWT.SAVE); dialog.setFilterNames(new String[] { "PNG Files", "All Files (*.*)" }); dialog.setFilterExtensions(new String[] { "*.png", "*.*" }); // Windows String path = dialog.open(); return path; } }
# Using AOT compilation ## What is tfcompile? `tfcompile` is a standalone tool that ahead-of-time (AOT) compiles TensorFlow graphs into executable code. It can reduce total binary size, and also avoid some runtime overheads. A typical use-case of `tfcompile` is to compile an inference graph into executable code for mobile devices. The TensorFlow graph is normally executed by the TensorFlow runtime. This incurs some runtime overhead for execution of each node in the graph. This also leads to a larger total binary size, since the code for the TensorFlow runtime needs to be available, in addition to the graph itself. The executable code produced by `tfcompile` does not use the TensorFlow runtime, and only has dependencies on kernels that are actually used in the computation. The compiler is built on top of the XLA framework. The code bridging TensorFlow to the XLA framework resides under [tensorflow/compiler](https: which also includes support for [just-in-time (JIT) compilation](jit.md) of TensorFlow graphs. ## What does tfcompile do? `tfcompile` takes a subgraph, identified by the TensorFlow concepts of feeds and fetches, and generates a function that implements that subgraph. The `feeds` are the input arguments for the function, and the `fetches` are the output arguments for the function. All inputs must be fully specified by the feeds; the resulting pruned subgraph cannot contain Placeholder or Variable nodes. It is common to specify all Placeholders and Variables as feeds, which ensures the resulting subgraph no longer contains these nodes. The generated function is packaged as a `cc_library`, with a header file exporting the function signature, and an object file containing the implementation. The user writes code to invoke the generated function as appropriate. ## Using tfcompile This section details high level steps for generating an executable binary with `tfcompile` from a TensorFlow subgraph. The steps are: * Step 1: Configure the subgraph to compile * Step 2: Use the `tf_library` build macro to compile the subgraph * Step 3: Write code to invoke the subgraph * Step 4: Create the final binary Step 1: Configure the subgraph to compile Identify the feeds and fetches that correspond to the input and output arguments for the generated function. Then configure the `feeds` and `fetches` in a [`tensorflow.tf2xla.Config`](https: proto. textproto # Each feed is a positional input argument for the generated function. The order # refer to the names of placeholder nodes defined in the graph. feed { id { node_name: "x_hold" } shape { dim { size: 2 } dim { size: 3 } } } feed { id { node_name: "y_hold" } shape { dim { size: 3 } dim { size: 2 } } } # Each fetch is a positional output argument for the generated function. The order # refers to the name of a matmul node defined in the graph. fetch { id { node_name: "x_y_prod" } } Step 2: Use tf_library build macro to compile the subgraph This step converts the graph into a `cc_library` using the `tf_library` build macro. The `cc_library` consists of an object file containing the code generated from the graph, along with a header file that gives access to the generated code. `tf_library` utilizes `tfcompile` to compile the TensorFlow graph into executable code. build load("//tensorflow/compiler/aot:tfcompile.bzl", "tf_library") # Use the tf_library macro to compile your graph into executable code. tf_library( # name is used to generate the following underlying build rules: # <name> : cc_library packaging the generated header and object files # <name>_test : cc_test containing a simple test and benchmark # <name>_benchmark : cc_binary containing a stand-alone benchmark with minimal deps; # can be run on a mobile device name = "test_graph_tfmatmul", # cpp_class specifies the name of the generated C++ class, with namespaces allowed. # The class will be generated in the given namespace(s), or if no namespaces are # given, within the global namespace. cpp_class = "foo::bar::MatMulComp", # graph is the input GraphDef proto, by default expected in binary format. To # created from this input graph, with feeds as inputs and fetches as outputs. # No Placeholder or Variable ops may exist in this subgraph. graph = "test_graph_tfmatmul.pb", # config is the input Config proto, by default expected in binary format. To # feeds and fetches were specified above, in the previous step. config = "test_graph_tfmatmul.config.pbtxt", ) > To generate the GraphDef proto (test_graph_tfmatmul.pb) for this example, run > [make_test_graphs.py](https: > and specify the output location with the --out_dir flag. Typical graphs contain [`Variables`](https: representing the weights that are learned via training, but `tfcompile` cannot compile a subgraph that contain `Variables`. The [freeze_graph.py](https: tool converts variables into constants, using values stored in a checkpoint file. As a convenience, the `tf_library` macro supports the `freeze_checkpoint` argument, which runs the tool. For more examples see [tensorflow/compiler/aot/tests/BUILD](https: > Constants that show up in the compiled subgraph are compiled directly into the > generated code. To pass the constants into the generated function, rather than > having them compiled-in, simply pass them in as feeds. For details on the `tf_library` build macro, see [tfcompile.bzl](https: For details on the underlying `tfcompile` tool, see [tfcompile_main.cc](https: Step 3: Write code to invoke the subgraph This step uses the header file (`test_graph_tfmatmul.h`) generated by the `tf_library` build macro in the previous step to invoke the generated code. The header file is located in the `bazel-genfiles` directory corresponding to the build package, and is named based on the name attribute set on the `tf_library` build macro. For example, the header generated for `test_graph_tfmatmul` would be `test_graph_tfmatmul.h`. Below is an abbreviated version of what is generated. The generated file, in `bazel-genfiles`, contains additional useful comments. c++ namespace foo { namespace bar { // MatMulComp represents a computation previously specified in a // TensorFlow graph, now compiled into executable code. class MatMulComp { public: // AllocMode controls the buffer allocation mode. enum class AllocMode { <API key>, // Allocate arg, result and temp buffers <API key>, // Only allocate result and temp buffers }; MatMulComp(AllocMode mode = AllocMode::<API key>); ~MatMulComp(); // Runs the computation, with inputs read from arg buffers, and outputs // written to result buffers. Returns true on success and false on failure. bool Run(); // Arg methods for managing input buffers. Buffers are in row-major order. // There is a set of methods for each positional argument. void** args(); void set_arg0_data(float* data); float* arg0_data(); float& arg0(size_t dim0, size_t dim1); void set_arg1_data(float* data); float* arg1_data(); float& arg1(size_t dim0, size_t dim1); // Result methods for managing output buffers. Buffers are in row-major order. // Must only be called after a successful Run call. There is a set of methods // for each positional result. void** results(); float* result0_data(); float& result0(size_t dim0, size_t dim1); }; } // end namespace bar } // end namespace foo The generated C++ class is called `MatMulComp` in the `foo::bar` namespace, because that was the `cpp_class` specified in the `tf_library` macro. All generated classes have a similar API, with the only difference being the methods to handle arg and result buffers. Those methods differ based on the number and types of the buffers, which were specified by the `feed` and `fetch` arguments to the `tf_library` macro. There are three types of buffers managed within the generated class: `args` representing the inputs, `results` representing the outputs, and `temps` representing temporary buffers used internally to perform the computation. By default, each instance of the generated class allocates and manages all of these buffers for you. The `AllocMode` constructor argument may be used to change this behavior. All buffers are aligned to 64-byte boundaries. The generated C++ class is just a wrapper around the low-level code generated by XLA. Example of invoking the generated function based on [`tfcompile_test.cc`](https: c++ #define EIGEN_USE_THREADS #define <API key> #include <iostream> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/compiler/aot/tests/test_graph_tfmatmul.h" // generated int main(int argc, char** argv) { Eigen::ThreadPool tp(2); // Size the thread pool as appropriate. Eigen::ThreadPoolDevice device(&tp, tp.NumThreads()); foo::bar::MatMulComp matmul; matmul.set_thread_pool(&device); // Set up args and run the computation. const float args[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::copy(args + 0, args + 6, matmul.arg0_data()); std::copy(args + 6, args + 12, matmul.arg1_data()); matmul.Run(); // Check result if (matmul.result0(0, 0) == 58) { std::cout << "Success" << std::endl; } else { std::cout << "Failed. Expected value 58 at 0,0. Got:" << matmul.result0(0, 0) << std::endl; } return 0; } Step 4: Create the final binary This step combines the library generated by `tf_library` in step 2 and the code written in step 3 to create a final binary. Below is an example `bazel` BUILD file. build # Example of linking your binary # Also see //tensorflow/compiler/aot/tests/BUILD load("//tensorflow/compiler/aot:tfcompile.bzl", "tf_library") # The same tf_library call from step 2 above. tf_library( name = "test_graph_tfmatmul", ) # The executable code generated by tf_library can then be linked into your code. cc_binary( name = "my_binary", srcs = [ "my_code.cc", # include test_graph_tfmatmul.h to access the generated header ], deps = [ ":test_graph_tfmatmul", # link in the generated object file "//third_party/eigen3", ], linkopts = [ "-lpthread", ] )
<?php if (!defined('APPLICATION')) exit(); $Alt = FALSE; $Session = Gdn::Session(); $EditUser = $Session->CheckPermission('Garden.Users.Edit'); $DeleteUser = $Session->CheckPermission('Garden.Users.Delete'); foreach ($this->UserData->Result() as $User) { $Alt = $Alt ? FALSE : TRUE; ?> <tr id="<?php echo "UserID_{$User->UserID}"; ?>"<?php echo $Alt ? ' class="Alt"' : ''; ?>> <!-- <td class="CheckboxCell"><input type="checkbox" name="LogID[]" value="<?php echo $User->UserID; ?>" /></td>--> <td><strong><?php echo UserAnchor($User); ?></strong></td> <td class="Alt"><?php echo Gdn_Format::Email($User->Email); ?></td> <td style="max-width: 200px;"> <?php $Roles = GetValue('Roles', $User, array()); $RolesString = ''; if ($User->Banned && !in_array('Banned', $Roles)) { $RolesString = T('Banned'); } if ($User->Admin > 1) { $RolesString = ConcatSep(', ', $RolesString, T('System')); } foreach ($Roles as $RoleID => $RoleName) { $Query = http_build_query(array('Keywords' => $RoleName)); $RolesString = ConcatSep(', ', $RolesString, '<a href="'.Url('/user/browse?'.$Query).'">'.htmlspecialchars($RoleName).'</a>'); } echo $RolesString; ?> </td> <td class="Alt"><?php echo Gdn_Format::Date($User->DateFirstVisit, 'html'); ?></td> <td><?php echo Gdn_Format::Date($User->DateLastActive, 'html'); ?></td> <td><?php echo htmlspecialchars($User->LastIPAddress); ?></td> <?php $this->EventArgs['User'] = $User; $this->FireEvent('UserCell'); ?> <?php if ($EditUser || $DeleteUser) { ?> <td><?php if ($EditUser) echo Anchor(T('Edit'), '/user/edit/'.$User->UserID, 'Popup SmallButton'); if ($DeleteUser && $User->UserID != $Session->User->UserID) echo Anchor(T('Delete'), '/user/delete/'.$User->UserID, 'SmallButton'); $this->EventArguments['User'] = $User; $this->FireEvent('UserListOptions'); ?></td> <?php } ?> </tr> <?php }
Namespace Microsoft.CodeAnalysis.VisualBasic Friend Partial Module ErrorFacts Public Function IsWarning(code as ERRID) As Boolean Select Case code Case ERRID.WRN_BadSwitch, ERRID.<API key>, ERRID.<API key>, ERRID.WRN_BadUILang, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.WRN_OverrideType5, ERRID.WRN_MustOverride2, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.WRN_ObjectMath1, ERRID.WRN_ObjectMath2, ERRID.<API key>, ERRID.WRN_ObjectAssumed1, ERRID.<API key>, ERRID.WRN_UnusedLocal, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.WRN_DuplicateCatch, ERRID.WRN_ObjectMath1Not, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.WRN_MainIgnored, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.<API key>, ERRID.WRN_Experimental Return True Case Else Return False End Select End Function Public Function IsFatal(code as ERRID) As Boolean Select Case code Case ERRID.<API key> Return True Case Else Return False End Select End Function Public Function IsInfo(code as ERRID) As Boolean Select Case code Case ERRID.<API key> Return True Case Else Return False End Select End Function Public Function IsHidden(code as ERRID) As Boolean Select Case code Case ERRID.<API key>, ERRID.<API key> Return True Case Else Return False End Select End Function End Module End Namespace
<?php namespace yiiunit\extensions\authclient\oauth\signature; use yii\authclient\signature\RsaSha1; use yiiunit\extensions\authclient\TestCase; class RsaSha1Test extends TestCase { /** * Returns test public certificate string. * @return string public certificate string. */ protected function <API key>() { return ' <API key> <API key> <API key> <API key> <API key> <API key> <API key> <API key> <API key> <API key>+u <API key>+1ko4 <API key> <API key> <API key>/zANBgkqhkiG9w0B AQUFAAOBgQB1/<API key> <API key>/ <API key>/<API key>== --END CERTIFICATE } /** * Returns test private certificate string. * @return string private certificate string. */ protected function <API key>() { return ' <API key>+ud6rP <API key>+1ko4xAIP <API key> <API key>+hFxz2M97eTglqolw+/p4tHWo 2+ZORioKJ/V6//<API key> <API key> <API key>/WaJU0Ap/ <API key>+ifX8/<API key> m+<API key> UI5kQ4KX1yW/lSeVS+<API key>/0kxxQJAebRX AalKMSRo+QVg/F0Kpenoa+<API key> <API key> 8b+<API key>= --END RSA PRIVATE KEY } // Tests : public function <API key>() { $signatureMethod = new RsaSha1(); $signatureMethod-><API key>($this-><API key>()); $signatureMethod-><API key>($this-><API key>()); $baseString = 'test_base_string'; $key = 'test_key'; $signature = $signatureMethod->generateSignature($baseString, $key); $this->assertNotEmpty($signature, 'Unable to generate signature!'); } /** * @depends <API key> */ public function testVerify() { $signatureMethod = new RsaSha1(); $signatureMethod-><API key>($this-><API key>()); $signatureMethod-><API key>($this-><API key>()); $baseString = 'test_base_string'; $key = 'test_key'; $signature = 'unsigned'; $this->assertFalse($signatureMethod->verify($signature, $baseString, $key), 'Unsigned signature is valid!'); $generatedSignature = $signatureMethod->generateSignature($baseString, $key); $this->assertTrue($signatureMethod->verify($generatedSignature, $baseString, $key), 'Generated signature is invalid!'); } public function <API key>() { $signatureMethod = new RsaSha1(); $certificateFileName = __FILE__; $signatureMethod-><API key> = $certificateFileName; $this->assertEquals(file_get_contents($certificateFileName), $signatureMethod-><API key>(), 'Unable to fetch private certificate from file!'); } public function <API key>() { $signatureMethod = new RsaSha1(); $certificateFileName = __FILE__; $signatureMethod-><API key> = $certificateFileName; $this->assertEquals(file_get_contents($certificateFileName), $signatureMethod-><API key>(), 'Unable to fetch public certificate from file!'); } }
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime import itertools import os import re from importlib import import_module from django.apps import apps from django.conf import settings from django.contrib.admin.models import LogEntry from django.contrib.auth import REDIRECT_FIELD_NAME, SESSION_KEY from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, SetPasswordForm, ) from django.contrib.auth.models import User from django.contrib.auth.tests.custom_user import CustomUser from django.contrib.auth.views import login as login_view, redirect_to_login from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sites.requests import RequestSite from django.core import mail from django.core.urlresolvers import NoReverseMatch, reverse, reverse_lazy from django.db import connection from django.http import HttpRequest, QueryDict from django.middleware.csrf import CsrfViewMiddleware, get_token from django.test import ( TestCase, ignore_warnings, modify_settings, override_settings, ) from django.test.utils import patch_logger from django.utils.deprecation import <API key> from django.utils.encoding import force_text from django.utils.http import urlquote from django.utils.six.moves.urllib.parse import ParseResult, urlparse from django.utils.translation import <API key> from .models import UUIDUser from .settings import AUTH_TEMPLATES @override_settings( LANGUAGES=[ ('en', 'English'), ], LANGUAGE_CODE='en', TEMPLATES=AUTH_TEMPLATES, USE_TZ=False, PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF='auth_tests.urls', ) class AuthViewsTestCase(TestCase): """ Helper base class for all the follow test cases. """ @classmethod def setUpTestData(cls): cls.u1 = User.objects.create( password='sha1$6efc0$<SHA1-like>', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='testclient', first_name='Test', last_name='Client', email='testclient@example.com', is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) cls.u2 = User.objects.create( password='sha1$6efc0$<SHA1-like>', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='inactive', first_name='Inactive', last_name='User', email='testclient2@example.com', is_staff=False, is_active=False, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) cls.u3 = User.objects.create( password='sha1$6efc0$<SHA1-like>', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='staff', first_name='Staff', last_name='Member', email='staffmember@example.com', is_staff=True, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) cls.u4 = User.objects.create( password='', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='empty_password', first_name='Empty', last_name='Password', email='empty_password@example.com', is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) cls.u5 = User.objects.create( password='$', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='<API key>', first_name='Unmanageable', last_name='Password', email='<API key>@example.com', is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) cls.u6 = User.objects.create( password='foo$bar', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='unknown_password', first_name='Unknown', last_name='Password', email='unknown_password@example.com', is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) def login(self, username='testclient', password='password'): response = self.client.post('/login/', { 'username': username, 'password': password, }) self.assertIn(SESSION_KEY, self.client.session) return response def logout(self): response = self.client.get('/admin/logout/') self.assertEqual(response.status_code, 200) self.assertNotIn(SESSION_KEY, self.client.session) def assertFormError(self, response, error): """Assert that error is found in response.context['form'] errors""" form_errors = list(itertools.chain(*response.context['form'].errors.values())) self.assertIn(force_text(error), form_errors) def assertURLEqual(self, url, expected, parse_qs=False): """ Given two URLs, make sure all their components (the ones given by urlparse) are equal, only comparing components that are present in both URLs. If `parse_qs` is True, then the querystrings are parsed with QueryDict. This is useful if you don't want the order of parameters to matter. Otherwise, the query strings are compared as-is. """ fields = ParseResult._fields for attr, x, y in zip(fields, urlparse(url), urlparse(expected)): if parse_qs and attr == 'query': x, y = QueryDict(x), QueryDict(y) if x and y and x != y: self.fail("%r != %r (%s doesn't match)" % (url, expected, attr)) @override_settings(ROOT_URLCONF='django.contrib.auth.urls') class <API key>(AuthViewsTestCase): def test_named_urls(self): "Named URLs should be reversible" expected_named_urls = [ ('login', [], {}), ('logout', [], {}), ('password_change', [], {}), ('<API key>', [], {}), ('password_reset', [], {}), ('password_reset_done', [], {}), ('<API key>', [], { 'uidb64': 'aaaaaaa', 'token': '1111-aaaaa', }), ('<API key>', [], {}), ] for name, args, kwargs in expected_named_urls: try: reverse(name, args=args, kwargs=kwargs) except NoReverseMatch: self.fail("Reversal of url named '%s' failed with NoReverseMatch" % name) class PasswordResetTest(AuthViewsTestCase): def <API key>(self): """If the provided email is not registered, don't raise any error but also don't send any email.""" response = self.client.get('/password_reset/') self.assertEqual(response.status_code, 200) response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 0) def test_email_found(self): "Email is sent if a valid email address is provided for password reset" response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertIn("http://", mail.outbox[0].body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email) # optional multipart text/html email has been added. Make sure original, # default functionality is 100% the same self.assertFalse(mail.outbox[0].message().is_multipart()) def <API key>(self): """ extra_email_context should be available in the email template context. """ response = self.client.post( '/<API key>/', {'email': 'staffmember@example.com'}, ) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertIn('Email email context: "Hello!"', mail.outbox[0].body) def <API key>(self): """ A multipart email with text/plain and text/html is sent if the html_email_template parameter is passed to the view """ response = self.client.post('/password_reset/html_email_template/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0].message() self.assertEqual(len(message.get_payload()), 2) self.assertTrue(message.is_multipart()) self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain') self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') self.assertNotIn('<html>', message.get_payload(0).get_payload()) self.assertIn('<html>', message.get_payload(1).get_payload()) def <API key>(self): "Email is sent if a valid email address is provided for password reset when a custom from_email is provided." response = self.client.post('/<API key>/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertEqual("staffmember@example.com", mail.outbox[0].from_email) @ignore_warnings(category=<API key>) @override_settings(ALLOWED_HOSTS=['adminsite.com']) def test_admin_reset(self): "If the reset view is marked as being for admin, the HTTP_HOST header is used for a domain override." response = self.client.post('/<API key>/', {'email': 'staffmember@example.com'}, HTTP_HOST='adminsite.com' ) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertIn("http://adminsite.com", mail.outbox[0].body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email) # Skip any 500 handler action (like sending more mail...) @override_settings(<API key>=True) def <API key>(self): "Poisoned HTTP_HOST headers can't be used for reset emails" # This attack is based on the way browsers handle URLs. The colon # should be used to separate the port, but if the URL contains an @, # the colon is interpreted as part of a username for login purposes, # making 'evil.com' the request domain. Since HTTP_HOST is used to # produce a meaningful reset URL, we need to be certain that the # HTTP_HOST header isn't poisoned. This is done as a check when get_host() # is invoked, but we check here as a practical consequence. with patch_logger('django.security.DisallowedHost', 'error') as logger_calls: response = self.client.post( '/password_reset/', {'email': 'staffmember@example.com'}, HTTP_HOST='www.example:dr.frankenstein@evil.tld' ) self.assertEqual(response.status_code, 400) self.assertEqual(len(mail.outbox), 0) self.assertEqual(len(logger_calls), 1) # Skip any 500 handler action (like sending more mail...) @override_settings(<API key>=True) def <API key>(self): "Poisoned HTTP_HOST headers can't be used for reset emails on admin views" with patch_logger('django.security.DisallowedHost', 'error') as logger_calls: response = self.client.post( '/<API key>/', {'email': 'staffmember@example.com'}, HTTP_HOST='www.example:dr.frankenstein@evil.tld' ) self.assertEqual(response.status_code, 400) self.assertEqual(len(mail.outbox), 0) self.assertEqual(len(logger_calls), 1) def _test_confirm_start(self): # Start by creating the email self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) self.assertEqual(len(mail.outbox), 1) return self._read_signup_email(mail.outbox[0]) def _read_signup_email(self, email): urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body) self.assertIsNotNone(urlmatch, "No URL found in sent email") return urlmatch.group(), urlmatch.groups()[0] def test_confirm_valid(self): url, path = self._test_confirm_start() response = self.client.get(path) # redirect to a 'complete' page: self.assertContains(response, "Please enter your new password") def <API key>(self): url, path = self._test_confirm_start() # Let's munge the token in the path, but keep the same length, # in case the URLconf will reject a different length. path = path[:-5] + ("0" * 4) + path[-1] response = self.client.get(path) self.assertContains(response, "The password reset link was invalid") def <API key>(self): # Ensure that we get a 200 response for a non-existent user, not a 404 response = self.client.get('/reset/123456/1-1/') self.assertContains(response, "The password reset link was invalid") def <API key>(self): # Ensure that we get a 200 response for a base36 user id that overflows int response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/') self.assertContains(response, "The password reset link was invalid") def <API key>(self): # Same as <API key>, but trying # to do a POST instead. url, path = self._test_confirm_start() path = path[:-5] + ("0" * 4) + path[-1] self.client.post(path, { 'new_password1': 'anewpassword', 'new_password2': ' anewpassword', }) # Check the password has not been changed u = User.objects.get(email='staffmember@example.com') self.assertTrue(not u.check_password("anewpassword")) def <API key>(self): url, path = self._test_confirm_start() response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) # Check the password has been changed u = User.objects.get(email='staffmember@example.com') self.assertTrue(u.check_password("anewpassword")) # Check we can't use the link again response = self.client.get(path) self.assertContains(response, "The password reset link was invalid") def <API key>(self): url, path = self._test_confirm_start() response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'x'}) self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch']) def <API key>(self): response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/done/') def <API key>(self): response = self.client.post('/password_reset/custom_redirect/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/custom/') def <API key>(self): response = self.client.post('/password_reset/custom_redirect/named/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/') def <API key>(self): url, path = self._test_confirm_start() response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/reset/done/') def <API key>(self): url, path = self._test_confirm_start() path = path.replace('/reset/', '/reset/custom/') response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/custom/') def <API key>(self): url, path = self._test_confirm_start() path = path.replace('/reset/', '/reset/custom/named/') response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/') def <API key>(self): url, path = self._test_confirm_start() response = self.client.get(path) # #16919 -- The ``<API key>`` view should pass the user # object to the ``SetPasswordForm``, even on GET requests. # For this test, we render ``{{ form.user }}`` in the template # ``registration/<API key>.html`` so that we can test this. username = User.objects.get(email='staffmember@example.com').username self.assertContains(response, "Hello, %s." % username) # However, the view should NOT pass any user object on a form if the # password reset link was invalid. response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/') self.assertContains(response, "Hello, .") @override_settings(AUTH_USER_MODEL='auth.CustomUser') class <API key>(AuthViewsTestCase): user_email = 'staffmember@example.com' @classmethod def setUpTestData(cls): cls.u1 = CustomUser.custom_objects.create( password='sha1$6efc0$<SHA1-like>', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), email='staffmember@example.com', is_active=True, is_admin=False, date_of_birth=datetime.date(1976, 11, 8) ) def _test_confirm_start(self): # Start by creating the email response = self.client.post('/password_reset/', {'email': self.user_email}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) return self._read_signup_email(mail.outbox[0]) def _read_signup_email(self, email): urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body) self.assertIsNotNone(urlmatch, "No URL found in sent email") return urlmatch.group(), urlmatch.groups()[0] def <API key>(self): url, path = self._test_confirm_start() response = self.client.get(path) # redirect to a 'complete' page: self.assertContains(response, "Please enter your new password") # then submit a new password response = self.client.post(path, { 'new_password1': 'anewpassword', 'new_password2': 'anewpassword', }) self.assertRedirects(response, '/reset/done/') @override_settings(AUTH_USER_MODEL='auth.UUIDUser') class <API key>(<API key>): def _test_confirm_start(self): # instead of fixture UUIDUser.objects.create_user( email=self.user_email, username='foo', password='foo', ) return super(<API key>, self)._test_confirm_start() class ChangePasswordTest(AuthViewsTestCase): def fail_login(self, password='password'): response = self.client.post('/login/', { 'username': 'testclient', 'password': password, }) self.assertFormError(response, AuthenticationForm.error_messages['invalid_login'] % { 'username': User._meta.get_field('username').verbose_name }) def logout(self): self.client.get('/logout/') def test_<API key>(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'donuts', 'new_password1': 'password1', 'new_password2': 'password1', }) self.assertFormError(response, PasswordChangeForm.error_messages['password_incorrect']) def test_<API key>(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'donuts', }) self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch']) def test_<API key>(self): self.login() self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) self.fail_login() self.login(password='password1') def test_<API key>(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_change/done/') @override_settings(LOGIN_URL='/login/') def test_<API key>(self): response = self.client.get('/password_change/done/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/login/?next=/password_change/done/') def test_<API key>(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_change/done/') def test_<API key>(self): self.login() response = self.client.post('/password_change/custom/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/custom/') def test_<API key>(self): self.login() response = self.client.post('/password_change/custom/named/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/') @modify_settings(MIDDLEWARE_CLASSES={ 'append': 'django.contrib.auth.middleware.Session<API key>, }) class <API key>(AuthViewsTestCase): def test_user_<API key>(self): """ #21649 - Ensure contrib.auth.views.password_change updates the user's session auth hash after a password change so the session isn't logged out. """ self.login() response = self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) # if the hash isn't updated, retrieving the redirection page will fail. self.assertRedirects(response, '/password_change/done/') class LoginTest(AuthViewsTestCase): def <API key>(self): response = self.client.get(reverse('login')) self.assertEqual(response.status_code, 200) if apps.is_installed('django.contrib.sites'): Site = apps.get_model('sites.Site') site = Site.objects.get_current() self.assertEqual(response.context['site'], site) self.assertEqual(response.context['site_name'], site.name) else: self.assertIsInstance(response.context['site'], RequestSite) self.assertIsInstance(response.context['form'], AuthenticationForm) def test_security_check(self, password='password'): login_url = reverse('login') # Those URLs should not pass the security check for bad_url in ('http://example.com', 'http:///example.com', 'https://example.com', 'ftp://exampel.com', '///example.com', '//example.com', 'javascript:alert("XSS")'): nasty_url = '%(url)s?%(next)s=%(bad_url)s' % { 'url': login_url, 'next': REDIRECT_FIELD_NAME, 'bad_url': urlquote(bad_url), } response = self.client.post(nasty_url, { 'username': 'testclient', 'password': password, }) self.assertEqual(response.status_code, 302) self.assertNotIn(bad_url, response.url, "%s should be blocked" % bad_url) # These URLs *should* still pass the security check for good_url in ('/view/?param=http://example.com', '/view/?param=https://example.com', '/view?param=ftp://exampel.com', 'view/?param=//example.com', 'https://testserver/', 'HTTPS://testserver/', '//testserver/', '/url%20with%20spaces/'): # see ticket #12534 safe_url = '%(url)s?%(next)s=%(good_url)s' % { 'url': login_url, 'next': REDIRECT_FIELD_NAME, 'good_url': urlquote(good_url), } response = self.client.post(safe_url, { 'username': 'testclient', 'password': password, }) self.assertEqual(response.status_code, 302) self.assertIn(good_url, response.url, "%s should be allowed" % good_url) def <API key>(self): # 15198 self.client.post('/<API key>/', { 'username': 'testclient', 'password': 'password', }, follow=True) # the custom authentication form used by this login asserts # that a request is passed to the form successfully. def <API key>(self, password='password'): """ Makes sure that a login rotates the currently-used CSRF token. """ # Do a GET to establish a CSRF token # TestClient isn't used here as we're testing middleware, essentially. req = HttpRequest() CsrfViewMiddleware().process_view(req, login_view, (), {}) # get_token() triggers CSRF token inclusion in the response get_token(req) resp = login_view(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None) token1 = csrf_cookie.coded_value # Prepare the POST request req = HttpRequest() req.COOKIES[settings.CSRF_COOKIE_NAME] = token1 req.method = "POST" req.POST = {'username': 'testclient', 'password': password, 'csrfmiddlewaretoken': token1} # Use POST request to log in SessionMiddleware().process_request(req) CsrfViewMiddleware().process_view(req, login_view, (), {}) req.META["SERVER_NAME"] = "testserver" # Required to have redirect work in login view req.META["SERVER_PORT"] = 80 resp = login_view(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None) token2 = csrf_cookie.coded_value # Check the CSRF token switched self.assertNotEqual(token1, token2) def <API key>(self): """ To avoid reusing another user's session, ensure a new, empty session is created if the existing session corresponds to a different authenticated user. """ self.login() <API key> = self.client.session.session_key self.login(username='staff') self.assertNotEqual(<API key>, self.client.session.session_key) def <API key>(self): """ As above, but same user logging in after a password change. """ self.login() <API key> = self.client.session.session_key # If no password change, session key should not be flushed. self.login() self.assertEqual(<API key>, self.client.session.session_key) user = User.objects.get(username='testclient') user.set_password('foobar') user.save() self.login(password='foobar') self.assertNotEqual(<API key>, self.client.session.session_key) def <API key>(self): """ Session without django.contrib.auth.HASH_SESSION_KEY should login without an exception. """ user = User.objects.get(username='testclient') engine = import_module(settings.SESSION_ENGINE) session = engine.SessionStore() session[SESSION_KEY] = user.id session.save() <API key> = session.session_key self.client.cookies[settings.SESSION_COOKIE_NAME] = <API key> self.login() self.assertNotEqual(<API key>, self.client.session.session_key) class LoginURLSettings(AuthViewsTestCase): """Tests for settings.LOGIN_URL.""" def <API key>(self, url, parse_qs=False): response = self.client.get('/login_required/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, url, parse_qs=parse_qs) @override_settings(LOGIN_URL='/login/') def <API key>(self): self.<API key>('/login/?next=/login_required/') @override_settings(LOGIN_URL='login') def <API key>(self): self.<API key>('/login/?next=/login_required/') @override_settings(LOGIN_URL='http://remote.example.com/login') def <API key>(self): quoted_next = urlquote('http://testserver/login_required/') expected = 'http://remote.example.com/login?next=%s' % quoted_next self.<API key>(expected) @override_settings(LOGIN_URL='https:///login/') def <API key>(self): quoted_next = urlquote('http://testserver/login_required/') expected = 'https:///login/?next=%s' % quoted_next self.<API key>(expected) @override_settings(LOGIN_URL='/login/?pretty=1') def <API key>(self): self.<API key>('/login/?pretty=1&next=/login_required/', parse_qs=True) @override_settings(LOGIN_URL='http://remote.example.com/login/?next=/default/') def <API key>(self): quoted_next = urlquote('http://testserver/login_required/') expected = 'http://remote.example.com/login/?next=%s' % quoted_next self.<API key>(expected) @override_settings(LOGIN_URL=reverse_lazy('login')) def test_lazy_login_url(self): self.<API key>('/login/?next=/login_required/') class <API key>(AuthViewsTestCase): """Tests for settings.LOGIN_REDIRECT_URL.""" def <API key>(self, url): response = self.login() self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, url) def test_default(self): self.<API key>('/accounts/profile/') @override_settings(LOGIN_REDIRECT_URL='/custom/') def test_custom(self): self.<API key>('/custom/') @override_settings(LOGIN_REDIRECT_URL='password_reset') def test_named(self): self.<API key>('/password_reset/') @override_settings(LOGIN_REDIRECT_URL='http://remote.example.com/welcome/') def test_remote(self): self.<API key>('http://remote.example.com/welcome/') class <API key>(AuthViewsTestCase): """Tests for the redirect_to_login view""" @override_settings(LOGIN_URL=reverse_lazy('login')) def <API key>(self): <API key> = redirect_to_login(next='/else/where/') expected = '/login/?next=/else/where/' self.assertEqual(expected, <API key>.url) @override_settings(LOGIN_URL=reverse_lazy('login')) def <API key>(self): <API key> = redirect_to_login(next='/else/where/झ/') expected = '/login/?next=/else/where/%E0%A4%9D/' self.assertEqual(expected, <API key>.url) class LogoutTest(AuthViewsTestCase): def confirm_logged_out(self): self.assertNotIn(SESSION_KEY, self.client.session) def test_logout_default(self): "Logout without next_page option renders the default template" self.login() response = self.client.get('/logout/') self.assertContains(response, 'Logged out') self.confirm_logged_out() def test_14377(self): # Bug 14377 self.login() response = self.client.get('/logout/') self.assertIn('site', response.context) def <API key>(self): # Bug 11223 self.login() response = self.client.get('/logout/next_page/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/somewhere/') response = self.client.get('/logout/next_page/?next=/login/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/login/') self.confirm_logged_out() def <API key>(self): "Logout with next_page option given redirects to specified resource" self.login() response = self.client.get('/logout/next_page/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/somewhere/') self.confirm_logged_out() def <API key>(self): "Logout with query string redirects to specified resource" self.login() response = self.client.get('/logout/?next=/login/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/login/') self.confirm_logged_out() def <API key>(self): "Logout with custom query string redirects to specified resource" self.login() response = self.client.get('/logout/custom_query/?follow=/somewhere/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/somewhere/') self.confirm_logged_out() def <API key>(self): "Logout resolves names or URLs passed as next_page." self.login() response = self.client.get('/logout/next_page/named/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/') self.confirm_logged_out() def test_security_check(self, password='password'): logout_url = reverse('logout') # Those URLs should not pass the security check for bad_url in ('http://example.com', 'http:///example.com', 'https://example.com', 'ftp://exampel.com', '///example.com', '//example.com', 'javascript:alert("XSS")'): nasty_url = '%(url)s?%(next)s=%(bad_url)s' % { 'url': logout_url, 'next': REDIRECT_FIELD_NAME, 'bad_url': urlquote(bad_url), } self.login() response = self.client.get(nasty_url) self.assertEqual(response.status_code, 302) self.assertNotIn(bad_url, response.url, "%s should be blocked" % bad_url) self.confirm_logged_out() # These URLs *should* still pass the security check for good_url in ('/view/?param=http://example.com', '/view/?param=https://example.com', '/view?param=ftp://exampel.com', 'view/?param=//example.com', 'https://testserver/', 'HTTPS://testserver/', '//testserver/', '/url%20with%20spaces/'): # see ticket #12534 safe_url = '%(url)s?%(next)s=%(good_url)s' % { 'url': logout_url, 'next': REDIRECT_FIELD_NAME, 'good_url': urlquote(good_url), } self.login() response = self.client.get(safe_url) self.assertEqual(response.status_code, 302) self.assertIn(good_url, response.url, "%s should be allowed" % good_url) self.confirm_logged_out() def <API key>(self): """Check that language stored in session is preserved after logout""" # Create a new session with language engine = import_module(settings.SESSION_ENGINE) session = engine.SessionStore() session[<API key>] = 'pl' session.save() self.client.cookies[settings.SESSION_COOKIE_NAME] = session.session_key self.client.get('/logout/') self.assertEqual(self.client.session[<API key>], 'pl') # Redirect in <API key> will fail if session auth hash # isn't updated after password change (#21649) @modify_settings(MIDDLEWARE_CLASSES={ 'append': 'django.contrib.auth.middleware.Session<API key>, }) @override_settings( PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF='auth_tests.urls_admin', ) class ChangelistTests(AuthViewsTestCase): def setUp(self): # Make me a superuser before logging in. User.objects.filter(username='testclient').update(is_staff=True, is_superuser=True) self.login() self.admin = User.objects.get(pk=self.u1.pk) def get_user_data(self, user): return { 'username': user.username, 'password': user.password, 'email': user.email, 'is_active': user.is_active, 'is_staff': user.is_staff, 'is_superuser': user.is_superuser, 'last_login_0': user.last_login.strftime('%Y-%m-%d'), 'last_login_1': user.last_login.strftime('%H:%M:%S'), '<API key>': user.last_login.strftime('%Y-%m-%d'), '<API key>': user.last_login.strftime('%H:%M:%S'), 'date_joined_0': user.date_joined.strftime('%Y-%m-%d'), 'date_joined_1': user.date_joined.strftime('%H:%M:%S'), '<API key>': user.date_joined.strftime('%Y-%m-%d'), '<API key>': user.date_joined.strftime('%H:%M:%S'), 'first_name': user.first_name, 'last_name': user.last_name, } # #20078 - users shouldn't be allowed to guess password hashes via # repeated <API key> queries. def <API key>(self): # A lookup that tries to filter on password isn't OK with patch_logger('django.security.<API key>', 'error') as logger_calls: response = self.client.get(reverse('auth_test_admin:<API key>) + '?<API key>=sha1$') self.assertEqual(response.status_code, 400) self.assertEqual(len(logger_calls), 1) def <API key>(self): data = self.get_user_data(self.admin) data['email'] = 'new_' + data['email'] response = self.client.post( reverse('auth_test_admin:auth_user_change', args=(self.admin.pk,)), data ) self.assertRedirects(response, reverse('auth_test_admin:<API key>)) row = LogEntry.objects.latest('id') self.assertEqual(row.change_message, 'Changed email.') def <API key>(self): response = self.client.post( reverse('auth_test_admin:auth_user_change', args=(self.admin.pk,)), self.get_user_data(self.admin) ) self.assertRedirects(response, reverse('auth_test_admin:<API key>)) row = LogEntry.objects.latest('id') self.assertEqual(row.change_message, 'No fields changed.') def <API key>(self): user_change_url = reverse('auth_test_admin:auth_user_change', args=(self.admin.pk,)) password_change_url = reverse('auth_test_admin:<API key>, args=(self.admin.pk,)) response = self.client.get(user_change_url) # Test the link inside password field help_text. rel_link = re.search( r'you can change the password using <a href="([^"]*)">this form</a>', force_text(response.content) ).groups()[0] self.assertEqual( os.path.normpath(user_change_url + rel_link), os.path.normpath(password_change_url) ) response = self.client.post( password_change_url, { 'password1': 'password1', 'password2': 'password1', } ) self.assertRedirects(response, user_change_url) row = LogEntry.objects.latest('id') self.assertEqual(row.change_message, 'Changed password.') self.logout() self.login(password='password1') def <API key>(self): u = User.objects.get(email='staffmember@example.com') response = self.client.post( reverse('auth_test_admin:<API key>, args=(u.pk,)), { 'password1': 'password1', 'password2': 'password1', } ) self.assertRedirects(response, reverse('auth_test_admin:auth_user_change', args=(u.pk,))) row = LogEntry.objects.latest('id') self.assertEqual(row.user_id, self.admin.pk) self.assertEqual(row.object_id, str(u.pk)) self.assertEqual(row.change_message, 'Changed password.') def <API key>(self): response = self.client.get(reverse('auth_test_admin:<API key>, args=('foobar',))) self.assertEqual(response.status_code, 404) @override_settings( AUTH_USER_MODEL='auth.UUIDUser', ROOT_URLCONF='auth_tests.<API key>', ) class UUIDUserTests(TestCase): def <API key>(self): u = UUIDUser.objects.create_superuser(username='uuid', email='foo@bar.com', password='test') self.assertTrue(self.client.login(username='uuid', password='test')) user_change_url = reverse('custom_user_admin:<API key>, args=(u.pk,)) response = self.client.get(user_change_url) self.assertEqual(response.status_code, 200) password_change_url = reverse('custom_user_admin:<API key>, args=(u.pk,)) response = self.client.get(password_change_url) self.assertEqual(response.status_code, 200) # A LogEntry is created with pk=1 which breaks a FK constraint on MySQL with connection.<API key>(): response = self.client.post(password_change_url, { 'password1': 'password1', 'password2': 'password1', }) self.assertRedirects(response, user_change_url) row = LogEntry.objects.latest('id') self.assertEqual(row.user_id, 1) # harcoded in CustomUserAdmin.log_change() self.assertEqual(row.object_id, str(u.pk)) self.assertEqual(row.change_message, 'Changed password.')
<<API key> <API key>="customDataEntryForm"></<API key>>
! This file is all about BACKSPACE ! { dg-do run } integer i, n, nr real x(10), y(10) ! PR libfortran/20068 open (20, status='scratch') write (20,*) 1 write (20,*) 2 write (20,*) 3 rewind (20) read (20,*) i if (i .ne. 1) call abort write (*,*) ' ' backspace (20) read (20,*) i if (i .ne. 1) call abort close (20) ! PR libfortran/20125 open (20, status='scratch') write (20,*) 7 backspace (20) read (20,*) i if (i .ne. 7) call abort close (20) open (20, status='scratch', form='unformatted') write (20) 8 backspace (20) read (20) i if (i .ne. 8) call abort close (20) ! PR libfortran/20471 do n = 1, 10 x(n) = sqrt(real(n)) end do open (3, form='unformatted', status='scratch') write (3) (x(n),n=1,10) backspace (3) rewind (3) read (3) (y(n),n=1,10) do n = 1, 10 if (abs(x(n)-y(n)) > 0.00001) call abort end do close (3) ! PR libfortran/20156 open (3, form='unformatted', status='scratch') do i = 1, 5 x(1) = i write (3) n, (x(n),n=1,10) end do nr = 0 rewind (3) 20 continue read (3,end=30,err=90) n, (x(n),n=1,10) nr = nr + 1 goto 20 30 continue if (nr .ne. 5) call abort do i = 1, nr+1 backspace (3) end do do i = 1, nr read(3,end=70,err=90) n, (x(n),n=1,10) if (abs(x(1) - i) .gt. 0.001) call abort end do close (3) stop 70 continue call abort 90 continue call abort end
'use strict'; const path = require('../fastpath'); const <API key> = require('./<API key>'); function <API key>(filename, platforms) { const ext = path.extname(filename); const platformExt = <API key>(filename, platforms); let pattern = '@([\\d\\.]+)x'; if (platformExt != null) { pattern += '(\\.' + platformExt + ')?'; } pattern += '\\' + ext + '$'; const re = new RegExp(pattern); const match = filename.match(re); let resolution; if (!(match && match[1])) { resolution = 1; } else { resolution = parseFloat(match[1], 10); if (isNaN(resolution)) { resolution = 1; } } let assetName; if (match) { assetName = filename.replace(re, ext); } else if (platformExt != null) { assetName = filename.replace(new RegExp(`\\.${platformExt}\\${ext}`), ext); } else { assetName = filename; } return { resolution: resolution, assetName: assetName, type: ext.slice(1), name: path.basename(assetName, ext), platform: platformExt, }; } module.exports = <API key>;
var utils = require('../../lib/utils'); // if they agree to the ULA, notify hubspot, create a trial and send verification link module.exports = function trialSignup(request, reply) { var postToHubspot = request.server.methods.npme.sendData, getCustomer = request.server.methods.npme.getCustomer; var opts = {}; var data = { hs_context: { pageName: "<API key>", ipAddress: utils.getUserIP(request) }, // we can trust the email is fine because we've verified it in the show-ula handler email: request.payload.customer_email, }; postToHubspot(process.env.<API key>, data, function(er) { if (er) { request.logger.error('Could not hit ULA notification form on Hubspot'); request.logger.error(er); reply.view('errors/internal', opts).code(500); return; } getCustomer(data.email, function(err, customer) { if (err) { request.logger.error('Unknown problem with customer record'); request.logger.error(err); reply.view('errors/internal', opts).code(500); return; } if (!customer) { request.logger.error('Unable to locate customer error ' + data.email); reply.view('errors/internal', opts).code(500); return; } if (customer && customer.id + '' === request.payload.customer_id + '') { return createTrialAccount(request, reply, customer); } request.logger.error('Unable to verify customer record ', data.email); reply.view('errors/internal', opts).code(500); }); }); }; function createTrialAccount(request, reply, customer) { var createTrial = request.server.methods.npme.createTrial; var opts = {}; createTrial(customer, function(er, trial) { if (er) { request.logger.error('There was an error with creating a trial for ', customer.id); request.logger.error(er); reply.view('errors/internal', opts).code(500); return; } return <API key>(request, reply, customer, trial); }); } function <API key>(request, reply, customer, trial) { var opts = {}; var sendEmail = request.server.methods.email.send; var user = { name: customer.name, email: customer.email, verification_key: trial.verification_key }; sendEmail('<API key>', user, request.redis) .catch(function(er) { request.logger.error('Unable to send verification email to ', customer); request.logger.error(er); reply.view('errors/internal', opts).code(500); return; }) .then(function() { return reply.view('enterprise/thanks', opts); }); }
using System; using System.Collections.Generic; using UIKit; using Foundation; using System.Reflection; namespace FontList.Code { <summary> Combined DataSource and Delegate for our UITableView </summary> public class NavItemTableSource : UITableViewSource { protected List<NavItemGroup> navItems; string cellIdentifier = "NavTableCellView"; <API key> <API key>; public NavItemTableSource (<API key> <API key>, List<NavItemGroup> items) { navItems = items; this.<API key> = <API key>; } <summary> Called by the TableView to determine how many sections(groups) there are. </summary> public override nint NumberOfSections (UITableView tableView) { return navItems.Count; } <summary> Called by the TableView to determine how many cells to create for that particular section. </summary> public override nint RowsInSection (UITableView tableview, nint section) { return navItems[(int)section].Items.Count; } <summary> Called by the TableView to retrieve the header text for the particular section(group) </summary> public override string TitleForHeader (UITableView tableView, nint section) { return navItems[(int)section].Name; } <summary> Called by the TableView to retrieve the footer text for the particular section(group) </summary> public override string TitleForFooter (UITableView tableView, nint section) { return navItems[(int)section].Footer; } <summary> Called by the TableView to actually build each cell. </summary> public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { NavItem navItem = this.navItems[indexPath.Section].Items[indexPath.Row]; var cell = tableView.DequeueReusableCell (this.cellIdentifier); if (cell == null) { cell = new UITableViewCell (<API key>.Default, this.cellIdentifier); cell.Tag = Environment.TickCount; } cell.TextLabel.Text = this.navItems[indexPath.Section].Items[indexPath.Row].Name; cell.Accessory = <API key>.DisclosureIndicator; if (navItem.Font != null) { cell.TextLabel.Font = navItem.Font; } return cell; } <summary> Is called when a row is selected </summary> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { NavItem navItem = navItems[indexPath.Section].Items[indexPath.Row]; // if the nav item has a proper controller, push it on to the <API key> // NOTE: we could also raise an event here, to loosely couple this, but isn't neccessary, // because we'll only ever use this this way if (navItem.Controller != null) { <API key>.PushViewController (navItem.Controller, true); // show the nav bar (we don't show it on the home page) <API key>.NavigationBarHidden = false; } else { if (navItem.ControllerType != null) { ConstructorInfo ctor = null; // if the nav item has constructor aguments if (navItem.<API key>.Length > 0) { // look for the constructor ctor = navItem.ControllerType.GetConstructor (navItem.<API key>); } else { // search for the default constructor ctor = navItem.ControllerType.GetConstructor (System.Type.EmptyTypes); } // if we found the constructor if (ctor != null) { UIViewController instance = null; if (navItem.<API key>.Length > 0) { // instance the view controller instance = ctor.Invoke (navItem.<API key>) as UIViewController; } else { // instance the view controller instance = ctor.Invoke (null) as UIViewController; } if (instance != null) { // save the object navItem.Controller = instance; // push the view controller onto the stack <API key>.PushViewController (navItem.Controller, true); } else { Console.WriteLine ("instance of view controller not created"); } } else { Console.WriteLine ("constructor not found"); } } } } } }
var insert = require('./insert') var concat = require('concat-stream') insert('aggregate', [{ name: 'Squirtle', type: 'water' }, { name: 'Starmie', type: 'water' }, { name: 'Charmander', type: 'fire' }, { name: 'Lapras', type: 'water' }], function (db, t, done) { db.a.aggregate([{$group: {_id: '$type'}}, {$project: { _id: 0, foo: '$_id' }}], function (err, types) { console.log(err, types) var arr = types.map(function (x) {return x.foo}) console.log('arr', arr) t.equal(types.length, 2) console.log('here') t.notEqual(arr.indexOf('fire'), -1) console.log('there') t.notEqual(arr.indexOf('water'), -1) console.log('where') // test as a stream var strm = db.a.aggregate([{$group: {_id: '$type'}}, {$project: {_id: 0, foo: '$_id'}}]) strm.pipe(concat(function (types) { var arr = types.map(function (x) {return x.foo}) t.equal(types.length, 2) t.notEqual(arr.indexOf('fire'), -1) t.notEqual(arr.indexOf('water'), -1) t.end() })) strm.on('error', function (err) { // Aggregation cursors are only supported on mongodb 2.6+ // this shouldn't fail the tests for other versions of mongodb if (err.message === 'unrecognized field "cursor') t.ok(1) else t.fail(err) t.end() }) }) })
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use ArrayObject; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\Collection\Cells; use PhpOffice\PhpSpreadsheet\Collection\CellsFactory; use PhpOffice\PhpSpreadsheet\Comment; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Style; class Worksheet implements IComparable { // Break types const BREAK_NONE = 0; const BREAK_ROW = 1; const BREAK_COLUMN = 2; // Sheet state const SHEETSTATE_VISIBLE = 'visible'; const SHEETSTATE_HIDDEN = 'hidden'; const <API key> = 'veryHidden'; /** * Maximum 31 characters allowed for sheet title. * * @var int */ const <API key> = 31; /** * Invalid characters in sheet title. * * @var array */ private static $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']']; /** * Parent spreadsheet. * * @var Spreadsheet */ private $parent; /** * Collection of cells. * * @var Cells */ private $cellCollection; /** * Collection of row dimensions. * * @var RowDimension[] */ private $rowDimensions = []; /** * Default row dimension. * * @var RowDimension */ private $defaultRowDimension; /** * Collection of column dimensions. * * @var ColumnDimension[] */ private $columnDimensions = []; /** * Default column dimension. * * @var ColumnDimension */ private $<API key>; /** * Collection of drawings. * * @var BaseDrawing[] */ private $drawingCollection; /** * Collection of Chart objects. * * @var Chart[] */ private $chartCollection = []; /** * Worksheet title. * * @var string */ private $title; /** * Sheet state. * * @var string */ private $sheetState; /** * Page setup. * * @var PageSetup */ private $pageSetup; /** * Page margins. * * @var PageMargins */ private $pageMargins; /** * Page header/footer. * * @var HeaderFooter */ private $headerFooter; /** * Sheet view. * * @var SheetView */ private $sheetView; /** * Protection. * * @var Protection */ private $protection; /** * Collection of styles. * * @var Style[] */ private $styles = []; /** * Conditional styles. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $<API key> = []; /** * Is the current cell collection sorted already? * * @var bool */ private $<API key> = false; /** * Collection of breaks. * * @var array */ private $breaks = []; /** * Collection of merged cell ranges. * * @var array */ private $mergeCells = []; /** * Collection of protected cell ranges. * * @var array */ private $protectedCells = []; /** * Autofilter Range and selection. * * @var AutoFilter */ private $autoFilter; /** * Freeze pane. * * @var null|string */ private $freezePane; /** * Default position of the right bottom pane. * * @var null|string */ private $topLeftCell; /** * Show gridlines? * * @var bool */ private $showGridlines = true; /** * Print gridlines? * * @var bool */ private $printGridlines = false; /** * Show row and column headers? * * @var bool */ private $showRowColHeaders = true; /** * Show summary below? (Row/Column outline). * * @var bool */ private $showSummaryBelow = true; /** * Show summary right? (Row/Column outline). * * @var bool */ private $showSummaryRight = true; /** * Collection of comments. * * @var Comment[] */ private $comments = []; /** * Active cell. (Only one!). * * @var string */ private $activeCell = 'A1'; /** * Selected cells. * * @var string */ private $selectedCells = 'A1'; /** * Cached highest column. * * @var string */ private $cachedHighestColumn = 'A'; /** * Cached highest row. * * @var int */ private $cachedHighestRow = 1; /** * Right-to-left? * * @var bool */ private $rightToLeft = false; /** * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $hyperlinkCollection = []; /** * Data validation objects. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $<API key> = []; /** * Tab color. * * @var Color */ private $tabColor; /** * Dirty flag. * * @var bool */ private $dirty = true; /** * Hash. * * @var string */ private $hash; /** * CodeName. * * @var string */ private $codeName; /** * Create a new worksheet. * * @param Spreadsheet $parent * @param string $pTitle */ public function __construct(Spreadsheet $parent = null, $pTitle = 'Worksheet') { // Set parent and title $this->parent = $parent; $this->setTitle($pTitle, false); // setTitle can change $pTitle $this->setCodeName($this->getTitle()); $this->setSheetState(self::SHEETSTATE_VISIBLE); $this->cellCollection = CellsFactory::getInstance($this); // Set page setup $this->pageSetup = new PageSetup(); // Set page margins $this->pageMargins = new PageMargins(); // Set page header/footer $this->headerFooter = new HeaderFooter(); // Set sheet view $this->sheetView = new SheetView(); // Drawing collection $this->drawingCollection = new \ArrayObject(); // Chart collection $this->chartCollection = new \ArrayObject(); // Protection $this->protection = new Protection(); // Default row dimension $this->defaultRowDimension = new RowDimension(null); // Default column dimension $this-><API key> = new ColumnDimension(null); $this->autoFilter = new AutoFilter(null, $this); } /** * Disconnect all cells from this Worksheet object, * typically so that the worksheet object can be unset. */ public function disconnectCells() { if ($this->cellCollection !== null) { $this->cellCollection->unsetWorksheetCells(); $this->cellCollection = null; } // detach ourself from the workbook, so that it can then delete this worksheet successfully $this->parent = null; } /** * Code to execute when this worksheet is unset(). */ public function __destruct() { Calculation::getInstance($this->parent)-><API key>($this->title); $this->disconnectCells(); } /** * Return the cell collection. * * @return Cells */ public function getCellCollection() { return $this->cellCollection; } /** * Get array of invalid characters for sheet title. * * @return array */ public static function <API key>() { return self::$invalidCharacters; } /** * Check sheet code name for valid Excel syntax. * * @param string $pValue The string to check * * @throws Exception * * @return string The valid string */ private static function checkSheetCodeName($pValue) { $CharCount = Shared\StringHelper::countCharacters($pValue); if ($CharCount == 0) { throw new Exception('Sheet code name cannot be empty.'); } // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'" if ((str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) || (Shared\StringHelper::substring($pValue, -1, 1) == '\'') || (Shared\StringHelper::substring($pValue, 0, 1) == '\'')) { throw new Exception('Invalid character found in sheet code name'); } // Enforce maximum characters allowed for sheet title if ($CharCount > self::<API key>) { throw new Exception('Maximum ' . self::<API key> . ' characters allowed in sheet code name.'); } return $pValue; } /** * Check sheet title for valid Excel syntax. * * @param string $pValue The string to check * * @throws Exception * * @return string The valid string */ private static function checkSheetTitle($pValue) { // Some of the printable ASCII characters are invalid: * : / \ ? [ ] if (str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) { throw new Exception('Invalid character found in sheet title'); } // Enforce maximum characters allowed for sheet title if (Shared\StringHelper::countCharacters($pValue) > self::<API key>) { throw new Exception('Maximum ' . self::<API key> . ' characters allowed in sheet title.'); } return $pValue; } /** * Get a sorted list of all cell coordinates currently held in the collection by row and column. * * @param bool $sorted Also sort the cell collection? * * @return string[] */ public function getCoordinates($sorted = true) { if ($this->cellCollection == null) { return []; } if ($sorted) { return $this->cellCollection-><API key>(); } return $this->cellCollection->getCoordinates(); } /** * Get collection of row dimensions. * * @return RowDimension[] */ public function getRowDimensions() { return $this->rowDimensions; } /** * Get default row dimension. * * @return RowDimension */ public function <API key>() { return $this->defaultRowDimension; } /** * Get collection of column dimensions. * * @return ColumnDimension[] */ public function getColumnDimensions() { return $this->columnDimensions; } /** * Get default column dimension. * * @return ColumnDimension */ public function <API key>() { return $this-><API key>; } /** * Get collection of drawings. * * @return BaseDrawing[] */ public function <API key>() { return $this->drawingCollection; } /** * Get collection of charts. * * @return Chart[] */ public function getChartCollection() { return $this->chartCollection; } /** * Add chart. * * @param Chart $pChart * @param null|int $iChartIndex Index where chart should go (0,1,..., or null for last) * * @return Chart */ public function addChart(Chart $pChart, $iChartIndex = null) { $pChart->setWorksheet($this); if ($iChartIndex === null) { $this->chartCollection[] = $pChart; } else { // Insert the chart at the requested index array_splice($this->chartCollection, $iChartIndex, 0, [$pChart]); } return $pChart; } /** * Return the count of charts on this worksheet. * * @return int The number of charts */ public function getChartCount() { return count($this->chartCollection); } /** * Get a chart by its index position. * * @param string $index Chart index position * * @return Chart|false */ public function getChartByIndex($index) { $chartCount = count($this->chartCollection); if ($chartCount == 0) { return false; } if ($index === null) { $index = --$chartCount; } if (!isset($this->chartCollection[$index])) { return false; } return $this->chartCollection[$index]; } /** * Return an array of the names of charts on this worksheet. * * @return string[] The names of charts */ public function getChartNames() { $chartNames = []; foreach ($this->chartCollection as $chart) { $chartNames[] = $chart->getName(); } return $chartNames; } /** * Get a chart by name. * * @param string $chartName Chart name * * @return Chart|false */ public function getChartByName($chartName) { $chartCount = count($this->chartCollection); if ($chartCount == 0) { return false; } foreach ($this->chartCollection as $index => $chart) { if ($chart->getName() == $chartName) { return $this->chartCollection[$index]; } } return false; } /** * Refresh column dimensions. * * @return Worksheet */ public function <API key>() { $<API key> = $this->getColumnDimensions(); $newColumnDimensions = []; foreach ($<API key> as $objColumnDimension) { $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension; } $this->columnDimensions = $newColumnDimensions; return $this; } /** * Refresh row dimensions. * * @return Worksheet */ public function <API key>() { $<API key> = $this->getRowDimensions(); $newRowDimensions = []; foreach ($<API key> as $objRowDimension) { $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension; } $this->rowDimensions = $newRowDimensions; return $this; } /** * Calculate worksheet dimension. * * @return string String containing the dimension of this worksheet */ public function <API key>() { // Return return 'A1' . ':' . $this->getHighestColumn() . $this->getHighestRow(); } /** * Calculate worksheet data dimension. * * @return string String containing the dimension of this worksheet that actually contain data */ public function <API key>() { // Return return 'A1' . ':' . $this-><API key>() . $this->getHighestDataRow(); } /** * Calculate widths for auto-size columns. * * @return Worksheet; */ public function <API key>() { // initialize $autoSizes array $autoSizes = []; foreach ($this->getColumnDimensions() as $colDimension) { if ($colDimension->getAutoSize()) { $autoSizes[$colDimension->getColumnIndex()] = -1; } } // There is only something to do if there are some auto-size columns if (!empty($autoSizes)) { // build list of cells references that participate in a merge $isMergeCell = []; foreach ($this->getMergeCells() as $cells) { foreach (Coordinate::<API key>($cells) as $cellReference) { $isMergeCell[$cellReference] = true; } } // loop through all cells in the worksheet foreach ($this->getCoordinates(false) as $coordinate) { $cell = $this->getCell($coordinate, false); if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) { //Determine if cell is in merge range $isMerged = isset($isMergeCell[$this->cellCollection-><API key>()]); //By default merged cells should be ignored $isMergedButProceed = false; //The only exception is if it's a merge range value cell of a 'vertical' randge (1 column wide) if ($isMerged && $cell-><API key>()) { $range = $cell->getMergeRange(); $rangeBoundaries = Coordinate::rangeDimension($range); if ($rangeBoundaries[0] == 1) { $isMergedButProceed = true; } } // Determine width if cell does not participate in a merge or does and is a value cell of 1-column wide range if (!$isMerged || $isMergedButProceed) { // Calculated value // To formatted string $cellValue = NumberFormat::toFormattedString( $cell->getCalculatedValue(), $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode() ); $autoSizes[$this->cellCollection->getCurrentColumn()] = max( (float) $autoSizes[$this->cellCollection->getCurrentColumn()], (float) Shared\Font::<API key>( $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(), $cellValue, $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(), $this->getParent()->getDefaultStyle()->getFont() ) ); } } } // adjust column widths foreach ($autoSizes as $columnIndex => $width) { if ($width == -1) { $width = $this-><API key>()->getWidth(); } $this->getColumnDimension($columnIndex)->setWidth($width); } } return $this; } /** * Get parent. * * @return Spreadsheet */ public function getParent() { return $this->parent; } /** * Re-bind parent. * * @param Spreadsheet $parent * * @return Worksheet */ public function rebindParent(Spreadsheet $parent) { if ($this->parent !== null) { $namedRanges = $this->parent->getNamedRanges(); foreach ($namedRanges as $namedRange) { $parent->addNamedRange($namedRange); } $this->parent->removeSheetByIndex( $this->parent->getIndex($this) ); } $this->parent = $parent; return $this; } /** * Get title. * * @return string */ public function getTitle() { return $this->title; } /** * Set title. * * @param string $pValue String containing the dimension of this worksheet * @param bool $<API key> Flag indicating whether cell references in formulae should * be updated to reflect the new sheet name. * This should be left as the default true, unless you are * certain that no formula cells on any worksheet contain * references to this worksheet * @param bool $validate False to skip validation of new title. WARNING: This should only be set * at parse time (by Readers), where titles can be assumed to be valid. * * @return Worksheet */ public function setTitle($pValue, $<API key> = true, $validate = true) { // Is this a 'rename' or not? if ($this->getTitle() == $pValue) { return $this; } // Old title $oldTitle = $this->getTitle(); if ($validate) { // Syntax check self::checkSheetTitle($pValue); if ($this->parent) { // Is there already such sheet name? if ($this->parent->sheetNameExists($pValue)) { // Use name, but append with lowest possible integer if (Shared\StringHelper::countCharacters($pValue) > 29) { $pValue = Shared\StringHelper::substring($pValue, 0, 29); } $i = 1; while ($this->parent->sheetNameExists($pValue . ' ' . $i)) { ++$i; if ($i == 10) { if (Shared\StringHelper::countCharacters($pValue) > 28) { $pValue = Shared\StringHelper::substring($pValue, 0, 28); } } elseif ($i == 100) { if (Shared\StringHelper::countCharacters($pValue) > 27) { $pValue = Shared\StringHelper::substring($pValue, 0, 27); } } } $pValue .= " $i"; } } } // Set title $this->title = $pValue; $this->dirty = true; if ($this->parent && $this->parent-><API key>()) { // New title $newTitle = $this->getTitle(); $this->parent-><API key>() -><API key>($oldTitle, $newTitle); if ($<API key>) { ReferenceHelper::getInstance()->updateNamedFormulas($this->parent, $oldTitle, $newTitle); } } return $this; } /** * Get sheet state. * * @return string Sheet state (visible, hidden, veryHidden) */ public function getSheetState() { return $this->sheetState; } /** * Set sheet state. * * @param string $value Sheet state (visible, hidden, veryHidden) * * @return Worksheet */ public function setSheetState($value) { $this->sheetState = $value; return $this; } /** * Get page setup. * * @return PageSetup */ public function getPageSetup() { return $this->pageSetup; } /** * Set page setup. * * @param PageSetup $pValue * * @return Worksheet */ public function setPageSetup(PageSetup $pValue) { $this->pageSetup = $pValue; return $this; } /** * Get page margins. * * @return PageMargins */ public function getPageMargins() { return $this->pageMargins; } /** * Set page margins. * * @param PageMargins $pValue * * @return Worksheet */ public function setPageMargins(PageMargins $pValue) { $this->pageMargins = $pValue; return $this; } /** * Get page header/footer. * * @return HeaderFooter */ public function getHeaderFooter() { return $this->headerFooter; } /** * Set page header/footer. * * @param HeaderFooter $pValue * * @return Worksheet */ public function setHeaderFooter(HeaderFooter $pValue) { $this->headerFooter = $pValue; return $this; } /** * Get sheet view. * * @return SheetView */ public function getSheetView() { return $this->sheetView; } /** * Set sheet view. * * @param SheetView $pValue * * @return Worksheet */ public function setSheetView(SheetView $pValue) { $this->sheetView = $pValue; return $this; } /** * Get Protection. * * @return Protection */ public function getProtection() { return $this->protection; } /** * Set Protection. * * @param Protection $pValue * * @return Worksheet */ public function setProtection(Protection $pValue) { $this->protection = $pValue; $this->dirty = true; return $this; } /** * Get highest worksheet column. * * @param string $row Return the data highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name */ public function getHighestColumn($row = null) { if ($row == null) { return $this->cachedHighestColumn; } return $this-><API key>($row); } /** * Get highest worksheet column that contains data. * * @param string $row Return the highest data column for the specified row, * or the highest data column of any row if no row number is passed * * @return string Highest column name that contains data */ public function <API key>($row = null) { return $this->cellCollection->getHighestColumn($row); } /** * Get highest worksheet row. * * @param string $column Return the highest data row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number */ public function getHighestRow($column = null) { if ($column == null) { return $this->cachedHighestRow; } return $this->getHighestDataRow($column); } /** * Get highest worksheet row that contains data. * * @param string $column Return the highest data row for the specified column, * or the highest data row of any column if no column letter is passed * * @return int Highest row number that contains data */ public function getHighestDataRow($column = null) { return $this->cellCollection->getHighestRow($column); } /** * Get highest worksheet column and highest row that have cell records. * * @return array Highest column name and highest row number */ public function <API key>() { return $this->cellCollection-><API key>(); } /** * Set a cell value. * * @param string $pCoordinate Coordinate of the cell, eg: 'A1' * @param mixed $pValue Value of the cell * * @return Worksheet */ public function setCellValue($pCoordinate, $pValue) { $this->getCell($pCoordinate)->setValue($pValue); return $this; } /** * Set a cell value by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param mixed $value Value of the cell * * @return Worksheet */ public function <API key>($columnIndex, $row, $value) { $this-><API key>($columnIndex, $row)->setValue($value); return $this; } /** * Set a cell value. * * @param string $pCoordinate Coordinate of the cell, eg: 'A1' * @param mixed $pValue Value of the cell * @param string $pDataType Explicit data type, see DataType::TYPE_* * * @return Worksheet */ public function <API key>($pCoordinate, $pValue, $pDataType) { // Set value $this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType); return $this; } /** * Set a cell value by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param mixed $value Value of the cell * @param string $dataType Explicit data type, see DataType::TYPE_* * * @return Worksheet */ public function <API key>($columnIndex, $row, $value, $dataType) { $this-><API key>($columnIndex, $row)->setValueExplicit($value, $dataType); return $this; } /** * Get cell at a specific coordinate. * * @param string $pCoordinate Coordinate of the cell, eg: 'A1' * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't * already exist, or a null should be returned instead * * @throws Exception * * @return null|Cell Cell that was found/created or null */ public function getCell($pCoordinate, $createIfNotExists = true) { // Uppercase coordinate $pCoordinateUpper = strtoupper($pCoordinate); // Check cell collection if ($this->cellCollection->has($pCoordinateUpper)) { return $this->cellCollection->get($pCoordinateUpper); } // Worksheet reference? if (strpos($pCoordinate, '!') !== false) { $worksheetReference = self::extractSheetTitle($pCoordinate, true); return $this->parent->getSheetByName($worksheetReference[0])->getCell(strtoupper($worksheetReference[1]), $createIfNotExists); } // Named range? if ((!preg_match('/^' . Calculation::<API key> . '$/i', $pCoordinate, $matches)) && (preg_match('/^' . Calculation::<API key> . '$/i', $pCoordinate, $matches))) { $namedRange = NamedRange::resolveRange($pCoordinate, $this); if ($namedRange !== null) { $pCoordinate = $namedRange->getRange(); return $namedRange->getWorksheet()->getCell($pCoordinate, $createIfNotExists); } } if (Coordinate::coordinateIsRange($pCoordinate)) { throw new Exception('Cell coordinate can not be a range of cells.'); } elseif (strpos($pCoordinate, '$') !== false) { throw new Exception('Cell coordinate must not be absolute.'); } // Create new cell object, if required return $createIfNotExists ? $this->createNewCell($pCoordinateUpper) : null; } /** * Get cell at a specific coordinate by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't * already exist, or a null should be returned instead * * @return null|Cell Cell that was found/created or null */ public function <API key>($columnIndex, $row, $createIfNotExists = true) { $columnLetter = Coordinate::<API key>($columnIndex); $coordinate = $columnLetter . $row; if ($this->cellCollection->has($coordinate)) { return $this->cellCollection->get($coordinate); } // Create new cell object, if required return $createIfNotExists ? $this->createNewCell($coordinate) : null; } /** * Create a new cell at the specified coordinate. * * @param string $pCoordinate Coordinate of the cell * * @return Cell Cell that was created */ private function createNewCell($pCoordinate) { $cell = new Cell(null, DataType::TYPE_NULL, $this); $this->cellCollection->add($pCoordinate, $cell); $this-><API key> = false; // Coordinates $aCoordinates = Coordinate::<API key>($pCoordinate); if (Coordinate::<API key>($this->cachedHighestColumn) < Coordinate::<API key>($aCoordinates[0])) { $this->cachedHighestColumn = $aCoordinates[0]; } if ($aCoordinates[1] > $this->cachedHighestRow) { $this->cachedHighestRow = $aCoordinates[1]; } // Cell needs appropriate xfIndex from dimensions records // but don't create dimension records if they don't already exist $rowDimension = $this->getRowDimension($aCoordinates[1], false); $columnDimension = $this->getColumnDimension($aCoordinates[0], false); if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) { // then there is a row dimension with explicit style, assign it to the cell $cell->setXfIndex($rowDimension->getXfIndex()); } elseif ($columnDimension !== null && $columnDimension->getXfIndex() > 0) { // then there is a column dimension, assign it to the cell $cell->setXfIndex($columnDimension->getXfIndex()); } return $cell; } /** * Does the cell at a specific coordinate exist? * * @param string $pCoordinate Coordinate of the cell eg: 'A1' * * @throws Exception * * @return bool */ public function cellExists($pCoordinate) { // Worksheet reference? if (strpos($pCoordinate, '!') !== false) { $worksheetReference = self::extractSheetTitle($pCoordinate, true); return $this->parent->getSheetByName($worksheetReference[0])->cellExists(strtoupper($worksheetReference[1])); } // Named range? if ((!preg_match('/^' . Calculation::<API key> . '$/i', $pCoordinate, $matches)) && (preg_match('/^' . Calculation::<API key> . '$/i', $pCoordinate, $matches))) { $namedRange = NamedRange::resolveRange($pCoordinate, $this); if ($namedRange !== null) { $pCoordinate = $namedRange->getRange(); if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) { if (!$namedRange->getLocalOnly()) { return $namedRange->getWorksheet()->cellExists($pCoordinate); } throw new Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle()); } } else { return false; } } // Uppercase coordinate $pCoordinate = strtoupper($pCoordinate); if (Coordinate::coordinateIsRange($pCoordinate)) { throw new Exception('Cell coordinate can not be a range of cells.'); } elseif (strpos($pCoordinate, '$') !== false) { throw new Exception('Cell coordinate must not be absolute.'); } // Cell exists? return $this->cellCollection->has($pCoordinate); } /** * Cell at a specific coordinate by using numeric cell coordinates exists? * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @return bool */ public function <API key>($columnIndex, $row) { return $this->cellExists(Coordinate::<API key>($columnIndex) . $row); } /** * Get row dimension at a specific row. * * @param int $pRow Numeric index of the row * @param bool $create * * @return RowDimension */ public function getRowDimension($pRow, $create = true) { // Found $found = null; // Get row dimension if (!isset($this->rowDimensions[$pRow])) { if (!$create) { return null; } $this->rowDimensions[$pRow] = new RowDimension($pRow); $this->cachedHighestRow = max($this->cachedHighestRow, $pRow); } return $this->rowDimensions[$pRow]; } /** * Get column dimension at a specific column. * * @param string $pColumn String index of the column eg: 'A' * @param bool $create * * @return ColumnDimension */ public function getColumnDimension($pColumn, $create = true) { // Uppercase coordinate $pColumn = strtoupper($pColumn); // Fetch dimensions if (!isset($this->columnDimensions[$pColumn])) { if (!$create) { return null; } $this->columnDimensions[$pColumn] = new ColumnDimension($pColumn); if (Coordinate::<API key>($this->cachedHighestColumn) < Coordinate::<API key>($pColumn)) { $this->cachedHighestColumn = $pColumn; } } return $this->columnDimensions[$pColumn]; } /** * Get column dimension at a specific column by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * * @return ColumnDimension */ public function <API key>($columnIndex) { return $this->getColumnDimension(Coordinate::<API key>($columnIndex)); } /** * Get styles. * * @return Style[] */ public function getStyles() { return $this->styles; } /** * Get style for cell. * * @param string $pCellCoordinate Cell coordinate (or range) to get style for, eg: 'A1' * * @throws Exception * * @return Style */ public function getStyle($pCellCoordinate) { // set this sheet as active $this->parent->setActiveSheetIndex($this->parent->getIndex($this)); // set cell coordinate as active $this->setSelectedCells(strtoupper($pCellCoordinate)); return $this->parent->getCellXfSupervisor(); } /** * Get conditional styles for a cell. * * @param string $pCoordinate eg: 'A1' * * @return Conditional[] */ public function <API key>($pCoordinate) { $pCoordinate = strtoupper($pCoordinate); if (!isset($this-><API key>[$pCoordinate])) { $this-><API key>[$pCoordinate] = []; } return $this-><API key>[$pCoordinate]; } /** * Do conditional styles exist for this cell? * * @param string $pCoordinate eg: 'A1' * * @return bool */ public function <API key>($pCoordinate) { return isset($this-><API key>[strtoupper($pCoordinate)]); } /** * Removes conditional styles for a cell. * * @param string $pCoordinate eg: 'A1' * * @return Worksheet */ public function <API key>($pCoordinate) { unset($this-><API key>[strtoupper($pCoordinate)]); return $this; } /** * Get collection of conditional styles. * * @return array */ public function <API key>() { return $this-><API key>; } /** * Set conditional styles. * * @param string $pCoordinate eg: 'A1' * @param $pValue Conditional[] * * @return Worksheet */ public function <API key>($pCoordinate, $pValue) { $this-><API key>[strtoupper($pCoordinate)] = $pValue; return $this; } /** * Get style for cell by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the cell * @param int $row1 Numeric row coordinate of the cell * @param null|int $columnIndex2 Numeric column coordinate of the range cell * @param null|int $row2 Numeric row coordinate of the range cell * * @return Style */ public function <API key>($columnIndex1, $row1, $columnIndex2 = null, $row2 = null) { if ($columnIndex2 !== null && $row2 !== null) { $cellRange = Coordinate::<API key>($columnIndex1) . $row1 . ':' . Coordinate::<API key>($columnIndex2) . $row2; return $this->getStyle($cellRange); } return $this->getStyle(Coordinate::<API key>($columnIndex1) . $row1); } /** * Duplicate cell style to a range of cells. * * Please note that this will overwrite existing cell styles for cells in range! * * @param Style $pCellStyle Cell style to duplicate * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * * @throws Exception * * @return Worksheet */ public function duplicateStyle(Style $pCellStyle, $pRange) { // Add the style to the workbook if necessary $workbook = $this->parent; if ($existingStyle = $this->parent->getCellXfByHashCode($pCellStyle->getHashCode())) { // there is already such cell Xf in our collection $xfIndex = $existingStyle->getIndex(); } else { // we don't have such a cell Xf, need to add $workbook->addCellXf($pCellStyle); $xfIndex = $pCellStyle->getIndex(); } // Calculate range outer borders list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange . ':' . $pRange); // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { $tmp = $rangeStart; $rangeStart = $rangeEnd; $rangeEnd = $tmp; } // Loop through cells and apply styles for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { $this->getCell(Coordinate::<API key>($col) . $row)->setXfIndex($xfIndex); } } return $this; } /** * Duplicate conditional style to a range of cells. * * Please note that this will overwrite existing cell styles for cells in range! * * @param Conditional[] $pCellStyle Cell style to duplicate * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * * @throws Exception * * @return Worksheet */ public function <API key>(array $pCellStyle, $pRange = '') { foreach ($pCellStyle as $cellStyle) { if (!($cellStyle instanceof Conditional)) { throw new Exception('Style is not a conditional style'); } } // Calculate range outer borders list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange . ':' . $pRange); // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { $tmp = $rangeStart; $rangeStart = $rangeEnd; $rangeEnd = $tmp; } // Loop through cells and apply styles for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { $this-><API key>(Coordinate::<API key>($col) . $row, $pCellStyle); } } return $this; } /** * Set break on a cell. * * @param string $pCoordinate Cell coordinate (e.g. A1) * @param int $pBreak Break type (type of Worksheet::BREAK_*) * * @throws Exception * * @return Worksheet */ public function setBreak($pCoordinate, $pBreak) { // Uppercase coordinate $pCoordinate = strtoupper($pCoordinate); if ($pCoordinate != '') { if ($pBreak == self::BREAK_NONE) { if (isset($this->breaks[$pCoordinate])) { unset($this->breaks[$pCoordinate]); } } else { $this->breaks[$pCoordinate] = $pBreak; } } else { throw new Exception('No cell coordinate specified.'); } return $this; } /** * Set break on a cell by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param int $break Break type (type of Worksheet::BREAK_*) * * @return Worksheet */ public function <API key>($columnIndex, $row, $break) { return $this->setBreak(Coordinate::<API key>($columnIndex) . $row, $break); } /** * Get breaks. * * @return array[] */ public function getBreaks() { return $this->breaks; } /** * Set merge on a cell range. * * @param string $pRange Cell range (e.g. A1:E1) * * @throws Exception * * @return Worksheet */ public function mergeCells($pRange) { // Uppercase coordinate $pRange = strtoupper($pRange); if (strpos($pRange, ':') !== false) { $this->mergeCells[$pRange] = $pRange; // make sure cells are created // get the cells in the range $aReferences = Coordinate::<API key>($pRange); // create upper left cell if it does not already exist $upperLeft = $aReferences[0]; if (!$this->cellExists($upperLeft)) { $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL); } // Blank out the rest of the cells in the range (if they exist) $count = count($aReferences); for ($i = 1; $i < $count; ++$i) { if ($this->cellExists($aReferences[$i])) { $this->getCell($aReferences[$i])->setValueExplicit(null, DataType::TYPE_NULL); } } } else { throw new Exception('Merge must be set on a range of cells.'); } return $this; } /** * Set merge on a cell range by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * * @throws Exception * * @return Worksheet */ public function <API key>($columnIndex1, $row1, $columnIndex2, $row2) { $cellRange = Coordinate::<API key>($columnIndex1) . $row1 . ':' . Coordinate::<API key>($columnIndex2) . $row2; return $this->mergeCells($cellRange); } /** * Remove merge on a cell range. * * @param string $pRange Cell range (e.g. A1:E1) * * @throws Exception * * @return Worksheet */ public function unmergeCells($pRange) { // Uppercase coordinate $pRange = strtoupper($pRange); if (strpos($pRange, ':') !== false) { if (isset($this->mergeCells[$pRange])) { unset($this->mergeCells[$pRange]); } else { throw new Exception('Cell range ' . $pRange . ' not known as merged.'); } } else { throw new Exception('Merge can only be removed from a range of cells.'); } return $this; } /** * Remove merge on a cell range by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * * @throws Exception * * @return Worksheet */ public function <API key>($columnIndex1, $row1, $columnIndex2, $row2) { $cellRange = Coordinate::<API key>($columnIndex1) . $row1 . ':' . Coordinate::<API key>($columnIndex2) . $row2; return $this->unmergeCells($cellRange); } /** * Get merge cells array. * * @return array[] */ public function getMergeCells() { return $this->mergeCells; } /** * Set merge cells array for the entire sheet. Use instead mergeCells() to merge * a single cell range. * * @param array $pValue * * @return Worksheet */ public function setMergeCells(array $pValue) { $this->mergeCells = $pValue; return $this; } /** * Set protection on a cell range. * * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) * @param string $pPassword Password to unlock the protection * @param bool $pAlreadyHashed If the password has already been hashed, set this to true * * @return Worksheet */ public function protectCells($pRange, $pPassword, $pAlreadyHashed = false) { // Uppercase coordinate $pRange = strtoupper($pRange); if (!$pAlreadyHashed) { $pPassword = Shared\PasswordHasher::hashPassword($pPassword); } $this->protectedCells[$pRange] = $pPassword; return $this; } /** * Set protection on a cell range by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * @param string $password Password to unlock the protection * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return Worksheet */ public function <API key>($columnIndex1, $row1, $columnIndex2, $row2, $password, $alreadyHashed = false) { $cellRange = Coordinate::<API key>($columnIndex1) . $row1 . ':' . Coordinate::<API key>($columnIndex2) . $row2; return $this->protectCells($cellRange, $password, $alreadyHashed); } /** * Remove protection on a cell range. * * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) * * @throws Exception * * @return Worksheet */ public function unprotectCells($pRange) { // Uppercase coordinate $pRange = strtoupper($pRange); if (isset($this->protectedCells[$pRange])) { unset($this->protectedCells[$pRange]); } else { throw new Exception('Cell range ' . $pRange . ' not known as protected.'); } return $this; } /** * Remove protection on a cell range by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * * @throws Exception * * @return Worksheet */ public function <API key>($columnIndex1, $row1, $columnIndex2, $row2) { $cellRange = Coordinate::<API key>($columnIndex1) . $row1 . ':' . Coordinate::<API key>($columnIndex2) . $row2; return $this->unprotectCells($cellRange); } /** * Get protected cells. * * @return array[] */ public function getProtectedCells() { return $this->protectedCells; } /** * Get Autofilter. * * @return AutoFilter */ public function getAutoFilter() { return $this->autoFilter; } /** * Set AutoFilter. * * @param AutoFilter|string $pValue * A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility * * @throws Exception * * @return Worksheet */ public function setAutoFilter($pValue) { if (is_string($pValue)) { $this->autoFilter->setRange($pValue); } elseif (is_object($pValue) && ($pValue instanceof AutoFilter)) { $this->autoFilter = $pValue; } return $this; } /** * Set Autofilter Range by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the second cell * @param int $row2 Numeric row coordinate of the second cell * * @throws Exception * * @return Worksheet */ public function <API key>($columnIndex1, $row1, $columnIndex2, $row2) { return $this->setAutoFilter( Coordinate::<API key>($columnIndex1) . $row1 . ':' . Coordinate::<API key>($columnIndex2) . $row2 ); } /** * Remove autofilter. * * @return Worksheet */ public function removeAutoFilter() { $this->autoFilter->setRange(null); return $this; } /** * Get Freeze Pane. * * @return string */ public function getFreezePane() { return $this->freezePane; } /** * Freeze Pane. * * Examples: * * - A2 will freeze the rows above cell A2 (i.e row 1) * - B1 will freeze the columns to the left of cell B1 (i.e column A) * - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A) * * @param null|string $cell Position of the split * @param null|string $topLeftCell default position of the right bottom pane * * @throws Exception * * @return Worksheet */ public function freezePane($cell, $topLeftCell = null) { if (is_string($cell) && Coordinate::coordinateIsRange($cell)) { throw new Exception('Freeze pane can not be set on a range of cells.'); } if ($cell !== null && $topLeftCell === null) { $coordinate = Coordinate::<API key>($cell); $topLeftCell = $coordinate[0] . $coordinate[1]; } $this->freezePane = $cell; $this->topLeftCell = $topLeftCell; return $this; } /** * Freeze Pane by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @return Worksheet */ public function <API key>($columnIndex, $row) { return $this->freezePane(Coordinate::<API key>($columnIndex) . $row); } /** * Unfreeze Pane. * * @return Worksheet */ public function unfreezePane() { return $this->freezePane(null); } /** * Get the default position of the right bottom pane. * * @return int */ public function getTopLeftCell() { return $this->topLeftCell; } /** * Insert a new row, updating all possible related data. * * @param int $pBefore Insert before this one * @param int $pNumRows Number of rows to insert * * @throws Exception * * @return Worksheet */ public function insertNewRowBefore($pBefore, $pNumRows = 1) { if ($pBefore >= 1) { $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this); } else { throw new Exception('Rows can only be inserted before at least row 1.'); } return $this; } /** * Insert a new column, updating all possible related data. * * @param string $pBefore Insert before this one, eg: 'A' * @param int $pNumCols Number of columns to insert * * @throws Exception * * @return Worksheet */ public function <API key>($pBefore, $pNumCols = 1) { if (!is_numeric($pBefore)) { $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this); } else { throw new Exception('Column references should not be numeric.'); } return $this; } /** * Insert a new column, updating all possible related data. * * @param int $beforeColumnIndex Insert before this one (numeric column coordinate of the cell) * @param int $pNumCols Number of columns to insert * * @throws Exception * * @return Worksheet */ public function <API key>($beforeColumnIndex, $pNumCols = 1) { if ($beforeColumnIndex >= 1) { return $this-><API key>(Coordinate::<API key>($beforeColumnIndex), $pNumCols); } throw new Exception('Columns can only be inserted before at least column A (1).'); } /** * Delete a row, updating all possible related data. * * @param int $pRow Remove starting with this one * @param int $pNumRows Number of rows to remove * * @throws Exception * * @return Worksheet */ public function removeRow($pRow, $pNumRows = 1) { if ($pRow >= 1) { $highestRow = $this->getHighestDataRow(); $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this); for ($r = 0; $r < $pNumRows; ++$r) { $this->getCellCollection()->removeRow($highestRow); --$highestRow; } } else { throw new Exception('Rows to be deleted should at least start from row 1.'); } return $this; } /** * Remove a column, updating all possible related data. * * @param string $pColumn Remove starting with this one, eg: 'A' * @param int $pNumCols Number of columns to remove * * @throws Exception * * @return Worksheet */ public function removeColumn($pColumn, $pNumCols = 1) { if (!is_numeric($pColumn)) { $highestColumn = $this-><API key>(); $pColumn = Coordinate::<API key>(Coordinate::<API key>($pColumn) + $pNumCols); $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this); for ($c = 0; $c < $pNumCols; ++$c) { $this->getCellCollection()->removeColumn($highestColumn); $highestColumn = Coordinate::<API key>(Coordinate::<API key>($highestColumn) - 1); } } else { throw new Exception('Column references should not be numeric.'); } return $this; } /** * Remove a column, updating all possible related data. * * @param int $columnIndex Remove starting with this one (numeric column coordinate of the cell) * @param int $numColumns Number of columns to remove * * @throws Exception * * @return Worksheet */ public function removeColumnByIndex($columnIndex, $numColumns = 1) { if ($columnIndex >= 1) { return $this->removeColumn(Coordinate::<API key>($columnIndex), $numColumns); } throw new Exception('Columns to be deleted should at least start from column A (1)'); } /** * Show gridlines? * * @return bool */ public function getShowGridlines() { return $this->showGridlines; } /** * Set show gridlines. * * @param bool $pValue Show gridlines (true/false) * * @return Worksheet */ public function setShowGridlines($pValue) { $this->showGridlines = $pValue; return $this; } /** * Print gridlines? * * @return bool */ public function getPrintGridlines() { return $this->printGridlines; } /** * Set print gridlines. * * @param bool $pValue Print gridlines (true/false) * * @return Worksheet */ public function setPrintGridlines($pValue) { $this->printGridlines = $pValue; return $this; } /** * Show row and column headers? * * @return bool */ public function <API key>() { return $this->showRowColHeaders; } /** * Set show row and column headers. * * @param bool $pValue Show row and column headers (true/false) * * @return Worksheet */ public function <API key>($pValue) { $this->showRowColHeaders = $pValue; return $this; } /** * Show summary below? (Row/Column outlining). * * @return bool */ public function getShowSummaryBelow() { return $this->showSummaryBelow; } /** * Set show summary below. * * @param bool $pValue Show summary below (true/false) * * @return Worksheet */ public function setShowSummaryBelow($pValue) { $this->showSummaryBelow = $pValue; return $this; } /** * Show summary right? (Row/Column outlining). * * @return bool */ public function getShowSummaryRight() { return $this->showSummaryRight; } /** * Set show summary right. * * @param bool $pValue Show summary right (true/false) * * @return Worksheet */ public function setShowSummaryRight($pValue) { $this->showSummaryRight = $pValue; return $this; } /** * Get comments. * * @return Comment[] */ public function getComments() { return $this->comments; } /** * Set comments array for the entire sheet. * * @param Comment[] $pValue * * @return Worksheet */ public function setComments(array $pValue) { $this->comments = $pValue; return $this; } /** * Get comment for cell. * * @param string $pCellCoordinate Cell coordinate to get comment for, eg: 'A1' * * @throws Exception * * @return Comment */ public function getComment($pCellCoordinate) { // Uppercase coordinate $pCellCoordinate = strtoupper($pCellCoordinate); if (Coordinate::coordinateIsRange($pCellCoordinate)) { throw new Exception('Cell coordinate string can not be a range of cells.'); } elseif (strpos($pCellCoordinate, '$') !== false) { throw new Exception('Cell coordinate string must not be absolute.'); } elseif ($pCellCoordinate == '') { throw new Exception('Cell coordinate can not be zero-length string.'); } // Check if we already have a comment for this cell. if (isset($this->comments[$pCellCoordinate])) { return $this->comments[$pCellCoordinate]; } // If not, create a new comment. $newComment = new Comment(); $this->comments[$pCellCoordinate] = $newComment; return $newComment; } /** * Get comment for cell by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @return Comment */ public function <API key>($columnIndex, $row) { return $this->getComment(Coordinate::<API key>($columnIndex) . $row); } /** * Get active cell. * * @return string Example: 'A1' */ public function getActiveCell() { return $this->activeCell; } /** * Get selected cells. * * @return string */ public function getSelectedCells() { return $this->selectedCells; } /** * Selected cell. * * @param string $pCoordinate Cell (i.e. A1) * * @return Worksheet */ public function setSelectedCell($pCoordinate) { return $this->setSelectedCells($pCoordinate); } /** * Select a range of cells. * * @param string $pCoordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6' * * @return Worksheet */ public function setSelectedCells($pCoordinate) { // Uppercase coordinate $pCoordinate = strtoupper($pCoordinate); // Convert 'A' to 'A:A' $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate); // Convert '1' to '1:1' $pCoordinate = preg_replace('/^(\d+)$/', '${1}:${1}', $pCoordinate); // Convert 'A:C' to 'A1:C1048576' $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate); // Convert '1:3' to 'A1:XFD3' $pCoordinate = preg_replace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $pCoordinate); if (Coordinate::coordinateIsRange($pCoordinate)) { list($first) = Coordinate::splitRange($pCoordinate); $this->activeCell = $first[0]; } else { $this->activeCell = $pCoordinate; } $this->selectedCells = $pCoordinate; return $this; } /** * Selected cell by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @throws Exception * * @return Worksheet */ public function <API key>($columnIndex, $row) { return $this->setSelectedCells(Coordinate::<API key>($columnIndex) . $row); } /** * Get right-to-left. * * @return bool */ public function getRightToLeft() { return $this->rightToLeft; } /** * Set right-to-left. * * @param bool $value Right-to-left true/false * * @return Worksheet */ public function setRightToLeft($value) { $this->rightToLeft = $value; return $this; } /** * Fill worksheet from values in array. * * @param array $source Source array * @param mixed $nullValue Value in source array that stands for blank cell * @param string $startCell Insert array starting from this cell address as the top left coordinate * @param bool $<API key> Apply strict comparison when testing for null values in the array * * @throws Exception * * @return Worksheet */ public function fromArray(array $source, $nullValue = null, $startCell = 'A1', $<API key> = false) { // Convert a 1-D array to 2-D (for ease of looping) if (!is_array(end($source))) { $source = [$source]; } // start coordinate list($startColumn, $startRow) = Coordinate::<API key>($startCell); // Loop through $source foreach ($source as $rowData) { $currentColumn = $startColumn; foreach ($rowData as $cellValue) { if ($<API key>) { if ($cellValue !== $nullValue) { // Set cell value $this->getCell($currentColumn . $startRow)->setValue($cellValue); } } else { if ($cellValue != $nullValue) { // Set cell value $this->getCell($currentColumn . $startRow)->setValue($cellValue); } } ++$currentColumn; } ++$startRow; } return $this; } /** * Create array from a range of cells. * * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * * @return array */ public function rangeToArray($pRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { // Returnvalue $returnValue = []; // Identify the range that we need to extract from the worksheet list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange); $minCol = Coordinate::<API key>($rangeStart[0]); $minRow = $rangeStart[1]; $maxCol = Coordinate::<API key>($rangeEnd[0]); $maxRow = $rangeEnd[1]; ++$maxCol; // Loop through rows $r = -1; for ($row = $minRow; $row <= $maxRow; ++$row) { $rRef = ($returnCellRef) ? $row : ++$r; $c = -1; // Loop through columns in the current row for ($col = $minCol; $col != $maxCol; ++$col) { $cRef = ($returnCellRef) ? $col : ++$c; // Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen // so we test and retrieve directly against cellCollection if ($this->cellCollection->has($col . $row)) { // Cell exists $cell = $this->cellCollection->get($col . $row); if ($cell->getValue() !== null) { if ($cell->getValue() instanceof RichText) { $returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText(); } else { if ($calculateFormulas) { $returnValue[$rRef][$cRef] = $cell->getCalculatedValue(); } else { $returnValue[$rRef][$cRef] = $cell->getValue(); } } if ($formatData) { $style = $this->parent->getCellXfByIndex($cell->getXfIndex()); $returnValue[$rRef][$cRef] = NumberFormat::toFormattedString( $returnValue[$rRef][$cRef], ($style && $style->getNumberFormat()) ? $style->getNumberFormat()->getFormatCode() : NumberFormat::FORMAT_GENERAL ); } } else { // Cell holds a NULL $returnValue[$rRef][$cRef] = $nullValue; } } else { // Cell doesn't exist $returnValue[$rRef][$cRef] = $nullValue; } } } // Return return $returnValue; } /** * Create array from a range of cells. * * @param string $pNamedRange Name of the Named Range * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * * @throws Exception * * @return array */ public function namedRangeToArray($pNamedRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { $namedRange = NamedRange::resolveRange($pNamedRange, $this); if ($namedRange !== null) { $pWorkSheet = $namedRange->getWorksheet(); $pCellRange = $namedRange->getRange(); return $pWorkSheet->rangeToArray($pCellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef); } throw new Exception('Named Range ' . $pNamedRange . ' does not exist.'); } /** * Create array from worksheet. * * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * * @return array */ public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { // Garbage collect... $this->garbageCollect(); // Identify the range that we need to extract from the worksheet $maxCol = $this->getHighestColumn(); $maxRow = $this->getHighestRow(); // Return return $this->rangeToArray('A1:' . $maxCol . $maxRow, $nullValue, $calculateFormulas, $formatData, $returnCellRef); } /** * Get row iterator. * * @param int $startRow The row number at which to start iterating * @param int $endRow The row number at which to stop iterating * * @return RowIterator */ public function getRowIterator($startRow = 1, $endRow = null) { return new RowIterator($this, $startRow, $endRow); } /** * Get column iterator. * * @param string $startColumn The column address at which to start iterating * @param string $endColumn The column address at which to stop iterating * * @return ColumnIterator */ public function getColumnIterator($startColumn = 'A', $endColumn = null) { return new ColumnIterator($this, $startColumn, $endColumn); } /** * Run PhpSpreadsheet garbage collector. * * @return Worksheet */ public function garbageCollect() { // Flush cache $this->cellCollection->get('A1'); // Lookup highest column and highest row if cells are cleaned $colRow = $this->cellCollection-><API key>(); $highestRow = $colRow['row']; $highestColumn = Coordinate::<API key>($colRow['column']); // Loop through column dimensions foreach ($this->columnDimensions as $dimension) { $highestColumn = max($highestColumn, Coordinate::<API key>($dimension->getColumnIndex())); } // Loop through row dimensions foreach ($this->rowDimensions as $dimension) { $highestRow = max($highestRow, $dimension->getRowIndex()); } // Cache values if ($highestColumn < 1) { $this->cachedHighestColumn = 'A'; } else { $this->cachedHighestColumn = Coordinate::<API key>($highestColumn); } $this->cachedHighestRow = $highestRow; // Return return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { if ($this->dirty) { $this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__); $this->dirty = false; } return $this->hash; } /** * Extract worksheet title from range. * * Example: extractSheetTitle("testSheet!A1") ==> 'A1' * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1']; * * @param string $pRange Range to extract title from * @param bool $returnRange Return range? (see example) * * @return mixed */ public static function extractSheetTitle($pRange, $returnRange = false) { // Sheet title included? if (($sep = strrpos($pRange, '!')) === false) { return $returnRange ? ['', $pRange] : ''; } if ($returnRange) { return [substr($pRange, 0, $sep), substr($pRange, $sep + 1)]; } return substr($pRange, $sep + 1); } /** * Get hyperlink. * * @param string $pCellCoordinate Cell coordinate to get hyperlink for, eg: 'A1' * * @return Hyperlink */ public function getHyperlink($pCellCoordinate) { // return hyperlink if we already have one if (isset($this->hyperlinkCollection[$pCellCoordinate])) { return $this->hyperlinkCollection[$pCellCoordinate]; } // else create hyperlink $this->hyperlinkCollection[$pCellCoordinate] = new Hyperlink(); return $this->hyperlinkCollection[$pCellCoordinate]; } /** * Set hyperlink. * * @param string $pCellCoordinate Cell coordinate to insert hyperlink, eg: 'A1' * @param null|Hyperlink $pHyperlink * * @return Worksheet */ public function setHyperlink($pCellCoordinate, Hyperlink $pHyperlink = null) { if ($pHyperlink === null) { unset($this->hyperlinkCollection[$pCellCoordinate]); } else { $this->hyperlinkCollection[$pCellCoordinate] = $pHyperlink; } return $this; } /** * Hyperlink at a specific coordinate exists? * * @param string $pCoordinate eg: 'A1' * * @return bool */ public function hyperlinkExists($pCoordinate) { return isset($this->hyperlinkCollection[$pCoordinate]); } /** * Get collection of hyperlinks. * * @return Hyperlink[] */ public function <API key>() { return $this->hyperlinkCollection; } /** * Get data validation. * * @param string $pCellCoordinate Cell coordinate to get data validation for, eg: 'A1' * * @return DataValidation */ public function getDataValidation($pCellCoordinate) { // return data validation if we already have one if (isset($this-><API key>[$pCellCoordinate])) { return $this-><API key>[$pCellCoordinate]; } // else create data validation $this-><API key>[$pCellCoordinate] = new DataValidation(); return $this-><API key>[$pCellCoordinate]; } /** * Set data validation. * * @param string $pCellCoordinate Cell coordinate to insert data validation, eg: 'A1' * @param null|DataValidation $pDataValidation * * @return Worksheet */ public function setDataValidation($pCellCoordinate, DataValidation $pDataValidation = null) { if ($pDataValidation === null) { unset($this-><API key>[$pCellCoordinate]); } else { $this-><API key>[$pCellCoordinate] = $pDataValidation; } return $this; } /** * Data validation at a specific coordinate exists? * * @param string $pCoordinate eg: 'A1' * * @return bool */ public function <API key>($pCoordinate) { return isset($this-><API key>[$pCoordinate]); } /** * Get collection of data validations. * * @return DataValidation[] */ public function <API key>() { return $this-><API key>; } /** * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet. * * @param string $range * * @return string Adjusted range value */ public function shrinkRangeToFit($range) { $maxCol = $this->getHighestColumn(); $maxRow = $this->getHighestRow(); $maxCol = Coordinate::<API key>($maxCol); $rangeBlocks = explode(' ', $range); foreach ($rangeBlocks as &$rangeSet) { $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet); if (Coordinate::<API key>($rangeBoundaries[0][0]) > $maxCol) { $rangeBoundaries[0][0] = Coordinate::<API key>($maxCol); } if ($rangeBoundaries[0][1] > $maxRow) { $rangeBoundaries[0][1] = $maxRow; } if (Coordinate::<API key>($rangeBoundaries[1][0]) > $maxCol) { $rangeBoundaries[1][0] = Coordinate::<API key>($maxCol); } if ($rangeBoundaries[1][1] > $maxRow) { $rangeBoundaries[1][1] = $maxRow; } $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1]; } unset($rangeSet); $stRange = implode(' ', $rangeBlocks); return $stRange; } /** * Get tab color. * * @return Color */ public function getTabColor() { if ($this->tabColor === null) { $this->tabColor = new Color(); } return $this->tabColor; } /** * Reset tab color. * * @return Worksheet */ public function resetTabColor() { $this->tabColor = null; unset($this->tabColor); return $this; } /** * Tab color set? * * @return bool */ public function isTabColorSet() { return $this->tabColor !== null; } /** * Copy worksheet (!= clone!). * * @return Worksheet */ public function copy() { $copied = clone $this; return $copied; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { foreach ($this as $key => $val) { if ($key == 'parent') { continue; } if (is_object($val) || (is_array($val))) { if ($key == 'cellCollection') { $newCollection = $this->cellCollection->cloneCellCollection($this); $this->cellCollection = $newCollection; } elseif ($key == 'drawingCollection') { $currentCollection = $this->drawingCollection; $this->drawingCollection = new ArrayObject(); foreach ($currentCollection as $item) { if (is_object($item)) { $newDrawing = clone $item; $newDrawing->setWorksheet($this); } } } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) { $newAutoFilter = clone $this->autoFilter; $this->autoFilter = $newAutoFilter; $this->autoFilter->setParent($this); } else { $this->{$key} = unserialize(serialize($val)); } } } } /** * Define the code name of the sheet. * * @param string $pValue Same rule as Title minus space not allowed (but, like Excel, change * silently space to underscore) * @param bool $validate False to skip validation of new title. WARNING: This should only be set * at parse time (by Readers), where titles can be assumed to be valid. * * @throws Exception * * @return Worksheet */ public function setCodeName($pValue, $validate = true) { // Is this a 'rename' or not? if ($this->getCodeName() == $pValue) { return $this; } if ($validate) { $pValue = str_replace(' ', '_', $pValue); //Excel does this automatically without flinching, we are doing the same // Syntax check // throw an exception if not valid self::checkSheetCodeName($pValue); // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_' if ($this->getParent()) { // Is there already such sheet name? if ($this->getParent()->sheetCodeNameExists($pValue)) { // Use name, but append with lowest possible integer if (Shared\StringHelper::countCharacters($pValue) > 29) { $pValue = Shared\StringHelper::substring($pValue, 0, 29); } $i = 1; while ($this->getParent()->sheetCodeNameExists($pValue . '_' . $i)) { ++$i; if ($i == 10) { if (Shared\StringHelper::countCharacters($pValue) > 28) { $pValue = Shared\StringHelper::substring($pValue, 0, 28); } } elseif ($i == 100) { if (Shared\StringHelper::countCharacters($pValue) > 27) { $pValue = Shared\StringHelper::substring($pValue, 0, 27); } } } $pValue = $pValue . '_' . $i; // ok, we have a valid name } } } $this->codeName = $pValue; return $this; } /** * Return the code name of the sheet. * * @return null|string */ public function getCodeName() { return $this->codeName; } /** * Sheet has a code name ? * * @return bool */ public function hasCodeName() { return $this->codeName !== null; } }
import {addClass, hasClass, empty} from './../helpers/dom/element'; import {eventManager as eventManagerObject} from './../eventManager'; import {getRenderer, registerRenderer} from './../renderers'; import {<API key>} from './../3rdparty/walkontable/src/cell/coords'; var clonableWRAPPER = document.createElement('DIV'); clonableWRAPPER.className = '<API key>'; var clonableARROW = document.createElement('DIV'); clonableARROW.className = 'htAutocompleteArrow'; clonableARROW.appendChild(document.createTextNode(String.fromCharCode(9660))); var <API key> = function(TD, WRAPPER) { WRAPPER.innerHTML = TD.innerHTML; empty(TD); TD.appendChild(WRAPPER); }; /** * Autocomplete renderer * * @private * @renderer <API key> * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ function <API key>(instance, TD, row, col, prop, value, cellProperties) { var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement getRenderer('text')(instance, TD, row, col, prop, value, cellProperties); TD.appendChild(ARROW); addClass(TD, 'htAutocomplete'); if (!TD.firstChild) { //otherwise empty fields appear borderless in demo/renderers.html (IE) TD.appendChild(document.createTextNode(String.fromCharCode(160))); } if (!instance.acArrowListener) { var eventManager = eventManagerObject(instance); //not very elegant but easy and fast instance.acArrowListener = function(event) { if (hasClass(event.target, 'htAutocompleteArrow')) { instance.view.wt.getSetting('onCellDblClick', null, new <API key>(row, col), TD); } }; eventManager.addEventListener(instance.rootElement, 'mousedown', instance.acArrowListener); //We need to unbind the listener after the table has been destroyed instance.addHookOnce('afterDestroy', function() { eventManager.destroy(); }); } } export {<API key>}; registerRenderer('autocomplete', <API key>);
namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Security; using SR = System.ServiceModel.SR; sealed class <API key><TChannel> : <API key><TChannel>, <API key> { <API key> flowIssuedTokens; <API key> standardsManager; Dictionary<DirectionalAction, <API key>> dictionary; TransactionProtocol transactionProtocol; bool allowWildcardAction; public <API key>( TransactionProtocol transactionProtocol, BindingContext context, Dictionary<DirectionalAction, <API key>> dictionary, bool allowWildcardAction) : base(context.Binding, context.<API key><TChannel>()) { this.dictionary = dictionary; this.TransactionProtocol = transactionProtocol; this.allowWildcardAction = allowWildcardAction; this.standardsManager = <API key>.<API key>(this.TransactionProtocol); } public TransactionProtocol TransactionProtocol { get { return this.transactionProtocol; } set { if (!TransactionProtocol.IsDefined(value)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException(SR.GetString(SR.<API key>))); this.transactionProtocol = value; } } public <API key> FlowIssuedTokens { get { return this.flowIssuedTokens; } set { this.flowIssuedTokens = value; } } public <API key> StandardsManager { get { return this.standardsManager; } set { this.standardsManager = (value != null ? value : <API key>.<API key>(this.transactionProtocol)); } } public IDictionary<DirectionalAction, <API key>> Dictionary { get { return this.dictionary; } } public <API key> GetTransaction(MessageDirection direction, string action) { <API key> txOption; if (!dictionary.TryGetValue(new DirectionalAction(direction, action), out txOption)) { //Fixinng this for clients that opted in for lesser validation before flowing out a transaction if (this.allowWildcardAction && dictionary.TryGetValue(new DirectionalAction(direction, MessageHeaders.WildcardAction), out txOption)) { return txOption; } else return <API key>.NotAllowed; } else return txOption; } protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via) { TChannel innerChannel = ((IChannelFactory<TChannel>)InnerChannelFactory).CreateChannel(remoteAddress, via); return <API key>(innerChannel); } TChannel <API key>(TChannel innerChannel) { if (typeof(TChannel) == typeof(<API key>)) { return (TChannel)(object)new <API key>(this, (<API key>)(object)innerChannel); } else if (typeof(TChannel) == typeof(<API key>)) { return (TChannel)(object)new <API key>(this, (<API key>)(object)innerChannel); } else if (typeof(TChannel) == typeof(<API key>)) { return (TChannel)(object)new <API key>(this, (<API key>)(object)innerChannel); } else if (typeof(TChannel) == typeof(IOutputChannel)) { return (TChannel)(object)new <API key>(this, (IOutputChannel)(object)innerChannel); } else if (typeof(TChannel) == typeof(IRequestChannel)) { return (TChannel)(object)new <API key>(this, (IRequestChannel)(object)innerChannel); } else if (typeof(TChannel) == typeof(IDuplexChannel)) { return (TChannel)(object)new <API key>(this, (IDuplexChannel)(object)innerChannel); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(<API key>(typeof(TChannel))); } } // Transaction Output Channel classes sealed class <API key> : <API key><IOutputChannel> { public <API key>(ChannelManagerBase channelManager, IOutputChannel innerChannel) : base(channelManager, innerChannel) { } } sealed class <API key> : <API key><IRequestChannel> { public <API key>(ChannelManagerBase channelManager, IRequestChannel innerChannel) : base(channelManager, innerChannel) { } } sealed class <API key> : <API key><IDuplexChannel> { public <API key>(ChannelManagerBase channelManager, IDuplexChannel innerChannel) : base(channelManager, innerChannel) { } } sealed class <API key> : <API key><<API key>>, <API key> { public <API key>(ChannelManagerBase channelManager, <API key> innerChannel) : base(channelManager, innerChannel) { } public IOutputSession Session { get { return InnerChannel.Session; } } } sealed class <API key> : <API key><<API key>>, <API key> { public <API key>(ChannelManagerBase channelManager, <API key> innerChannel) : base(channelManager, innerChannel) { } public IOutputSession Session { get { return InnerChannel.Session; } } } sealed class <API key> : <API key><<API key>>, <API key> { public <API key>(ChannelManagerBase channelManager, <API key> innerChannel) : base(channelManager, innerChannel) { } public IDuplexSession Session { get { return InnerChannel.Session; } } } } static class <API key> { static <API key> <API key> = <API key>(<API key>.<API key>); static <API key> <API key>(<API key> securityVersion) { return new <API key>( securityVersion, new <API key>(securityVersion.SecurityVersion, securityVersion.TrustVersion, securityVersion.<API key>, false, null, null, null)); } public static <API key> <API key>(TransactionProtocol transactionProtocol) { if (transactionProtocol == TransactionProtocol.<API key> || transactionProtocol == TransactionProtocol.OleTransactions) { return <API key>.DefaultInstance; } else { return <API key>.<API key>; } } } // Transaction channel base generic classes class <API key><TChannel> : TransactionChannel<TChannel>, IOutputChannel where TChannel : class, IOutputChannel { public <API key>(ChannelManagerBase channelManager, TChannel innerChannel) : base(channelManager, innerChannel) { } public EndpointAddress RemoteAddress { get { return InnerChannel.RemoteAddress; } } public Uri Via { get { return InnerChannel.Via; } } public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state) { return this.BeginSend(message, this.DefaultSendTimeout, callback, state); } public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback asyncCallback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); <API key>(message, MessageDirection.Input); return InnerChannel.BeginSend(message, timeoutHelper.RemainingTime(), asyncCallback, state); } public void EndSend(IAsyncResult result) { InnerChannel.EndSend(result); } public void Send(Message message) { this.Send(message, this.DefaultSendTimeout); } public void Send(Message message, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); <API key>(message, MessageDirection.Input); InnerChannel.Send(message, timeoutHelper.RemainingTime()); } } class <API key><TChannel> : TransactionChannel<TChannel>, IRequestChannel where TChannel : class, IRequestChannel { public <API key>(ChannelManagerBase channelManager, TChannel innerChannel) : base(channelManager, innerChannel) { } public EndpointAddress RemoteAddress { get { return InnerChannel.RemoteAddress; } } public Uri Via { get { return InnerChannel.Via; } } public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state) { return this.BeginRequest(message, this.DefaultSendTimeout, callback, state); } public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback asyncCallback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); <API key>(message, MessageDirection.Input); return InnerChannel.BeginRequest(message, timeoutHelper.RemainingTime(), asyncCallback, state); } public Message EndRequest(IAsyncResult result) { Message reply = InnerChannel.EndRequest(result); if (reply != null) this.ReadIssuedTokens(reply, MessageDirection.Output); return reply; } public Message Request(Message message) { return this.Request(message, this.DefaultSendTimeout); } public Message Request(Message message, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); <API key>(message, MessageDirection.Input); Message reply = InnerChannel.Request(message, timeoutHelper.RemainingTime()); if (reply != null) this.ReadIssuedTokens(reply, MessageDirection.Output); return reply; } } class <API key><TChannel> : <API key><TChannel> where TChannel : class, IDuplexChannel { public <API key>(ChannelManagerBase channelManager, TChannel innerChannel) : base(channelManager, innerChannel, MessageDirection.Output) { } } }
#include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> typedef struct { uint32_t percent; <API key> value; } <API key>; typedef struct { <API key> value; ngx_array_t parts; } <API key>; static char *<API key>(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static char *<API key>(ngx_conf_t *cf, ngx_command_t *dummy, void *conf); static ngx_command_t <API key>[] = { { ngx_string("split_clients"), NGX_HTTP_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_TAKE2, <API key>, <API key>, 0, NULL }, ngx_null_command }; static ngx_http_module_t <API key> = { NULL, /* preconfiguration */ NULL, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL /* merge location configuration */ }; ngx_module_t <API key> = { NGX_MODULE_V1, &<API key>, /* module context */ <API key>, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ <API key> }; static ngx_int_t <API key>(ngx_http_request_t *r, <API key> *v, uintptr_t data) { <API key> *ctx = (<API key> *) data; uint32_t hash; ngx_str_t val; ngx_uint_t i; <API key> *part; *v = <API key>; if (<API key>(r, &ctx->value, &val) != NGX_OK) { return NGX_OK; } hash = ngx_murmur_hash2(val.data, val.len); part = ctx->parts.elts; for (i = 0; i < ctx->parts.nelts; i++) { ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http split: %uD %uD", hash, part[i].percent); if (hash < part[i].percent) { *v = part[i].value; return NGX_OK; } } return NGX_OK; } static char * <API key>(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { char *rv; ngx_str_t *value, name; ngx_uint_t i, sum, last; ngx_conf_t save; ngx_http_variable_t *var; <API key> *ctx; <API key> *part; <API key> ccv; ctx = ngx_pcalloc(cf->pool, sizeof(<API key>)); if (ctx == NULL) { return NGX_CONF_ERROR; } value = cf->args->elts; ngx_memzero(&ccv, sizeof(<API key>)); ccv.cf = cf; ccv.value = &value[1]; ccv.complex_value = &ctx->value; if (<API key>(&ccv) != NGX_OK) { return NGX_CONF_ERROR; } name = value[2]; name.len name.data++; var = <API key>(cf, &name, <API key>); if (var == NULL) { return NGX_CONF_ERROR; } var->get_handler = <API key>; var->data = (uintptr_t) ctx; if (ngx_array_init(&ctx->parts, cf->pool, 2, sizeof(<API key>)) != NGX_OK) { return NGX_CONF_ERROR; } save = *cf; cf->ctx = ctx; cf->handler = <API key>; cf->handler_conf = conf; rv = ngx_conf_parse(cf, NULL); *cf = save; if (rv != NGX_CONF_OK) { return rv; } sum = 0; last = 0; part = ctx->parts.elts; for (i = 0; i < ctx->parts.nelts; i++) { sum = part[i].percent ? sum + part[i].percent : 10000; if (sum > 10000) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "percent sum is more than 100%%"); return NGX_CONF_ERROR; } if (part[i].percent) { part[i].percent = (uint32_t) (last + 0xffffffff / 10000 * part[i].percent); } else { part[i].percent = 0xffffffff; } last = part[i].percent; } return rv; } static char * <API key>(ngx_conf_t *cf, ngx_command_t *dummy, void *conf) { ngx_int_t n; ngx_str_t *value; <API key> *ctx; <API key> *part; ctx = cf->ctx; value = cf->args->elts; part = ngx_array_push(&ctx->parts); if (part == NULL) { return NGX_CONF_ERROR; } if (value[0].len == 1 && value[0].data[0] == '*') { part->percent = 0; } else { if (value[0].data[value[0].len - 1] != '%') { goto invalid; } n = ngx_atofp(value[0].data, value[0].len - 1, 2); if (n == NGX_ERROR || n == 0) { goto invalid; } part->percent = (uint32_t) n; } part->value.len = value[1].len; part->value.valid = 1; part->value.no_cacheable = 0; part->value.not_found = 0; part->value.data = value[1].data; return NGX_CONF_OK; invalid: ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "invalid percent value \"%V\"", &value[0]); return NGX_CONF_ERROR; }
module Jekyll class TagIndex < Page def initialize(site, base, dir, tag) @site = site @base = base @dir = dir @name = 'index.html' self.process(@name) self.read_yaml(File.join(base, '_layouts'), 'tag_index.html') self.data['tag'] = tag self.data['title'] = "Posts Tagged &ldquo;"+tag+"&rdquo;" end end class TagGenerator < Generator safe true def generate(site) if site.layouts.key? 'tag_index' dir = 'tags' site.tags.keys.each do |tag| write_tag_index(site, File.join(dir, tag), tag) end end end def write_tag_index(site, dir, tag) index = TagIndex.new(site, site.source, dir, tag) index.render(site.layouts, site.site_payload) index.write(site.dest) site.pages << index end end end
// this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef SOL_DEMANGLE_HPP #define SOL_DEMANGLE_HPP #include <string> #include <array> #include <cctype> namespace sol { namespace detail { #ifdef _MSC_VER template <typename T> inline std::string ctti_get_type_name() { const static std::array<std::string, 7> removals = { { "public:", "private:", "protected:", "struct ", "class ", "`anonymous-namespace'", "`anonymous namespace'" } }; std::string name = __FUNCSIG__; std::size_t start = name.find("get_type_name"); if (start == std::string::npos) start = 0; else start += 13; if (start < name.size() - 1) start += 1; std::size_t end = name.find_last_of('>'); if (end == std::string::npos) end = name.size(); name = name.substr(start, end - start); if (name.find("struct", 0) == 0) name.replace(0, 6, "", 0); if (name.find("class", 0) == 0) name.replace(0, 5, "", 0); while (!name.empty() && std::isblank(name.front())) name.erase(name.begin()); while (!name.empty() && std::isblank(name.back())) name.pop_back(); for (std::size_t r = 0; r < removals.size(); ++r) { auto found = name.find(removals[r]); while (found != std::string::npos) { name.erase(found, removals[r].size()); found = name.find(removals[r]); } } return name; } #elif defined(__GNUC__) || defined(__clang__) template <typename T, class seperator_mark = int> inline std::string ctti_get_type_name() { const static std::array<std::string, 2> removals = { { "{anonymous}", "(anonymous namespace)" } }; std::string name = __PRETTY_FUNCTION__; std::size_t start = name.find_first_of('['); start = name.find_first_of('=', start); std::size_t end = name.find_last_of(']'); if (end == std::string::npos) end = name.size(); if (start == std::string::npos) start = 0; if (start < name.size() - 1) start += 1; name = name.substr(start, end - start); start = name.rfind("seperator_mark"); if (start != std::string::npos) { name.erase(start - 2, name.length()); } while (!name.empty() && std::isblank(name.front())) name.erase(name.begin()); while (!name.empty() && std::isblank(name.back())) name.pop_back(); for (std::size_t r = 0; r < removals.size(); ++r) { auto found = name.find(removals[r]); while (found != std::string::npos) { name.erase(found, removals[r].size()); found = name.find(removals[r]); } } return name; } #else #error Compiler not supported for demangling #endif // compilers template <typename T> inline std::string demangle_once() { std::string realname = ctti_get_type_name<T>(); return realname; } template <typename T> inline std::string short_demangle_once() { std::string realname = ctti_get_type_name<T>(); // This isn't the most complete but it'll do for now...? static const std::array<std::string, 10> ops = { { "operator<", "operator<<", "operator<<=", "operator<=", "operator>", "operator>>", "operator>>=", "operator>=", "operator->", "operator->*" } }; int level = 0; std::ptrdiff_t idx = 0; for (idx = static_cast<std::ptrdiff_t>(realname.empty() ? 0 : realname.size() - 1); idx > 0; --idx) { if (level == 0 && realname[idx] == ':') { break; } bool isleft = realname[idx] == '<'; bool isright = realname[idx] == '>'; if (!isleft && !isright) continue; bool earlybreak = false; for (const auto& op : ops) { std::size_t nisop = realname.rfind(op, idx); if (nisop == std::string::npos) continue; std::size_t nisopidx = idx - op.size() + 1; if (nisop == nisopidx) { idx = static_cast<std::ptrdiff_t>(nisopidx); earlybreak = true; } break; } if (earlybreak) { continue; } level += isleft ? -1 : 1; } if (idx > 0) { realname.erase(0, realname.length() < static_cast<std::size_t>(idx) ? realname.length() : idx + 1); } return realname; } template <typename T> inline const std::string& demangle() { static const std::string d = demangle_once<T>(); return d; } template <typename T> inline const std::string& short_demangle() { static const std::string d = short_demangle_once<T>(); return d; } } // detail } // sol #endif // SOL_DEMANGLE_HPP
var one = { name: 'one' };
package sun.java2d.opengl; import java.awt.AlphaComposite; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.Transparency; import java.awt.image.ColorModel; import java.awt.image.Raster; import sun.awt.SunHints; import sun.awt.image.PixelConverter; import sun.java2d.pipe.hw.AccelSurface; import sun.java2d.SunGraphics2D; import sun.java2d.SurfaceData; import sun.java2d.SurfaceDataProxy; import sun.java2d.loops.CompositeType; import sun.java2d.loops.GraphicsPrimitive; import sun.java2d.loops.MaskFill; import sun.java2d.loops.SurfaceType; import sun.java2d.pipe.ParallelogramPipe; import sun.java2d.pipe.<API key>; import sun.java2d.pipe.RenderBuffer; import sun.java2d.pipe.TextPipe; import static sun.java2d.pipe.BufferedOpCodes.*; import static sun.java2d.opengl.OGLContext.OGLContextCaps.*; public abstract class OGLSurfaceData extends SurfaceData implements AccelSurface { /** * OGL-specific surface types * * @see sun.java2d.pipe.hw.AccelSurface */ public static final int PBUFFER = RT_PLAIN; public static final int FBOBJECT = RT_TEXTURE; /** * Pixel formats */ public static final int PF_INT_ARGB = 0; public static final int PF_INT_ARGB_PRE = 1; public static final int PF_INT_RGB = 2; public static final int PF_INT_RGBX = 3; public static final int PF_INT_BGR = 4; public static final int PF_INT_BGRX = 5; public static final int PF_USHORT_565_RGB = 6; public static final int PF_USHORT_555_RGB = 7; public static final int PF_USHORT_555_RGBX = 8; public static final int PF_BYTE_GRAY = 9; public static final int PF_USHORT_GRAY = 10; public static final int PF_3BYTE_BGR = 11; /** * SurfaceTypes */ private static final String DESC_OPENGL_SURFACE = "OpenGL Surface"; private static final String <API key> = "OpenGL Surface (render-to-texture)"; private static final String DESC_OPENGL_TEXTURE = "OpenGL Texture"; static final SurfaceType OpenGLSurface = SurfaceType.Any.deriveSubType(DESC_OPENGL_SURFACE, PixelConverter.ArgbPre.instance); static final SurfaceType OpenGLSurfaceRTT = OpenGLSurface.deriveSubType(<API key>); static final SurfaceType OpenGLTexture = SurfaceType.Any.deriveSubType(DESC_OPENGL_TEXTURE); /** This will be true if the fbobject system property has been enabled. */ private static boolean isFBObjectEnabled; /** This will be true if the lcdshader system property has been enabled.*/ private static boolean isLCDShaderEnabled; /** This will be true if the biopshader system property has been enabled.*/ private static boolean isBIOpShaderEnabled; /** This will be true if the gradshader system property has been enabled.*/ private static boolean isGradShaderEnabled; private OGLGraphicsConfig graphicsConfig; protected int type; // these fields are set from the native code when the surface is // initialized private int nativeWidth, nativeHeight; protected static OGLRenderer oglRenderPipe; protected static <API key> oglTxRenderPipe; protected static ParallelogramPipe oglAAPgramPipe; protected static OGLTextRenderer oglTextPipe; protected static OGLDrawImage oglImagePipe; protected native boolean initTexture(long pData, boolean isOpaque, boolean texNonPow2, boolean texRect, int width, int height); protected native boolean initFBObject(long pData, boolean isOpaque, boolean texNonPow2, boolean texRect, int width, int height); protected native boolean initFlipBackbuffer(long pData); protected abstract boolean initPbuffer(long pData, long pConfigInfo, boolean isOpaque, int width, int height); private native int getTextureTarget(long pData); private native int getTextureID(long pData); static { if (!GraphicsEnvironment.isHeadless()) { // fbobject currently enabled by default; use "false" to disable String fbo = (String)java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "sun.java2d.opengl.fbobject")); isFBObjectEnabled = !"false".equals(fbo); // lcdshader currently enabled by default; use "false" to disable String lcd = (String)java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "sun.java2d.opengl.lcdshader")); isLCDShaderEnabled = !"false".equals(lcd); // biopshader currently enabled by default; use "false" to disable String biop = (String)java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "sun.java2d.opengl.biopshader")); isBIOpShaderEnabled = !"false".equals(biop); // gradshader currently enabled by default; use "false" to disable String grad = (String)java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "sun.java2d.opengl.gradshader")); isGradShaderEnabled = !"false".equals(grad); OGLRenderQueue rq = OGLRenderQueue.getInstance(); oglImagePipe = new OGLDrawImage(); oglTextPipe = new OGLTextRenderer(rq); oglRenderPipe = new OGLRenderer(rq); if (GraphicsPrimitive.tracingEnabled()) { oglTextPipe = oglTextPipe.traceWrap(); //The wrapped oglRenderPipe will wrap the AA pipe as well... //oglAAPgramPipe = oglRenderPipe.traceWrap(); } oglAAPgramPipe = oglRenderPipe.<API key>(); oglTxRenderPipe = new <API key>(oglRenderPipe, oglRenderPipe, 1.0, 0.25, true); OGLBlitLoops.register(); OGLMaskFill.register(); OGLMaskBlit.register(); } } protected OGLSurfaceData(OGLGraphicsConfig gc, ColorModel cm, int type) { super(<API key>(type), cm); this.graphicsConfig = gc; this.type = type; setBlitProxyKey(gc.getProxyKey()); } @Override public SurfaceDataProxy makeProxyFor(SurfaceData srcData) { return OGLSurfaceDataProxy.createProxy(srcData, graphicsConfig); } /** * Returns the appropriate SurfaceType corresponding to the given OpenGL * surface type constant (e.g. TEXTURE -> OpenGLTexture). */ private static SurfaceType <API key>(int oglType) { switch (oglType) { case TEXTURE: return OpenGLTexture; case FBOBJECT: return OpenGLSurfaceRTT; case PBUFFER: default: return OpenGLSurface; } } /** * Note: This should only be called from the QFT under the AWT lock. * This method is kept separate from the initSurface() method below just * to keep the code a bit cleaner. */ private void initSurfaceNow(int width, int height) { boolean isOpaque = (getTransparency() == Transparency.OPAQUE); boolean success = false; switch (type) { case PBUFFER: success = initPbuffer(getNativeOps(), graphicsConfig.getNativeConfigInfo(), isOpaque, width, height); break; case TEXTURE: success = initTexture(getNativeOps(), isOpaque, <API key>(), isTexRectAvailable(), width, height); break; case FBOBJECT: success = initFBObject(getNativeOps(), isOpaque, <API key>(), isTexRectAvailable(), width, height); break; case FLIP_BACKBUFFER: success = initFlipBackbuffer(getNativeOps()); break; default: break; } if (!success) { throw new OutOfMemoryError("can't create offscreen surface"); } } /** * Initializes the appropriate OpenGL offscreen surface based on the value * of the type parameter. If the surface creation fails for any reason, * an OutOfMemoryError will be thrown. */ protected void initSurface(final int width, final int height) { OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { switch (type) { case TEXTURE: case PBUFFER: case FBOBJECT: // need to make sure the context is current before // creating the texture (or pbuffer, or fbobject) OGLContext.setScratchSurface(graphicsConfig); break; default: break; } rq.flushAndInvokeNow(new Runnable() { public void run() { initSurfaceNow(width, height); } }); } finally { rq.unlock(); } } /** * Returns the OGLContext for the GraphicsConfig associated with this * surface. */ public final OGLContext getContext() { return graphicsConfig.getContext(); } /** * Returns the OGLGraphicsConfig associated with this surface. */ final OGLGraphicsConfig <API key>() { return graphicsConfig; } /** * Returns one of the surface type constants defined above. */ public final int getType() { return type; } /** * If this surface is backed by a texture object, returns the target * for that texture (either GL_TEXTURE_2D or <API key>). * Otherwise, this method will return zero. */ public final int getTextureTarget() { return getTextureTarget(getNativeOps()); } /** * If this surface is backed by a texture object, returns the texture ID * for that texture. * Otherwise, this method will return zero. */ public final int getTextureID() { return getTextureID(getNativeOps()); } /** * Returns native resource of specified {@code resType} associated with * this surface. * * Specifically, for {@code OGLSurfaceData} this method returns the * the following: * <pre> * TEXTURE - texture id * </pre> * * Note: the resource returned by this method is only valid on the rendering * thread. * * @return native resource of specified type or 0L if * such resource doesn't exist or can not be retrieved. * @see sun.java2d.pipe.hw.AccelSurface#getNativeResource */ public long getNativeResource(int resType) { if (resType == TEXTURE) { return getTextureID(); } return 0L; } public Raster getRaster(int x, int y, int w, int h) { throw new InternalError("not implemented yet"); } /** * For now, we can only render LCD text if: * - the fragment shader extension is available, and * - blending is disabled, and * - the source color is opaque * - and the destination is opaque * * Eventually, we could enhance the native OGL text rendering code * and remove the above restrictions, but that would require significantly * more code just to support a few uncommon cases. */ public boolean canRenderLCDText(SunGraphics2D sg2d) { return graphicsConfig.isCapPresent(CAPS_EXT_LCD_SHADER) && sg2d.compositeState <= SunGraphics2D.COMP_ISCOPY && sg2d.paintState <= SunGraphics2D.PAINT_OPAQUECOLOR && sg2d.surfaceData.getTransparency() == Transparency.OPAQUE; } public void validatePipe(SunGraphics2D sg2d) { TextPipe textpipe; boolean validated = false; // OGLTextRenderer handles both AA and non-AA text, but // only works with the following modes: // (Note: For LCD text we only enter this code path if // canRenderLCDText() has already validated that the mode is // CompositeType.SrcNoEa (opaque color), which will be subsumed // by the CompositeType.SrcNoEa (any color) test below.) if (/* CompositeType.SrcNoEa (any color) */ (sg2d.compositeState <= sg2d.COMP_ISCOPY && sg2d.paintState <= sg2d.PAINT_ALPHACOLOR) || /* CompositeType.SrcOver (any color) */ (sg2d.compositeState == sg2d.COMP_ALPHA && sg2d.paintState <= sg2d.PAINT_ALPHACOLOR && (((AlphaComposite)sg2d.composite).getRule() == AlphaComposite.SRC_OVER)) || /* CompositeType.Xor (any color) */ (sg2d.compositeState == sg2d.COMP_XOR && sg2d.paintState <= sg2d.PAINT_ALPHACOLOR)) { textpipe = oglTextPipe; } else { // do this to initialize textpipe correctly; we will attempt // to override the non-text pipes below super.validatePipe(sg2d); textpipe = sg2d.textpipe; validated = true; } <API key> txPipe = null; OGLRenderer nonTxPipe = null; if (sg2d.antialiasHint != SunHints.INTVAL_ANTIALIAS_ON) { if (sg2d.paintState <= sg2d.PAINT_ALPHACOLOR) { if (sg2d.compositeState <= sg2d.COMP_XOR) { txPipe = oglTxRenderPipe; nonTxPipe = oglRenderPipe; } } else if (sg2d.compositeState <= sg2d.COMP_ALPHA) { if (OGLPaints.isValid(sg2d)) { txPipe = oglTxRenderPipe; nonTxPipe = oglRenderPipe; } // custom paints handled by super.validatePipe() below } } else { if (sg2d.paintState <= sg2d.PAINT_ALPHACOLOR) { if (graphicsConfig.isCapPresent(CAPS_PS30) && (sg2d.imageComp == CompositeType.SrcOverNoEa || sg2d.imageComp == CompositeType.SrcOver)) { if (!validated) { super.validatePipe(sg2d); validated = true; } <API key> aaConverter = new <API key>(sg2d.shapepipe, oglAAPgramPipe, 1.0/8.0, 0.499, false); sg2d.drawpipe = aaConverter; sg2d.fillpipe = aaConverter; sg2d.shapepipe = aaConverter; } else if (sg2d.compositeState == sg2d.COMP_XOR) { // install the solid pipes when AA and XOR are both enabled txPipe = oglTxRenderPipe; nonTxPipe = oglRenderPipe; } } // other cases handled by super.validatePipe() below } if (txPipe != null) { if (sg2d.transformState >= sg2d.<API key>) { sg2d.drawpipe = txPipe; sg2d.fillpipe = txPipe; } else if (sg2d.strokeState != sg2d.STROKE_THIN) { sg2d.drawpipe = txPipe; sg2d.fillpipe = nonTxPipe; } else { sg2d.drawpipe = nonTxPipe; sg2d.fillpipe = nonTxPipe; } // Note that we use the transforming pipe here because it // will examine the shape and possibly perform an optimized // operation if it can be simplified. The simplifications // will be valid for all STROKE and TRANSFORM types. sg2d.shapepipe = txPipe; } else { if (!validated) { super.validatePipe(sg2d); } } // install the text pipe based on our earlier decision sg2d.textpipe = textpipe; // always override the image pipe with the specialized OGL pipe sg2d.imagepipe = oglImagePipe; } @Override protected MaskFill getMaskFill(SunGraphics2D sg2d) { if (sg2d.paintState > sg2d.PAINT_ALPHACOLOR) { /* * We can only accelerate non-Color MaskFill operations if * all of the following conditions hold true: * - there is an implementation for the given paintState * - the current Paint can be accelerated for this destination * - multitexturing is available (since we need to modulate * the alpha mask texture with the paint texture) * * In all other cases, we return null, in which case the * validation code will choose a more general software-based loop. */ if (!OGLPaints.isValid(sg2d) || !graphicsConfig.isCapPresent(CAPS_MULTITEXTURE)) { return null; } } return super.getMaskFill(sg2d); } public boolean copyArea(SunGraphics2D sg2d, int x, int y, int w, int h, int dx, int dy) { if (sg2d.transformState < sg2d.<API key> && sg2d.compositeState < sg2d.COMP_XOR) { x += sg2d.transX; y += sg2d.transY; oglRenderPipe.copyArea(sg2d, x, y, w, h, dx, dy); return true; } return false; } public void flush() { invalidate(); OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { // make sure we have a current context before // disposing the native resources (e.g. texture object) OGLContext.setScratchSurface(graphicsConfig); RenderBuffer buf = rq.getBuffer(); rq.<API key>(12, 4); buf.putInt(FLUSH_SURFACE); buf.putLong(getNativeOps()); // this call is expected to complete synchronously, so flush now rq.flushNow(); } finally { rq.unlock(); } } /** * Disposes the native resources associated with the given OGLSurfaceData * (referenced by the pData parameter). This method is invoked from * the native Dispose() method from the Disposer thread when the * Java-level OGLSurfaceData object is about to go away. Note that we * also pass a reference to the native GLX/<API key> * (pConfigInfo) for the purposes of making a context current. */ static void dispose(long pData, long pConfigInfo) { OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { // make sure we have a current context before // disposing the native resources (e.g. texture object) OGLContext.setScratchSurface(pConfigInfo); RenderBuffer buf = rq.getBuffer(); rq.<API key>(12, 4); buf.putInt(DISPOSE_SURFACE); buf.putLong(pData); // this call is expected to complete synchronously, so flush now rq.flushNow(); } finally { rq.unlock(); } } static void swapBuffers(long window) { OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { RenderBuffer buf = rq.getBuffer(); rq.<API key>(12, 4); buf.putInt(SWAP_BUFFERS); buf.putLong(window); rq.flushNow(); } finally { rq.unlock(); } } /** * Returns true if OpenGL textures can have non-power-of-two dimensions * when using the basic GL_TEXTURE_2D target. */ boolean <API key>() { return graphicsConfig.isCapPresent(CAPS_TEXNONPOW2); } /** * Returns true if OpenGL textures can have non-power-of-two dimensions * when using the <API key> target (only available when the * <API key> extension is present). */ boolean isTexRectAvailable() { return graphicsConfig.isCapPresent(CAPS_EXT_TEXRECT); } public Rectangle getNativeBounds() { OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { return new Rectangle(nativeWidth, nativeHeight); } finally { rq.unlock(); } } }
<?php namespace Doctrine\MongoDB\Event; use Doctrine\Common\EventArgs as BaseEventArgs; class EventArgs extends BaseEventArgs { private $invoker; private $data; public function __construct($invoker, &$data = null) { $this->invoker = $invoker; $this->data = $data; } public function getInvoker() { return $this->invoker; } public function getData() { return $this->data; } }
var crypto = require('crypto'); var scmp = require('scmp'); var utils = require('keystone-utils'); // The DISABLE_CSRF environment variable is available to automatically pass // CSRF validation. This is useful in development scenarios where you want to // restart the node process and aren't using a persistent session store, but // should NEVER be set in production environments!! var DISABLE_CSRF = process.env.DISABLE_CSRF === 'true'; exports.TOKEN_KEY = '_csrf'; exports.LOCAL_KEY = 'csrf_token_key'; exports.LOCAL_VALUE = 'csrf_token_value'; exports.SECRET_KEY = exports.TOKEN_KEY + '_secret'; exports.SECRET_LENGTH = 10; exports.CSRF_HEADER_KEY = 'x-csrf-token'; exports.XSRF_HEADER_KEY = 'x-xsrf-token'; exports.XSRF_COOKIE_KEY = 'XSRF-TOKEN'; function tokenize (salt, secret) { return salt + crypto.createHash('sha1').update(salt + secret).digest('hex'); } exports.createSecret = function () { return crypto.pseudoRandomBytes(exports.SECRET_LENGTH).toString('base64'); }; exports.getSecret = function (req) { return req.session[exports.SECRET_KEY] || (req.session[exports.SECRET_KEY] = exports.createSecret()); }; exports.createToken = function (req) { return tokenize(utils.randomString(exports.SECRET_LENGTH), exports.getSecret(req)); }; exports.getToken = function (req, res) { res.locals[exports.LOCAL_VALUE] = res.locals[exports.LOCAL_VALUE] || exports.createToken(req); res.cookie(exports.XSRF_COOKIE_KEY, res.locals[exports.LOCAL_VALUE]); return res.locals[exports.LOCAL_VALUE]; }; exports.requestToken = function (req) { if (req.body && req.body[exports.TOKEN_KEY]) { return req.body[exports.TOKEN_KEY]; } else if (req.query && req.query[exports.TOKEN_KEY]) { return req.query[exports.TOKEN_KEY]; } else if (req.headers && req.headers[exports.XSRF_HEADER_KEY]) { return req.headers[exports.XSRF_HEADER_KEY]; } else if (req.headers && req.headers[exports.CSRF_HEADER_KEY]) { return req.headers[exports.CSRF_HEADER_KEY]; } return ''; }; exports.validate = function (req, token) { // Allow environment variable to disable check if (DISABLE_CSRF) return true; if (arguments.length === 1) { token = exports.requestToken(req); } if (typeof token !== 'string') { return false; } return scmp(token, tokenize(token.slice(0, exports.SECRET_LENGTH), req.session[exports.SECRET_KEY])); }; exports.middleware = { init: function (req, res, next) { res.locals[exports.LOCAL_KEY] = exports.LOCAL_VALUE; exports.getToken(req, res); next(); }, validate: function (req, res, next) { // Allow environment variable to disable check if (DISABLE_CSRF) return next(); // Bail on safe methods if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') { return next(); } // Validate token if (exports.validate(req)) { next(); } else { res.statusCode = 403; next(new Error('CSRF token mismatch')); } }, };
<?php /** * The document handler for the docbook document markup. * * @package Document * @version //autogen// */ class ezcDocumentDocbook extends ezcDocumentXmlBase { /** * Construct document xml base. * * @ignore * @param <API key> $options * @return void */ public function __construct( <API key> $options = null ) { parent::__construct( $options === null ? new <API key>() : $options ); } /** * Return document compiled to the docbook format * * The internal document structure is compiled to the docbook format and * the resulting docbook document is returned. * * This method is required for all formats to have one central format, so * that each format can be compiled into each other format using docbook as * an intermediate format. * * You may of course just call an existing converter for this conversion. * * @return ezcDocumentDocbook */ public function getAsDocbook() { return $this; } /** * Create document from docbook document * * A document of the docbook format is provided and the internal document * structure should be created out of this. * * This method is required for all formats to have one central format, so * that each format can be compiled into each other format using docbook as * an intermediate format. * * You may of course just call an existing converter for this conversion. * * @param ezcDocumentDocbook $document * @return void */ public function createFromDocbook( ezcDocumentDocbook $document ) { $this->path = $document->getPath(); $this->document = $document->getDomDocument(); } /** * Return document as string * * Serialize the document to a string an return it. * * @return string */ public function save() { return $this->document->saveXml(); } /** * Validate the input file * * Validate the input file against the specification of the current * document format. * * Returns true, if the validation succeded, and an array with * <API key> objects otherwise. * * @param string $file * @return mixed */ public function validateFile( $file ) { $oldSetting = <API key>( true ); libxml_clear_errors(); $document = new DOMDocument(); $document->load( $file ); $document->schemaValidate( $this->options->schema ); // Get all errors $xmlErrors = libxml_get_errors(); $errors = array(); foreach ( $xmlErrors as $error ) { $errors[] = <API key>::<API key>( $error ); } libxml_clear_errors(); <API key>( $oldSetting ); return ( count( $errors ) ? $errors : true ); } /** * Validate the input string * * Validate the input string against the specification of the current * document format. * * Returns true, if the validation succeded, and an array with * <API key> objects otherwise. * * @param string $string * @return mixed */ public function validateString( $string ) { $oldSetting = <API key>( true ); libxml_clear_errors(); $document = new DOMDocument(); $document->loadXml( $string ); $document->schemaValidate( $this->options->schema ); // Get all errors $xmlErrors = libxml_get_errors(); $errors = array(); foreach ( $xmlErrors as $error ) { $errors[] = <API key>::<API key>( $error ); } libxml_clear_errors(); <API key>( $oldSetting ); return ( count( $errors ) ? $errors : true ); } } ?>
<?php class <API key> { /** * Field Constructor. * * Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function * * @since Redux_Options 1.0.0 */ function __construct($field, $value, $current) { $this->field = $field; $this->value = $value; $this->current = $current; $this->validate(); } /** * Field Render Function. * * Takes the vars and validates them * * @since Redux_Options 1.0.0 */ function validate() { $this->value = preg_replace($this->field['preg']['pattern'], $this->field['preg']['replacement'], $this->value); } }
<?php /** * @see <API key> */ #require_once 'Zend/Http/UserAgent/Exception.php'; class <API key> extends <API key> { }
#include <linux/capability.h> #include <linux/kernel.h> #include <linux/if_bridge.h> #include <linux/netdevice.h> #include <linux/times.h> #include <net/net_namespace.h> #include <asm/uaccess.h> #include "br_private.h" /* called with RTNL */ static int <API key>(int *indices, int num) { struct net_device *dev; int i = 0; for_each_netdev(&init_net, dev) { if (i >= num) break; if (dev->priv_flags & IFF_EBRIDGE) indices[i++] = dev->ifindex; } return i; } /* called with RTNL */ static void get_port_ifindices(struct net_bridge *br, int *ifindices, int num) { struct net_bridge_port *p; list_for_each_entry(p, &br->port_list, list) { if (p->port_no < num) ifindices[p->port_no] = p->dev->ifindex; } } /* * Format up to a page worth of forwarding table entries * userbuf -- where to copy result * maxnum -- maximum number of entries desired * (limited to a page for sanity) * offset -- number of records to skip */ static int get_fdb_entries(struct net_bridge *br, void __user *userbuf, unsigned long maxnum, unsigned long offset) { int num; void *buf; size_t size; /* Clamp size to PAGE_SIZE, test maxnum to avoid overflow */ if (maxnum > PAGE_SIZE/sizeof(struct __fdb_entry)) maxnum = PAGE_SIZE/sizeof(struct __fdb_entry); size = maxnum * sizeof(struct __fdb_entry); buf = kmalloc(size, GFP_USER); if (!buf) return -ENOMEM; num = br_fdb_fillbuf(br, buf, maxnum, offset); if (num > 0) { if (copy_to_user(userbuf, buf, num*sizeof(struct __fdb_entry))) num = -EFAULT; } kfree(buf); return num; } static int add_del_if(struct net_bridge *br, int ifindex, int isadd) { struct net_device *dev; int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; dev = dev_get_by_index(&init_net, ifindex); if (dev == NULL) return -EINVAL; if (isadd) ret = br_add_if(br, dev); else ret = br_del_if(br, dev); dev_put(dev); return ret; } /* * Legacy ioctl's through SIOCDEVPRIVATE * This interface is deprecated because it was too difficult to * to do the translation for 32/64bit ioctl compatability. */ static int old_dev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct net_bridge *br = netdev_priv(dev); unsigned long args[4]; if (copy_from_user(args, rq->ifr_data, sizeof(args))) return -EFAULT; switch (args[0]) { case BRCTL_ADD_IF: case BRCTL_DEL_IF: return add_del_if(br, args[1], args[0] == BRCTL_ADD_IF); case <API key>: { struct __bridge_info b; memset(&b, 0, sizeof(struct __bridge_info)); rcu_read_lock(); memcpy(&b.designated_root, &br->designated_root, 8); memcpy(&b.bridge_id, &br->bridge_id, 8); b.root_path_cost = br->root_path_cost; b.max_age = jiffies_to_clock_t(br->max_age); b.hello_time = jiffies_to_clock_t(br->hello_time); b.forward_delay = br->forward_delay; b.bridge_max_age = br->bridge_max_age; b.bridge_hello_time = br->bridge_hello_time; b.<API key> = jiffies_to_clock_t(br-><API key>); b.topology_change = br->topology_change; b.<API key> = br-><API key>; b.root_port = br->root_port; b.stp_enabled = (br->stp_enabled != BR_NO_STP); b.ageing_time = jiffies_to_clock_t(br->ageing_time); b.hello_timer_value = br_timer_value(&br->hello_timer); b.tcn_timer_value = br_timer_value(&br->tcn_timer); b.<API key> = br_timer_value(&br-><API key>); b.gc_timer_value = br_timer_value(&br->gc_timer); rcu_read_unlock(); if (copy_to_user((void __user *)args[1], &b, sizeof(b))) return -EFAULT; return 0; } case BRCTL_GET_PORT_LIST: { int num, *indices; num = args[2]; if (num < 0) return -EINVAL; if (num == 0) num = 256; if (num > BR_MAX_PORTS) num = BR_MAX_PORTS; indices = kcalloc(num, sizeof(int), GFP_KERNEL); if (indices == NULL) return -ENOMEM; get_port_ifindices(br, indices, num); if (copy_to_user((void __user *)args[1], indices, num*sizeof(int))) num = -EFAULT; kfree(indices); return num; } case <API key>: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br-><API key> = clock_t_to_jiffies(args[1]); if (br_is_root_bridge(br)) br->forward_delay = br-><API key>; spin_unlock_bh(&br->lock); return 0; case <API key>: { unsigned long t = clock_t_to_jiffies(args[1]); if (!capable(CAP_NET_ADMIN)) return -EPERM; if (t < HZ) return -EINVAL; spin_lock_bh(&br->lock); br->bridge_hello_time = t; if (br_is_root_bridge(br)) br->hello_time = br->bridge_hello_time; spin_unlock_bh(&br->lock); return 0; } case <API key>: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br->bridge_max_age = clock_t_to_jiffies(args[1]); if (br_is_root_bridge(br)) br->max_age = br->bridge_max_age; spin_unlock_bh(&br->lock); return 0; case <API key>: if (!capable(CAP_NET_ADMIN)) return -EPERM; br->ageing_time = clock_t_to_jiffies(args[1]); return 0; case BRCTL_GET_PORT_INFO: { struct __port_info p; struct net_bridge_port *pt; rcu_read_lock(); if ((pt = br_get_port(br, args[2])) == NULL) { rcu_read_unlock(); return -EINVAL; } memset(&p, 0, sizeof(struct __port_info)); memcpy(&p.designated_root, &pt->designated_root, 8); memcpy(&p.designated_bridge, &pt->designated_bridge, 8); p.port_id = pt->port_id; p.designated_port = pt->designated_port; p.path_cost = pt->path_cost; p.designated_cost = pt->designated_cost; p.state = pt->state; p.top_change_ack = pt->topology_change_ack; p.config_pending = pt->config_pending; p.<API key> = br_timer_value(&pt->message_age_timer); p.<API key> = br_timer_value(&pt->forward_delay_timer); p.hold_timer_value = br_timer_value(&pt->hold_timer); rcu_read_unlock(); if (copy_to_user((void __user *)args[1], &p, sizeof(p))) return -EFAULT; return 0; } case <API key>: if (!capable(CAP_NET_ADMIN)) return -EPERM; br_stp_set_enabled(br, args[1]); return 0; case <API key>: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); <API key>(br, args[1]); spin_unlock_bh(&br->lock); return 0; case <API key>: { struct net_bridge_port *p; int ret = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (args[2] >= (1<<(16-BR_PORT_BITS))) return -ERANGE; spin_lock_bh(&br->lock); if ((p = br_get_port(br, args[1])) == NULL) ret = -EINVAL; else <API key>(p, args[2]); spin_unlock_bh(&br->lock); return ret; } case BRCTL_SET_PATH_COST: { struct net_bridge_port *p; int ret = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; if ((p = br_get_port(br, args[1])) == NULL) ret = -EINVAL; else <API key>(p, args[2]); return ret; } case <API key>: return get_fdb_entries(br, (void __user *)args[1], args[2], args[3]); } return -EOPNOTSUPP; } static int old_deviceless(void __user *uarg) { unsigned long args[3]; if (copy_from_user(args, uarg, sizeof(args))) return -EFAULT; switch (args[0]) { case BRCTL_GET_VERSION: return BRCTL_VERSION; case BRCTL_GET_BRIDGES: { int *indices; int ret = 0; if (args[2] >= 2048) return -ENOMEM; indices = kcalloc(args[2], sizeof(int), GFP_KERNEL); if (indices == NULL) return -ENOMEM; args[2] = <API key>(indices, args[2]); ret = copy_to_user((void __user *)args[1], indices, args[2]*sizeof(int)) ? -EFAULT : args[2]; kfree(indices); return ret; } case BRCTL_ADD_BRIDGE: case BRCTL_DEL_BRIDGE: { char buf[IFNAMSIZ]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(buf, (void __user *)args[1], IFNAMSIZ)) return -EFAULT; buf[IFNAMSIZ-1] = 0; if (args[0] == BRCTL_ADD_BRIDGE) return br_add_bridge(buf); return br_del_bridge(buf); } } return -EOPNOTSUPP; } int <API key>(struct net *net, unsigned int cmd, void __user *uarg) { switch (cmd) { case SIOCGIFBR: case SIOCSIFBR: return old_deviceless(uarg); case SIOCBRADDBR: case SIOCBRDELBR: { char buf[IFNAMSIZ]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(buf, uarg, IFNAMSIZ)) return -EFAULT; buf[IFNAMSIZ-1] = 0; if (cmd == SIOCBRADDBR) return br_add_bridge(buf); return br_del_bridge(buf); } } return -EOPNOTSUPP; } int br_dev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct net_bridge *br = netdev_priv(dev); switch(cmd) { case SIOCDEVPRIVATE: return old_dev_ioctl(dev, rq, cmd); case SIOCBRADDIF: case SIOCBRDELIF: return add_del_if(br, rq->ifr_ifindex, cmd == SIOCBRADDIF); } pr_debug("Bridge does not support ioctl 0x%x\n", cmd); return -EOPNOTSUPP; }
#undef container_of /* * The container_of construct: if p is a pointer to member m of * container class c, then return a pointer to the container of which * *p is a member. */ #define container_of(p, c, m) ((c *)((char *)(p) - offsetof(c,m))) #include <../../../com32/include/linux/list.h>
/* ScriptData SDName: Trial Of the Champion SD%Complete: SDComment: SDCategory: <API key> EndScriptData */ /* ContentData npc_announcer_toc5 EndContentData */ #include "ScriptPCH.h" #include "<API key>.h" #include "Vehicle.h" #define GOSSIP_START_EVENT1 "I'm ready to start challenge." #define GOSSIP_START_EVENT2 "I'm ready for the next challenge." #define ORIENTATION 4.714f const Position SpawnPosition = {746.261f, 657.401f, 411.681f, 4.65f}; class npc_announcer_toc5 : public CreatureScript { public: npc_announcer_toc5() : CreatureScript("npc_announcer_toc5") { } struct <API key> : public ScriptedAI { <API key>(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); uiSummonTimes = 0; uiPosition = 0; uiLesserChampions = 0; uiFirstBoss = 0; uiSecondBoss = 0; uiThirdBoss = 0; uiArgentChampion = 0; uiPhase = 0; uiTimer = 0; uiVehicle1GUID = 0; uiVehicle2GUID = 0; uiVehicle3GUID = 0; Champion1List.clear(); Champion2List.clear(); Champion3List.clear(); me->SetReactState(REACT_PASSIVE); me->SetFlag(UNIT_FIELD_FLAGS, <API key>); me->SetFlag(UNIT_NPC_FLAGS, <API key>); <API key>(); SetArgentChampion(); } InstanceScript* instance; uint8 uiSummonTimes; uint8 uiPosition; uint8 uiLesserChampions; uint32 uiArgentChampion; uint32 uiFirstBoss; uint32 uiSecondBoss; uint32 uiThirdBoss; uint32 uiPhase; uint32 uiTimer; uint64 uiVehicle1GUID; uint64 uiVehicle2GUID; uint64 uiVehicle3GUID; uint64 <API key>; std::list<uint64> Champion1List; std::list<uint64> Champion2List; std::list<uint64> Champion3List; void NextStep(uint32 uiTimerStep, bool bNextStep = true, uint8 uiPhaseStep = 0) { uiTimer = uiTimerStep; if (bNextStep) ++uiPhase; else uiPhase = uiPhaseStep; } void SetData(uint32 uiType, uint32 /*uiData*/) { switch (uiType) { case DATA_START: <API key>(uiFirstBoss); NextStep(10000, false, 1); break; case DATA_IN_POSITION: //movement done. me->GetMotionMaster()->MovePoint(1, 735.81f, 661.92f, 412.39f); if (GameObject* go = GameObject::GetGameObject(*me, instance->GetData64(DATA_MAIN_GATE))) instance->HandleGameObject(go->GetGUID(), false); NextStep(10000, false, 3); break; case <API key>: { ++uiLesserChampions; std::list<uint64> TempList; if (uiLesserChampions == 3 || uiLesserChampions == 6) { switch (uiLesserChampions) { case 3: TempList = Champion2List; break; case 6: TempList = Champion3List; break; } for (std::list<uint64>::const_iterator itr = TempList.begin(); itr != TempList.end(); ++itr) if (Creature* summon = Unit::GetCreature(*me, *itr)) AggroAllPlayers(summon); }else if (uiLesserChampions == 9) <API key>(); break; } } } void <API key>() { Creature* pGrandChampion1 = Unit::GetCreature(*me, uiVehicle1GUID); Creature* pGrandChampion2 = Unit::GetCreature(*me, uiVehicle2GUID); Creature* pGrandChampion3 = Unit::GetCreature(*me, uiVehicle3GUID); if (pGrandChampion1 && pGrandChampion2 && pGrandChampion3) { AggroAllPlayers(pGrandChampion1); AggroAllPlayers(pGrandChampion2); AggroAllPlayers(pGrandChampion3); } } void MovementInform(uint32 uiType, uint32 uiPointId) { if (uiType != POINT_MOTION_TYPE) return; if (uiPointId == 1) { me->SetOrientation(ORIENTATION); me-><API key>(); } } void <API key>(uint32 uiBoss) { ++uiSummonTimes; uint32 VEHICLE_TO_SUMMON1 = 0; uint32 VEHICLE_TO_SUMMON2 = 0; switch (uiBoss) { case 0: VEHICLE_TO_SUMMON1 = <API key>; VEHICLE_TO_SUMMON2 = <API key>; break; case 1: VEHICLE_TO_SUMMON1 = <API key>; VEHICLE_TO_SUMMON2 = <API key>; break; case 2: VEHICLE_TO_SUMMON1 = <API key>; VEHICLE_TO_SUMMON2 = <API key>; break; case 3: VEHICLE_TO_SUMMON1 = <API key>; VEHICLE_TO_SUMMON2 = <API key>; break; case 4: VEHICLE_TO_SUMMON1 = <API key>; VEHICLE_TO_SUMMON2 = <API key>; break; default: return; } if (Creature* pBoss = me->SummonCreature(VEHICLE_TO_SUMMON1, SpawnPosition)) { switch (uiSummonTimes) { case 1: { uiVehicle1GUID = pBoss->GetGUID(); uint64 <API key> = 0; if (Vehicle* pVehicle = pBoss->GetVehicleKit()) if (Unit* unit = pVehicle->GetPassenger(0)) <API key> = unit->GetGUID(); if (instance) { instance->SetData64(<API key>, uiVehicle1GUID); instance->SetData64(<API key>, <API key>); } pBoss->AI()->SetData(1, 0); break; } case 2: { uiVehicle2GUID = pBoss->GetGUID(); uint64 <API key> = 0; if (Vehicle* pVehicle = pBoss->GetVehicleKit()) if (Unit* unit = pVehicle->GetPassenger(0)) <API key> = unit->GetGUID(); if (instance) { instance->SetData64(<API key>, uiVehicle2GUID); instance->SetData64(<API key>, <API key>); } pBoss->AI()->SetData(2, 0); break; } case 3: { uiVehicle3GUID = pBoss->GetGUID(); uint64 <API key> = 0; if (Vehicle* pVehicle = pBoss->GetVehicleKit()) if (Unit* unit = pVehicle->GetPassenger(0)) <API key> = unit->GetGUID(); if (instance) { instance->SetData64(<API key>, uiVehicle3GUID); instance->SetData64(<API key>, <API key>); } pBoss->AI()->SetData(3, 0); break; } default: return; } for (uint8 i = 0; i < 3; ++i) { if (Creature* pAdd = me->SummonCreature(VEHICLE_TO_SUMMON2, SpawnPosition, <API key>)) { switch (uiSummonTimes) { case 1: Champion1List.push_back(pAdd->GetGUID()); break; case 2: Champion2List.push_back(pAdd->GetGUID()); break; case 3: Champion3List.push_back(pAdd->GetGUID()); break; } switch (i) { case 0: pAdd->GetMotionMaster()->MoveFollow(pBoss, 2.0f, M_PI); break; case 1: pAdd->GetMotionMaster()->MoveFollow(pBoss, 2.0f, M_PI / 2); break; case 2: pAdd->GetMotionMaster()->MoveFollow(pBoss, 2.0f, M_PI / 2 + M_PI); break; } } } } } void <API key>() { me->GetMotionMaster()->MovePoint(1, 735.81f, 661.92f, 412.39f); if (me->SummonCreature(uiArgentChampion, SpawnPosition)) { for (uint8 i = 0; i < 3; ++i) { if (Creature* pTrash = me->SummonCreature(<API key>, SpawnPosition)) pTrash->AI()->SetData(i, 0); if (Creature* pTrash = me->SummonCreature(NPC_ARGENT_MONK, SpawnPosition)) pTrash->AI()->SetData(i, 0); if (Creature* pTrash = me->SummonCreature(NPC_PRIESTESS, SpawnPosition)) pTrash->AI()->SetData(i, 0); } } } void <API key>() { uiFirstBoss = urand(0, 4); while (uiSecondBoss == uiFirstBoss || uiThirdBoss == uiFirstBoss || uiThirdBoss == uiSecondBoss) { uiSecondBoss = urand(0, 4); uiThirdBoss = urand(0, 4); } } void SetArgentChampion() { uint8 uiTempBoss = urand(0, 1); switch (uiTempBoss) { case 0: uiArgentChampion = NPC_EADRIC; break; case 1: uiArgentChampion = NPC_PALETRESS; break; } } void StartEncounter() { if (!instance) return; me->RemoveFlag(UNIT_NPC_FLAGS, <API key>); if (instance->GetData(BOSS_BLACK_KNIGHT) == NOT_STARTED) { if (instance->GetData(<API key>) == NOT_STARTED && instance->GetData(<API key>) == NOT_STARTED) { if (instance->GetData(<API key>) == NOT_STARTED) me->AI()->SetData(DATA_START, 0); if (instance->GetData(<API key>) == DONE) <API key>(); } if ((instance->GetData(<API key>) == DONE && instance->GetData(<API key>) == DONE) || instance->GetData(<API key>) == DONE) me->SummonCreature(<API key>, 769.834f, 651.915f, 447.035f, 0); } } void AggroAllPlayers(Creature* temp) { Map::PlayerList const &PlList = me->GetMap()->GetPlayers(); if (PlList.isEmpty()) return; for (Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i) { if (Player* player = i->getSource()) { if (player->isGameMaster()) continue; if (player->isAlive()) { temp->SetHomePosition(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation()); temp->RemoveFlag(UNIT_FIELD_FLAGS, <API key>); temp->SetReactState(REACT_AGGRESSIVE); temp->SetInCombatWith(player); player->SetInCombatWith(temp); temp->AddThreat(player, 0.0f); } } } } void UpdateAI(const uint32 uiDiff) { ScriptedAI::UpdateAI(uiDiff); if (uiTimer <= uiDiff) { switch (uiPhase) { case 1: <API key>(uiSecondBoss); NextStep(10000, true); break; case 2: <API key>(uiThirdBoss); NextStep(0, false); break; case 3: if (!Champion1List.empty()) { for (std::list<uint64>::const_iterator itr = Champion1List.begin(); itr != Champion1List.end(); ++itr) if (Creature* summon = Unit::GetCreature(*me, *itr)) AggroAllPlayers(summon); NextStep(0, false); } break; } } else uiTimer -= uiDiff; if (!UpdateVictim()) return; } void JustSummoned(Creature* summon) { if (instance && instance->GetData(<API key>) == NOT_STARTED) { summon->SetFlag(UNIT_FIELD_FLAGS, <API key>); summon->SetReactState(REACT_PASSIVE); } } void <API key>(Creature* summon) { switch (summon->GetEntry()) { case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: me->AI()->SetData(<API key>, 0); break; } } }; CreatureAI* GetAI(Creature* creature) const { return new <API key>(creature); } bool OnGossipHello(Player* player, Creature* creature) { InstanceScript* instance = creature->GetInstanceScript(); if (instance && ((instance->GetData(<API key>) == DONE && instance->GetData(BOSS_BLACK_KNIGHT) == DONE && instance->GetData(<API key>) == DONE) || instance->GetData(<API key>) == DONE)) return false; if (instance && instance->GetData(<API key>) == NOT_STARTED && instance->GetData(<API key>) == NOT_STARTED && instance->GetData(<API key>) == NOT_STARTED && instance->GetData(BOSS_BLACK_KNIGHT) == NOT_STARTED) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_START_EVENT1, GOSSIP_SENDER_MAIN, <API key>+1); else if (instance) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_START_EVENT2, GOSSIP_SENDER_MAIN, <API key>+1); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); if (action == <API key>+1) { player->CLOSE_GOSSIP_MENU(); CAST_AI(npc_announcer_toc5::<API key>, creature->AI())->StartEncounter(); } return true; } }; void <API key>() { new npc_announcer_toc5(); }
#include <linux/string.h> #include <linux/timer.h> #include <linux/workqueue.h> #include <linux/platform_device.h> #include <mach/am_regs.h> #include <linux/amports/canvas.h> #include <linux/amports/vframe.h> #include <linux/amports/vframe_provider.h> #include "deinterlace.h" #ifdef DEBUG unsigned di_pre_underflow = 0, di_pre_overflow = 0; unsigned long debug_array[4 * 1024]; #endif #if 1 #define RECEIVER_NAME "amvideo" #else #define RECEIVER_NAME "deinterlace" #endif #define PATTERN32_NUM 2 #define PATTERN22_NUM 32 #if (PATTERN22_NUM < 32) #define PATTERN22_MARK ((1LL<<PATTERN22_NUM)-1) #elif (PATTERN22_NUM < 64) #define PATTERN22_MARK ((0x100000000LL<<(PATTERN22_NUM-32))-1) #else #define PATTERN22_MARK <API key> #endif #define PRE_HOLD_LINE 4 #define DI_PRE_INTERVAL (HZ/100) // 0 - off // 1 - pre-post link // 2 - pre-post separate, only post in vsync static int deinterlace_mode = 0; #if defined(CONFIG_ARCH_MESON2) static int <API key> = 2; #endif static struct timer_list di_pre_timer; static struct work_struct di_pre_work; int di_pre_recycle_buf = -1; int prev_struct = 0; int prog_field_count = 0; int buf_recycle_done = 1; int di_pre_post_done = 1; int field_counter = 0, pre_field_counter = 0, di_checked_field = 0; int pattern_len = 0; int di_p32_counter = 0; unsigned int last_big_data = 0, last_big_num = 0; unsigned long blend_mode, pattern_22, di_info[4][83]; unsigned long long di_p32_info, di_p22_info, di_p32_info_2, di_p22_info_2; vframe_t *cur_buf; vframe_t di_buf_pool[DI_BUF_NUM]; DI_MIF_t di_inp_top_mif; DI_MIF_t di_inp_bot_mif; DI_MIF_t di_mem_mif; DI_MIF_t di_buf0_mif; DI_MIF_t di_buf1_mif; DI_MIF_t di_chan2_mif; DI_SIM_MIF_t di_nrwr_mif; DI_SIM_MIF_t di_mtnwr_mif; DI_SIM_MIF_t di_mtncrd_mif; DI_SIM_MIF_t di_mtnprd_mif; unsigned di_mem_start; int vdin_en = 0; vframe_t dummy_buf; int <API key>(void) { return deinterlace_mode; } void <API key>(int mode) { deinterlace_mode = mode; } #if defined(CONFIG_ARCH_MESON2) int <API key>(void) { return <API key>; } void <API key>(int level) { <API key> = level; } #endif int <API key>(void) { return di_pre_recycle_buf; } vframe_t *peek_di_out_buf(void) { if (field_counter <= pre_field_counter - 2) { return &(di_buf_pool[field_counter % DI_BUF_NUM]); } else { return NULL; } } void inc_field_counter(void) { field_counter++; } void set_post_di_mem(int mode) { unsigned temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((field_counter + di_checked_field) % DI_BUF_NUM); canvas_config(di_buf0_mif.canvas0_addr0, temp, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); if (mode == 1) { temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((field_counter + di_checked_field + 1) % DI_BUF_NUM); } else { temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((field_counter + di_checked_field - 1) % DI_BUF_NUM); } canvas_config(di_buf1_mif.canvas0_addr0, temp, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((field_counter + di_checked_field) % DI_BUF_NUM) + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT); canvas_config(di_mtncrd_mif.canvas_num, temp, MAX_CANVAS_WIDTH / 2, MAX_CANVAS_HEIGHT / 2, 0, 0); temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((field_counter + di_checked_field + 1) % DI_BUF_NUM) + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT); canvas_config(di_mtnprd_mif.canvas_num, temp, MAX_CANVAS_WIDTH / 2, MAX_CANVAS_HEIGHT / 2, 0, 0); } void disable_deinterlace(void) { WRITE_MPEG_REG(DI_PRE_CTRL, 0x3 << 30); WRITE_MPEG_REG(DI_POST_CTRL, 0x3 << 30); WRITE_MPEG_REG(DI_PRE_SIZE, (32 - 1) | ((64 - 1) << 16)); WRITE_MPEG_REG(DI_POST_SIZE, (32 - 1) | ((128 - 1) << 16)); WRITE_MPEG_REG(DI_INP_GEN_REG, READ_MPEG_REG(DI_INP_GEN_REG) & 0xfffffffe); WRITE_MPEG_REG(DI_MEM_GEN_REG, READ_MPEG_REG(DI_MEM_GEN_REG) & 0xfffffffe); WRITE_MPEG_REG(DI_CHAN2_GEN_REG, READ_MPEG_REG(DI_CHAN2_GEN_REG) & 0xfffffffe); WRITE_MPEG_REG(DI_IF1_GEN_REG, READ_MPEG_REG(DI_IF1_GEN_REG) & 0xfffffffe); } void <API key>(void) { unsigned status = READ_MPEG_REG(DI_PRE_CTRL) & 0x2; if (prev_struct > 0) { unsigned temp = READ_MPEG_REG(DI_PRE_SIZE); unsigned total = (temp & 0xffff) * ((temp >> 16) & 0xffff); unsigned count = 0; while ((READ_MPEG_REG(DI_INTR_CTRL) & 0xf) != (status | 0x9)) { if (count++ >= total) { break; } } WRITE_MPEG_REG(DI_INTR_CTRL, READ_MPEG_REG(DI_INTR_CTRL)); } WRITE_MPEG_REG(DI_INP_GEN_REG, READ_MPEG_REG(DI_INP_GEN_REG) & 0xfffffffe); WRITE_MPEG_REG(DI_MEM_GEN_REG, READ_MPEG_REG(DI_MEM_GEN_REG) & 0xfffffffe); WRITE_MPEG_REG(DI_CHAN2_GEN_REG, READ_MPEG_REG(DI_CHAN2_GEN_REG) & 0xfffffffe); #ifdef DEBUG di_pre_underflow = 0; di_pre_overflow = 0; #endif prev_struct = 0; prog_field_count = 0; buf_recycle_done = 1; di_pre_post_done = 1; pre_field_counter = field_counter; di_pre_recycle_buf = -1; WRITE_MPEG_REG(DI_PRE_CTRL, 0x3 << 30); WRITE_MPEG_REG(DI_PRE_SIZE, (32 - 1) | ((64 - 1) << 16)); } void <API key>(void) { WRITE_MPEG_REG(DI_POST_CTRL, 0x3 << 30); WRITE_MPEG_REG(DI_POST_SIZE, (32 - 1) | ((128 - 1) << 16)); WRITE_MPEG_REG(DI_IF1_GEN_REG, READ_MPEG_REG(DI_IF1_GEN_REG) & 0xfffffffe); } void set_vd1_fmt_more( int hfmt_en, int hz_yc_ratio, //2bit int hz_ini_phase, //4bit int vfmt_en, int vt_yc_ratio, //2bit int vt_ini_phase, //4bit int y_length, int c_length, int hz_rpt //1bit ) { int vt_phase_step = (16 >> vt_yc_ratio); WRITE_MPEG_REG(VIU_VD1_FMT_CTRL, (hz_rpt << 28) | // hz rpt pixel (hz_ini_phase << 24) | // hz ini phase (0 << 23) | // repeat p0 enable (hz_yc_ratio << 21) | // hz yc ratio (hfmt_en << 20) | // hz enable (1 << 17) | // nrpt_phase0 enable (0 << 16) | // repeat l0 enable (0 << 12) | // skip line num (vt_ini_phase << 8) | // vt ini phase (vt_phase_step << 1) | // vt phase step (3.4) (vfmt_en << 0) // vt enable ); WRITE_MPEG_REG(VIU_VD1_FMT_W, (y_length << 16) | // hz format width (c_length << 0) // vt format width ); } void initial_di_prepost(int hsize_pre, int vsize_pre, int hsize_post, int vsize_post, int hold_line) { WRITE_MPEG_REG(DI_PRE_SIZE, (hsize_pre - 1) | ((vsize_pre - 1) << 16)); WRITE_MPEG_REG(DI_POST_SIZE, (hsize_post - 1) | ((vsize_post - 1) << 16)); WRITE_MPEG_REG(DI_BLEND_CTRL, (0x2 << 20) | // top mode. EI only 25); // KDEINT WRITE_MPEG_REG(DI_EI_CTRL0, (255 << 16) | // ei_filter. (5 << 8) | // ei_threshold. (1 << 2) | // ei bypass cf2. (1 << 1)); // ei bypass far1 WRITE_MPEG_REG(DI_EI_CTRL1, (180 << 24) | // ei diff (10 << 16) | // ei ang45 (15 << 8) | // ei peak. 45); // ei cross. WRITE_MPEG_REG(DI_EI_CTRL2, (10 << 23) | // close2 (10 << 16) | // close1 (10 << 8) | // far2 10); // far1 WRITE_MPEG_REG(DI_PRE_CTRL, 0 | // NR enable (0 << 1) | // MTN_EN (0 << 2) | // check 3:2 pulldown (0 << 3) | // check 2:2 pulldown (0 << 4) | // 2:2 check mid pixel come from next field after MTN. (0 << 5) | // hist check enable (0 << 6) | // hist check not use chan2. (0 << 7) | // hist check use data before noise reduction. (0 << 8) | // chan 2 enable for 2:2 pull down check. (0 << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (1 << 12) | // pre viu link (hold_line << 16) | // pre hold line number (0 << 29) | // pre field number. (0x3 << 30) // pre soft rst, pre frame rst. ); WRITE_MPEG_REG(DI_POST_CTRL, (0 << 0) | // line buffer 0 enable (0 << 1) | // line buffer 1 enable (0 << 2) | // ei enable (0 << 3) | // mtn line buffer enable (0 << 4) | // mtnp read mif enable (0 << 5) | // di blend enble. (0 << 6) | // di mux output enable (0 << 7) | // di write to SDRAM enable. (1 << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (1 << 12) | // post viu link (1 << 13) | // prepost_link (hold_line << 16) | // post hold line number (0 << 29) | // post field number. (0x3 << 30) // post soft rst post frame rst. ); WRITE_MPEG_REG(DI_MC_22LVL0, (READ_MPEG_REG(DI_MC_22LVL0) & 0xffff0000) | 256); // field 22 level WRITE_MPEG_REG(DI_MC_32LVL0, (READ_MPEG_REG(DI_MC_32LVL0) & 0xffffff00) | 16); // field 32 level // set hold line for all ddr req interface. WRITE_MPEG_REG(DI_INP_GEN_REG, (hold_line << 19)); WRITE_MPEG_REG(DI_MEM_GEN_REG, (hold_line << 19)); WRITE_MPEG_REG(VD1_IF0_GEN_REG, (hold_line << 19)); WRITE_MPEG_REG(DI_IF1_GEN_REG, (hold_line << 19)); WRITE_MPEG_REG(DI_CHAN2_GEN_REG, (hold_line << 19)); } void initial_di_pre(int hsize_pre, int vsize_pre, int hold_line) { WRITE_MPEG_REG(DI_PRE_SIZE, (hsize_pre - 1) | ((vsize_pre - 1) << 16)); WRITE_MPEG_REG(DI_PRE_CTRL, 0 | // NR enable (0 << 1) | // MTN_EN (0 << 2) | // check 3:2 pulldown (0 << 3) | // check 2:2 pulldown (0 << 4) | // 2:2 check mid pixel come from next field after MTN. (0 << 5) | // hist check enable (0 << 6) | // hist check not use chan2. (0 << 7) | // hist check use data before noise reduction. (0 << 8) | // chan 2 enable for 2:2 pull down check. (0 << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (0 << 12) | // pre viu link (hold_line << 16) | // pre hold line number (0 << 29) | // pre field number. (0x3 << 30) // pre soft rst, pre frame rst. ); WRITE_MPEG_REG(DI_MC_22LVL0, (READ_MPEG_REG(DI_MC_22LVL0) & 0xffff0000) | 256); // field 22 level WRITE_MPEG_REG(DI_MC_32LVL0, (READ_MPEG_REG(DI_MC_32LVL0) & 0xffffff00) | 16); // field 32 level } void initial_di_post(int hsize_post, int vsize_post, int hold_line) { WRITE_MPEG_REG(DI_POST_SIZE, (hsize_post - 1) | ((vsize_post - 1) << 16)); WRITE_MPEG_REG(DI_BLEND_CTRL, (0x2 << 20) | // top mode. EI only 25); // KDEINT WRITE_MPEG_REG(DI_EI_CTRL0, (255 << 16) | // ei_filter. (5 << 8) | // ei_threshold. (1 << 2) | // ei bypass cf2. (1 << 1)); // ei bypass far1 WRITE_MPEG_REG(DI_EI_CTRL1, (180 << 24) | // ei diff (10 << 16) | // ei ang45 (15 << 8) | // ei peak. 45); // ei cross. WRITE_MPEG_REG(DI_EI_CTRL2, (10 << 23) | // close2 (10 << 16) | // close1 (10 << 8) | // far2 10); // far1 WRITE_MPEG_REG(DI_POST_CTRL, (0 << 0) | // line buffer 0 enable (0 << 1) | // line buffer 1 enable (0 << 2) | // ei enable (0 << 3) | // mtn line buffer enable (0 << 4) | // mtnp read mif enable (0 << 5) | // di blend enble. (0 << 6) | // di mux output enable (0 << 7) | // di write to SDRAM enable. (1 << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (1 << 12) | // post viu link (hold_line << 16) | // post hold line number (0 << 29) | // post field number. (0x3 << 30) // post soft rst post frame rst. ); } void <API key>(int win0_start_x, int win0_end_x, int win0_start_y, int win0_end_y, int win1_start_x, int win1_end_x, int win1_start_y, int win1_end_y, int win2_start_x, int win2_end_x, int win2_start_y, int win2_end_y, int win3_start_x, int win3_end_x, int win3_start_y, int win3_end_y, int win4_start_x, int win4_end_x, int win4_start_y, int win4_end_y, int win0_32lvl, int win1_32lvl, int win2_32lvl, int win3_32lvl, int win4_32lvl, int win0_22lvl, int win1_22lvl, int win2_22lvl, int win3_22lvl, int win4_22lvl, int field_32lvl, int field_22lvl) { WRITE_MPEG_REG(DI_MC_REG0_X, (win0_start_x << 16) | // start_x win0_end_x); // end_x WRITE_MPEG_REG(DI_MC_REG0_Y, (win0_start_y << 16) | // start_y win0_end_y); // end_x WRITE_MPEG_REG(DI_MC_REG1_X, (win1_start_x << 16) | // start_x win1_end_x); // end_x WRITE_MPEG_REG(DI_MC_REG1_Y, (win1_start_y << 16) | // start_y win1_end_y); // end_x WRITE_MPEG_REG(DI_MC_REG2_X, (win2_start_x << 16) | // start_x win2_end_x); // end_x WRITE_MPEG_REG(DI_MC_REG2_Y, (win2_start_y << 16) | // start_y win2_end_y); // end_x WRITE_MPEG_REG(DI_MC_REG3_X, (win3_start_x << 16) | // start_x win3_end_x); // end_x WRITE_MPEG_REG(DI_MC_REG3_Y, (win3_start_y << 16) | // start_y win3_end_y); // end_x WRITE_MPEG_REG(DI_MC_REG4_X, (win4_start_x << 16) | // start_x win4_end_x); // end_x WRITE_MPEG_REG(DI_MC_REG4_Y, (win4_start_y << 16) | // start_y win4_end_y); // end_x WRITE_MPEG_REG(DI_MC_32LVL1, win3_32lvl | //region 3 (win4_32lvl << 8)); //region 4 WRITE_MPEG_REG(DI_MC_32LVL0, field_32lvl | //field 32 level (win0_32lvl << 8) | //region 0 (win1_32lvl << 16) | //region 1 (win2_32lvl << 24)); //region 2. WRITE_MPEG_REG(DI_MC_22LVL0, field_22lvl | // field 22 level (win0_22lvl << 16)); // region 0. WRITE_MPEG_REG(DI_MC_22LVL1, win1_22lvl | // region 1 (win2_22lvl << 16)); // region 2. WRITE_MPEG_REG(DI_MC_22LVL2, win3_22lvl | // region 3 (win4_22lvl << 16)); // region 4. WRITE_MPEG_REG(DI_MC_CTRL, 0x1f); // enable region level } // handle all case of prepost link. void <API key>( DI_MIF_t *di_inp_mif, DI_MIF_t *di_mem_mif, DI_MIF_t *di_buf0_mif, DI_MIF_t *di_buf1_mif, DI_MIF_t *di_chan2_mif, DI_SIM_MIF_t *di_nrwr_mif, DI_SIM_MIF_t *di_diwr_mif, DI_SIM_MIF_t *di_mtnwr_mif, DI_SIM_MIF_t *di_mtncrd_mif, DI_SIM_MIF_t *di_mtnprd_mif, int nr_en, int mtn_en, int pd32_check_en, int pd22_check_en, int hist_check_en, int ei_en, int blend_en, int blend_mtn_en, int blend_mode, int di_vpp_en, int di_ddr_en, #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) int nr_hfilt_en, int nr_hfilt_mb_en, int mtn_modify_en, int blend_mtn_filt_en, int blend_data_filt_en, int post_mb_en, #endif int post_field_num, int pre_field_num, int prepost_link, int hold_line) { int hist_check_only; int ei_only; int buf1_en; #if defined(CONFIG_ARCH_MESON2) int nr_zone_0, nr_zone_1, nr_zone_2; if (<API key> == 0) { nr_zone_0 = 1; nr_zone_1 = 3; nr_zone_2 = 5; } else { nr_zone_0 = 3; nr_zone_1 = 6; nr_zone_2 = 10; } #endif hist_check_only = hist_check_en && !nr_en && !mtn_en && !pd22_check_en && !pd32_check_en; ei_only = ei_en && !blend_en && (di_vpp_en || di_ddr_en); #if defined(CONFIG_ARCH_MESON) buf1_en = (!prepost_link && !ei_only && (di_ddr_en || di_vpp_en)); #elif defined(CONFIG_ARCH_MESON2) if (ei_only) { buf1_en = 0; } else { buf1_en = 1; } #endif if (nr_en | mtn_en | pd22_check_en || pd32_check_en) { set_di_inp_mif(di_inp_mif, di_vpp_en && prepost_link , hold_line); set_di_mem_mif(di_mem_mif, di_vpp_en && prepost_link, hold_line); } if (pd22_check_en || hist_check_only) { set_di_chan2_mif(di_chan2_mif, di_vpp_en && prepost_link, hold_line); } #if defined(CONFIG_ARCH_MESON) if (ei_en || di_vpp_en || di_ddr_en) { set_di_if0_mif(di_buf0_mif, di_vpp_en, hold_line); } if (!prepost_link && !ei_only && (di_ddr_en || di_vpp_en)) { set_di_if1_mif(di_buf1_mif, di_vpp_en, hold_line); } #elif defined(CONFIG_ARCH_MESON2) if (prepost_link && !ei_only && (di_ddr_en || di_vpp_en)) { set_di_if1_mif(di_buf1_mif, di_vpp_en, hold_line); } else if (!prepost_link && (ei_en || di_vpp_en || di_ddr_en)) { set_di_if0_mif(di_buf0_mif, di_vpp_en, hold_line); set_di_if1_mif(di_buf1_mif, di_vpp_en, hold_line); } #endif // set nr wr mif interface. if (nr_en) { WRITE_MPEG_REG(DI_NRWR_X, (di_nrwr_mif->start_x << 16) | (di_nrwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_NRWR_Y, (di_nrwr_mif->start_y << 16) | (di_nrwr_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_NRWR_CTRL, di_nrwr_mif->canvas_num | // canvas index. ((prepost_link && di_vpp_en) << 8)); // urgent. #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_NR_CTRL0, (1 << 31) | // nr yuv enable. (1 << 30) | // nr range. 3 point (0 << 29) | // max of 3 point. (nr_hfilt_en << 28) | // nr hfilter enable. (nr_hfilt_mb_en << 27) | // nr hfilter motion_blur enable. (nr_zone_2 << 16) | // zone 2 (nr_zone_1 << 8) | // zone 1 (nr_zone_0 << 0)); // zone 0 WRITE_MPEG_REG(DI_NR_CTRL2, (10 << 24) | //intra noise level (1 << 16) | // intra no noise level. (10 << 8) | // inter noise level. (1 << 0)); // inter no noise level. WRITE_MPEG_REG(DI_NR_CTRL3, (16 << 16) | // if any one of 3 point mtn larger than 16 don't use 3 point. 720); // if one line eq cnt is larger than this number, this line is not conunted. #endif } // motion wr mif. if (mtn_en) { WRITE_MPEG_REG(DI_MTNWR_X, (di_mtnwr_mif->start_x << 16) | (di_mtnwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNWR_Y, (di_mtnwr_mif->start_y << 16) | (di_mtnwr_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNWR_CTRL, di_mtnwr_mif->canvas_num | // canvas index. ((prepost_link && di_vpp_en) << 8)); // urgent. #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_MTN_CTRL, (1 << 31) | // lpf enable. (1 << 30) | // mtn uv enable. (mtn_modify_en << 29) | // no mtn modify. (2 << 24) | // char diff count. (40 << 16) | // black level. (196 << 8) | // white level. (64 << 0)); // char diff level. WRITE_MPEG_REG(DI_MTN_CTRL1, (3 << 8) | // mtn shift if mtn modifty_en 0); // mtn reduce before shift. #endif } // motion for current display field. #if defined(CONFIG_ARCH_MESON) if (blend_mtn_en) { WRITE_MPEG_REG(DI_MTNCRD_X, (di_mtncrd_mif->start_x << 16) | (di_mtncrd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNCRD_Y, (di_mtncrd_mif->start_y << 16) | (di_mtncrd_mif->end_y)); // start_y 0 end_y 239. if (!prepost_link) { WRITE_MPEG_REG(DI_MTNRD_CTRL, (di_mtnprd_mif->canvas_num << 8) | //mtnp canvas index. (0 << 16) | // urgent di_mtncrd_mif->canvas_num); // current field mtn canvas index. } else { WRITE_MPEG_REG(DI_MTNRD_CTRL, (0 << 8) | //mtnp canvas index. ((prepost_link && di_vpp_en) << 16) | // urgent di_mtncrd_mif->canvas_num); // current field mtn canvas index. } } if (blend_mtn_en && !prepost_link) { WRITE_MPEG_REG(DI_MTNPRD_X, (di_mtnprd_mif->start_x << 16) | (di_mtnprd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNPRD_Y, (di_mtnprd_mif->start_y << 16) | (di_mtnprd_mif->end_y)); // start_y 0 end_y 239. } #elif defined(CONFIG_ARCH_MESON2) if (blend_mtn_en) { WRITE_MPEG_REG(DI_MTNCRD_X, (di_mtncrd_mif->start_x << 16) | (di_mtncrd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNCRD_Y, (di_mtncrd_mif->start_y << 16) | (di_mtncrd_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNPRD_X, (di_mtnprd_mif->start_x << 16) | (di_mtnprd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNPRD_Y, (di_mtnprd_mif->start_y << 16) | (di_mtnprd_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNRD_CTRL, (di_mtnprd_mif->canvas_num << 8) | //mtnp canvas index. ((prepost_link && di_vpp_en) << 16) | // urgent di_mtncrd_mif->canvas_num); // current field mtn canvas index. } #endif if (di_ddr_en) { WRITE_MPEG_REG(DI_DIWR_X, (di_diwr_mif->start_x << 16) | (di_diwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_DIWR_Y, (di_diwr_mif->start_y << 16) | (di_diwr_mif->end_y * 2 + 1)); // start_y 0 end_y 479. WRITE_MPEG_REG(DI_DIWR_CTRL, di_diwr_mif->canvas_num | // canvas index. (di_vpp_en << 8)); // urgent. } #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_PRE_CTRL, nr_en | // NR enable (mtn_en << 1) | // MTN_EN (pd32_check_en << 2) | // check 3:2 pulldown (pd22_check_en << 3) | // check 2:2 pulldown (1 << 4) | // 2:2 check mid pixel come from next field after MTN. (hist_check_en << 5) | // hist check enable (0 << 6) | // hist check not use chan2. ((!nr_en) << 7) | // hist check use data before noise reduction. (pd22_check_en << 8) | // chan 2 enable for 2:2 pull down check. (pd22_check_en << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (di_vpp_en << 12) | // pre viu link (hold_line << 16) | // pre hold line number (pre_field_num << 29) | // pre field number. (0x1 << 30) // pre soft rst, pre frame rst. ); WRITE_MPEG_REG(DI_POST_CTRL, ((ei_en || di_vpp_en || di_ddr_en) << 0) | // line buffer 0 enable (buf1_en << 1) | // line buffer 1 enable (ei_en << 2) | // ei enable (blend_mtn_en << 3) | // mtn line buffer enable ((blend_mtn_en && !prepost_link) << 4) | // mtnp read mif enable (blend_en << 5) | // di blend enble. (1 << 6) | // di mux output enable (di_ddr_en << 7) | // di write to SDRAM enable. (di_vpp_en << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (1 << 12) | // post viu link (prepost_link << 13) | (hold_line << 16) | // post hold line number (post_field_num << 29) | // post field number. (0x1 << 30) // post soft rst post frame rst. ); #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_PRE_CTRL, nr_en | // NR enable (mtn_en << 1) | // MTN_EN (pd32_check_en << 2) | // check 3:2 pulldown (pd22_check_en << 3) | // check 2:2 pulldown (nr_en << 4) | // 2:2 check mid pixel come from next field after MTN. (hist_check_en << 5) | // hist check enable (1 << 6) | // hist check not use chan2. ((!nr_en) << 7) | // hist check use data before noise reduction. (pd22_check_en << 8) | // chan 2 enable for 2:2 pull down check. (pd22_check_en << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (di_vpp_en << 12) | // pre viu link (hold_line << 16) | // pre hold line number (nr_en << 22) | // MTN after NR. (pre_field_num << 29) | // pre field number. (0x1 << 30) // pre soft rst, pre frame rst. ); WRITE_MPEG_REG(DI_POST_CTRL, ((ei_en || blend_en) << 0) | // line buffer 0 enable (buf1_en << 1) | // line buffer 1 enable (ei_en << 2) | // ei enable (blend_mtn_en << 3) | // mtn line buffer enable (blend_mtn_en << 4) | // mtnp read mif enable (blend_en << 5) | // di blend enble. (1 << 6) | // di mux output enable (di_ddr_en << 7) | // di write to SDRAM enable. (di_vpp_en << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (di_vpp_en << 12) | // post viu link (prepost_link << 13) | (hold_line << 16) | // post hold line number (post_field_num << 29) | // post field number. (0x1 << 30) // post soft rst post frame rst. ); #endif if (ei_only == 0) { #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_BLEND_CTRL, (READ_MPEG_REG(DI_BLEND_CTRL) & (~((1 << 25) | (3 << 20)))) | // clean some bit we need to set. (blend_mtn_en << 26) | // blend mtn enable. (0 << 25) | // blend with the mtn of the pre display field and next display field. (1 << 24) | // blend with pre display field. (blend_mode << 20) // motion adaptive blend. ); #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_BLEND_CTRL, (post_mb_en << 28) | // post motion blur enable. (0 << 27) | // mtn3p(l, c, r) max. (0 << 26) | // mtn3p(l, c, r) min. (0 << 25) | // mtn3p(l, c, r) ave. (1 << 24) | // mtntopbot max (blend_mtn_filt_en << 23) | // blend mtn filter enable. (blend_data_filt_en << 22) | // blend data filter enable. (blend_mode << 20) | // motion adaptive blend. 25 // kdeint. ); WRITE_MPEG_REG(DI_BLEND_CTRL1, (196 << 24) | // char level (64 << 16) | // angle thredhold. (40 << 8) | // all_af filt thd. (64)); // all 4 equal WRITE_MPEG_REG(DI_BLEND_CTRL2, (4 << 8) | // mtn no mov level. (48)); //black level. #endif } } int di_mode_check(int cur_field) { int i; WRITE_MPEG_REG(DI_INFO_ADDR, 0); #if defined(CONFIG_ARCH_MESON) for (i = 0; i <= 76; i++) #elif defined(CONFIG_ARCH_MESON2) for (i = 0; i <= 82; i++) #endif { di_info[cur_field][i] = READ_MPEG_REG(DI_INFO_DATA); } WRITE_MPEG_REG(DI_PRE_CTRL, READ_MPEG_REG(DI_PRE_CTRL) | (0x1 << 30)); // pre soft rst WRITE_MPEG_REG(DI_POST_CTRL, READ_MPEG_REG(DI_POST_CTRL) | (0x1 << 30)); // post soft rst return (0); } void set_di_inp_fmt_more(int hfmt_en, int hz_yc_ratio, //2bit int hz_ini_phase, //4bit int vfmt_en, int vt_yc_ratio, //2bit int vt_ini_phase, //4bit int y_length, int c_length, int hz_rpt //1bit ) { int repeat_l0_en = 1, nrpt_phase0_en = 0; int vt_phase_step = (16 >> vt_yc_ratio); WRITE_MPEG_REG(DI_INP_FMT_CTRL, (hz_rpt << 28) | //hz rpt pixel (hz_ini_phase << 24) | //hz ini phase (0 << 23) | //repeat p0 enable (hz_yc_ratio << 21) | //hz yc ratio (hfmt_en << 20) | //hz enable (nrpt_phase0_en << 17) | //nrpt_phase0 enable (repeat_l0_en << 16) | //repeat l0 enable (0 << 12) | //skip line num (vt_ini_phase << 8) | //vt ini phase (vt_phase_step << 1) | //vt phase step (3.4) (vfmt_en << 0) //vt enable ); WRITE_MPEG_REG(DI_INP_FMT_W, (y_length << 16) | //hz format width (c_length << 0) //vt format width ); } void set_di_inp_mif(DI_MIF_t *mif, int urgent, int hold_line) { unsigned long bytes_per_pixel; unsigned long demux_mode; unsigned long chro_rpt_lastl_ctrl; unsigned long <API key>; unsigned long luma0_rpt_loop_end; unsigned long luma0_rpt_loop_pat; unsigned long <API key>; unsigned long <API key>; unsigned long <API key>; unsigned long vt_ini_phase = 0; if (mif->set_separate_en == 1 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; <API key> = 1; luma0_rpt_loop_end = 1; <API key> = 1; <API key> = 1; luma0_rpt_loop_pat = 0x80; <API key> = 0x80; if (mif->output_field_num == 0) { vt_ini_phase = 0xe; } else { vt_ini_phase = 0xa; } } else if (mif->set_separate_en == 1 && mif->src_field_mode == 0) { chro_rpt_lastl_ctrl = 1; <API key> = 0; luma0_rpt_loop_end = 0; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x0; <API key> = 0x0; } else if (mif->set_separate_en == 0 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; <API key> = 1; luma0_rpt_loop_end = 1; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x80; <API key> = 0x00; } else { chro_rpt_lastl_ctrl = 0; <API key> = 0; luma0_rpt_loop_end = 0; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x00; <API key> = 0x00; } bytes_per_pixel = mif->set_separate_en ? 0 : (mif->video_mode ? 2 : 1); demux_mode = mif->video_mode; // General register WRITE_MPEG_REG(DI_INP_GEN_REG, (urgent << 28) | // chroma urgent bit (urgent << 27) | // luma urgent bit. (1 << 25) | // no dummy data. (hold_line << 19) | // hold lines (1 << 18) | // push dummy pixel (demux_mode << 16) | // demux_mode (bytes_per_pixel << 14) | (mif->burst_size_cr << 12) | (mif->burst_size_cb << 10) | (mif->burst_size_y << 8) | (chro_rpt_lastl_ctrl << 6) | (mif->set_separate_en << 1) | (1 << 0) // cntl_enable ); // Canvas WRITE_MPEG_REG(DI_INP_CANVAS0, (mif->canvas0_addr2 << 16) | // cntl_canvas0_addr2 (mif->canvas0_addr1 << 8) | // cntl_canvas0_addr1 (mif->canvas0_addr0 << 0) // cntl_canvas0_addr0 ); // Picture 0 X/Y start,end WRITE_MPEG_REG(DI_INP_LUMA_X0, (mif->luma_x_end0 << 16) | // cntl_luma_x_end0 (mif->luma_x_start0 << 0) // cntl_luma_x_start0 ); WRITE_MPEG_REG(DI_INP_LUMA_Y0, (mif->luma_y_end0 << 16) | // cntl_luma_y_end0 (mif->luma_y_start0 << 0) // cntl_luma_y_start0 ); WRITE_MPEG_REG(DI_INP_CHROMA_X0, (mif->chroma_x_end0 << 16) | (mif->chroma_x_start0 << 0) ); WRITE_MPEG_REG(DI_INP_CHROMA_Y0, (mif->chroma_y_end0 << 16) | (mif->chroma_y_start0 << 0) ); // Repeat or skip WRITE_MPEG_REG(DI_INP_RPT_LOOP, (0 << 28) | (0 << 24) | (0 << 20) | (0 << 16) | (<API key> << 12) | (<API key> << 8) | (<API key> << 4) | (luma0_rpt_loop_end << 0) ) ; WRITE_MPEG_REG(<API key>, luma0_rpt_loop_pat); WRITE_MPEG_REG(<API key>, <API key>); // Dummy pixel value WRITE_MPEG_REG(DI_INP_DUMMY_PIXEL, 0x00808000); if ((mif->set_separate_en == 1)) { // 4:2:0 block mode. set_di_inp_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 1, // vfmt_en 1, // vt_yc_ratio vt_ini_phase, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length mif->chroma_x_end0 - mif->chroma_x_start0 + 1 , // c length 0); // hz repeat. } else { set_di_inp_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 0, // vfmt_en 0, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length ((mif->luma_x_end0 >> 1) - (mif->luma_x_start0 >> 1) + 1), // c length 0); // hz repeat. } } void set_di_mem_fmt_more(int hfmt_en, int hz_yc_ratio, //2bit int hz_ini_phase, //4bit int vfmt_en, int vt_yc_ratio, //2bit int vt_ini_phase, //4bit int y_length, int c_length, int hz_rpt //1bit ) { int vt_phase_step = (16 >> vt_yc_ratio); WRITE_MPEG_REG(DI_MEM_FMT_CTRL, (hz_rpt << 28) | //hz rpt pixel (hz_ini_phase << 24) | //hz ini phase (0 << 23) | //repeat p0 enable (hz_yc_ratio << 21) | //hz yc ratio (hfmt_en << 20) | //hz enable (1 << 17) | //nrpt_phase0 enable (0 << 16) | //repeat l0 enable (0 << 12) | //skip line num (vt_ini_phase << 8) | //vt ini phase (vt_phase_step << 1) | //vt phase step (3.4) (vfmt_en << 0) //vt enable ); WRITE_MPEG_REG(DI_MEM_FMT_W, (y_length << 16) | //hz format width (c_length << 0) //vt format width ); } void set_di_mem_mif(DI_MIF_t *mif, int urgent, int hold_line) { unsigned long bytes_per_pixel; unsigned long demux_mode; unsigned long chro_rpt_lastl_ctrl; unsigned long <API key>; unsigned long luma0_rpt_loop_end; unsigned long luma0_rpt_loop_pat; unsigned long <API key>; unsigned long <API key>; unsigned long <API key>; if (mif->set_separate_en == 1 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; <API key> = 1; luma0_rpt_loop_end = 1; <API key> = 1; <API key> = 1; luma0_rpt_loop_pat = 0x80; <API key> = 0x80; } else if (mif->set_separate_en == 1 && mif->src_field_mode == 0) { chro_rpt_lastl_ctrl = 1; <API key> = 0; luma0_rpt_loop_end = 0; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x0; <API key> = 0x0; } else if (mif->set_separate_en == 0 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; <API key> = 1; luma0_rpt_loop_end = 1; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x80; <API key> = 0x00; } else { chro_rpt_lastl_ctrl = 0; <API key> = 0; luma0_rpt_loop_end = 0; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x00; <API key> = 0x00; } bytes_per_pixel = mif->set_separate_en ? 0 : (mif->video_mode ? 2 : 1); demux_mode = mif->video_mode; // General register WRITE_MPEG_REG(DI_MEM_GEN_REG, (urgent << 28) | // urgent bit. (urgent << 27) | // urgent bit. (1 << 25) | // no dummy data. (hold_line << 19) | // hold lines (1 << 18) | // push dummy pixel (demux_mode << 16) | // demux_mode (bytes_per_pixel << 14) | (mif->burst_size_cr << 12) | (mif->burst_size_cb << 10) | (mif->burst_size_y << 8) | (chro_rpt_lastl_ctrl << 6) | (mif->set_separate_en << 1) | (1 << 0) // cntl_enable ); // Canvas WRITE_MPEG_REG(DI_MEM_CANVAS0, (mif->canvas0_addr2 << 16) | // cntl_canvas0_addr2 (mif->canvas0_addr1 << 8) | // cntl_canvas0_addr1 (mif->canvas0_addr0 << 0) // cntl_canvas0_addr0 ); // Picture 0 X/Y start,end WRITE_MPEG_REG(DI_MEM_LUMA_X0, (mif->luma_x_end0 << 16) | // cntl_luma_x_end0 (mif->luma_x_start0 << 0) // cntl_luma_x_start0 ); WRITE_MPEG_REG(DI_MEM_LUMA_Y0, (mif->luma_y_end0 << 16) | // cntl_luma_y_end0 (mif->luma_y_start0 << 0) // cntl_luma_y_start0 ); WRITE_MPEG_REG(DI_MEM_CHROMA_X0, (mif->chroma_x_end0 << 16) | (mif->chroma_x_start0 << 0) ); WRITE_MPEG_REG(DI_MEM_CHROMA_Y0, (mif->chroma_y_end0 << 16) | (mif->chroma_y_start0 << 0) ); // Repeat or skip WRITE_MPEG_REG(DI_MEM_RPT_LOOP, (0 << 28) | (0 << 24) | (0 << 20) | (0 << 16) | (<API key> << 12) | (<API key> << 8) | (<API key> << 4) | (luma0_rpt_loop_end << 0) ) ; WRITE_MPEG_REG(<API key>, luma0_rpt_loop_pat); WRITE_MPEG_REG(<API key>, <API key>); // Dummy pixel value WRITE_MPEG_REG(DI_MEM_DUMMY_PIXEL, 0x00808000); if ((mif->set_separate_en == 1)) { // 4:2:0 block mode. set_di_mem_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 1, // vfmt_en 1, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length mif->chroma_x_end0 - mif->chroma_x_start0 + 1, // c length 0); // hz repeat. } else { set_di_mem_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 0, // vfmt_en 0, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length ((mif->luma_x_end0 >> 1) - (mif->luma_x_start0 >> 1) + 1), // c length 0); // hz repeat. } } void set_di_if1_fmt_more(int hfmt_en, int hz_yc_ratio, //2bit int hz_ini_phase, //4bit int vfmt_en, int vt_yc_ratio, //2bit int vt_ini_phase, //4bit int y_length, int c_length, int hz_rpt //1bit ) { int vt_phase_step = (16 >> vt_yc_ratio); WRITE_MPEG_REG(DI_IF1_FMT_CTRL, (hz_rpt << 28) | //hz rpt pixel (hz_ini_phase << 24) | //hz ini phase (0 << 23) | //repeat p0 enable (hz_yc_ratio << 21) | //hz yc ratio (hfmt_en << 20) | //hz enable (1 << 17) | //nrpt_phase0 enable (0 << 16) | //repeat l0 enable (0 << 12) | //skip line num (vt_ini_phase << 8) | //vt ini phase (vt_phase_step << 1) | //vt phase step (3.4) (vfmt_en << 0) //vt enable ); WRITE_MPEG_REG(DI_IF1_FMT_W, (y_length << 16) | //hz format width (c_length << 0) //vt format width ); } void set_di_if1_mif(DI_MIF_t *mif, int urgent, int hold_line) { unsigned long bytes_per_pixel; unsigned long demux_mode; unsigned long chro_rpt_lastl_ctrl; unsigned long <API key>; unsigned long luma0_rpt_loop_end; unsigned long luma0_rpt_loop_pat; unsigned long <API key>; unsigned long <API key>; unsigned long <API key>; if (mif->set_separate_en == 1 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; <API key> = 1; luma0_rpt_loop_end = 1; <API key> = 1; <API key> = 1; luma0_rpt_loop_pat = 0x80; <API key> = 0x80; } else if (mif->set_separate_en == 1 && mif->src_field_mode == 0) { chro_rpt_lastl_ctrl = 1; <API key> = 0; luma0_rpt_loop_end = 0; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x0; <API key> = 0x0; } else if (mif->set_separate_en == 0 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; <API key> = 1; luma0_rpt_loop_end = 1; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x80; <API key> = 0x00; } else { chro_rpt_lastl_ctrl = 0; <API key> = 0; luma0_rpt_loop_end = 0; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x00; <API key> = 0x00; } bytes_per_pixel = mif->set_separate_en ? 0 : (mif->video_mode ? 2 : 1); demux_mode = mif->video_mode; // General register WRITE_MPEG_REG(DI_IF1_GEN_REG, (urgent << 28) | // urgent (urgent << 27) | // luma urgent (1 << 25) | // no dummy data. (hold_line << 19) | // hold lines (1 << 18) | // push dummy pixel (demux_mode << 16) | // demux_mode (bytes_per_pixel << 14) | (mif->burst_size_cr << 12) | (mif->burst_size_cb << 10) | (mif->burst_size_y << 8) | (chro_rpt_lastl_ctrl << 6) | (mif->set_separate_en << 1) | (1 << 0) // cntl_enable ); // Canvas WRITE_MPEG_REG(DI_IF1_CANVAS0, (mif->canvas0_addr2 << 16) | // cntl_canvas0_addr2 (mif->canvas0_addr1 << 8) | // cntl_canvas0_addr1 (mif->canvas0_addr0 << 0) // cntl_canvas0_addr0 ); // Picture 0 X/Y start,end WRITE_MPEG_REG(DI_IF1_LUMA_X0, (mif->luma_x_end0 << 16) | // cntl_luma_x_end0 (mif->luma_x_start0 << 0) // cntl_luma_x_start0 ); WRITE_MPEG_REG(DI_IF1_LUMA_Y0, (mif->luma_y_end0 << 16) | // cntl_luma_y_end0 (mif->luma_y_start0 << 0) // cntl_luma_y_start0 ); WRITE_MPEG_REG(DI_IF1_CHROMA_X0, (mif->chroma_x_end0 << 16) | (mif->chroma_x_start0 << 0) ); WRITE_MPEG_REG(DI_IF1_CHROMA_Y0, (mif->chroma_y_end0 << 16) | (mif->chroma_y_start0 << 0) ); // Repeat or skip WRITE_MPEG_REG(DI_IF1_RPT_LOOP, (0 << 28) | (0 << 24) | (0 << 20) | (0 << 16) | (<API key> << 12) | (<API key> << 8) | (<API key> << 4) | (luma0_rpt_loop_end << 0) ) ; WRITE_MPEG_REG(<API key>, luma0_rpt_loop_pat); WRITE_MPEG_REG(<API key>, <API key>); // Dummy pixel value WRITE_MPEG_REG(DI_IF1_DUMMY_PIXEL, 0x00808000); if ((mif->set_separate_en == 1)) { // 4:2:0 block mode. set_di_if1_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 1, // vfmt_en 1, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length mif->chroma_x_end0 - mif->chroma_x_start0 + 1 , // c length 0); // hz repeat. } else { set_di_if1_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 0, // vfmt_en 0, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length ((mif->luma_x_end0 >> 1) - (mif->luma_x_start0 >> 1) + 1), // c length 0); // hz repeat. } } void set_di_chan2_mif(DI_MIF_t *mif, int urgent, int hold_line) { unsigned long bytes_per_pixel; unsigned long demux_mode; unsigned long <API key>; unsigned long luma0_rpt_loop_end; unsigned long luma0_rpt_loop_pat; bytes_per_pixel = mif->set_separate_en ? 0 : ((mif->video_mode == 1) ? 2 : 1); demux_mode = mif->video_mode & 1; if (mif->src_field_mode == 1) { <API key> = 1; luma0_rpt_loop_end = 1; luma0_rpt_loop_pat = 0x80; } else { <API key> = 0; luma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0; } // General register WRITE_MPEG_REG(DI_CHAN2_GEN_REG, (urgent << 28) | // urgent (urgent << 27) | // luma urgent (1 << 25) | // no dummy data. (hold_line << 19) | // hold lines (1 << 18) | // push dummy pixel (demux_mode << 16) | // demux_mode (bytes_per_pixel << 14) | (0 << 12) | (0 << 10) | (mif->burst_size_y << 8) | ((hold_line == 0 ? 1 : 0) << 7) | //manual start. (0 << 6) | (0 << 1) | (1 << 0) // cntl_enable ); // Canvas WRITE_MPEG_REG(DI_CHAN2_CANVAS, (0 << 16) | // cntl_canvas0_addr2 (0 << 8) | // cntl_canvas0_addr1 (mif->canvas0_addr0 << 0) // cntl_canvas0_addr0 ); // Picture 0 X/Y start,end WRITE_MPEG_REG(DI_CHAN2_LUMA_X, (mif->luma_x_end0 << 16) | // cntl_luma_x_end0 (mif->luma_x_start0 << 0) // cntl_luma_x_start0 ); WRITE_MPEG_REG(DI_CHAN2_LUMA_Y, (mif->luma_y_end0 << 16) | // cntl_luma_y_end0 (mif->luma_y_start0 << 0) // cntl_luma_y_start0 ); // Repeat or skip WRITE_MPEG_REG(DI_CHAN2_RPT_LOOP, (0 << 28) | (0 << 24) | (0 << 20) | (0 << 16) | (0 << 12) | (0 << 8) | (<API key> << 4) | (luma0_rpt_loop_end << 0) ); WRITE_MPEG_REG(<API key>, luma0_rpt_loop_pat); // Dummy pixel value WRITE_MPEG_REG(<API key>, 0x00808000); } void set_di_if0_mif(DI_MIF_t *mif, int urgent, int hold_line) { unsigned long bytes_per_pixel; unsigned long demux_mode; unsigned long chro_rpt_lastl_ctrl; unsigned long <API key>; unsigned long luma0_rpt_loop_end; unsigned long luma0_rpt_loop_pat; unsigned long <API key>; unsigned long <API key>; unsigned long <API key>; if (mif->set_separate_en == 1 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; <API key> = 1; luma0_rpt_loop_end = 1; <API key> = 1; <API key> = 1; luma0_rpt_loop_pat = 0x80; <API key> = 0x80; } else if (mif->set_separate_en == 1 && mif->src_field_mode == 0) { chro_rpt_lastl_ctrl = 1; <API key> = 0; luma0_rpt_loop_end = 0; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x0; <API key> = 0x0; } else if (mif->set_separate_en == 0 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; <API key> = 1; luma0_rpt_loop_end = 1; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x80; <API key> = 0x00; } else { chro_rpt_lastl_ctrl = 0; <API key> = 0; luma0_rpt_loop_end = 0; <API key> = 0; <API key> = 0; luma0_rpt_loop_pat = 0x00; <API key> = 0x00; } bytes_per_pixel = mif->set_separate_en ? 0 : (mif->video_mode ? 2 : 1); demux_mode = mif->video_mode; // General register WRITE_MPEG_REG(VD1_IF0_GEN_REG, (urgent << 28) | // urgent (urgent << 27) | // luma urgent (1 << 25) | // no dummy data. (hold_line << 19) | // hold lines (1 << 18) | // push dummy pixel (demux_mode << 16) | // demux_mode (bytes_per_pixel << 14) | (mif->burst_size_cr << 12) | (mif->burst_size_cb << 10) | (mif->burst_size_y << 8) | (chro_rpt_lastl_ctrl << 6) | (mif->set_separate_en << 1) | (1 << 0) // cntl_enable ); // Canvas WRITE_MPEG_REG(VD1_IF0_CANVAS0, (mif->canvas0_addr2 << 16) | // cntl_canvas0_addr2 (mif->canvas0_addr1 << 8) | // cntl_canvas0_addr1 (mif->canvas0_addr0 << 0) // cntl_canvas0_addr0 ); // Picture 0 X/Y start,end WRITE_MPEG_REG(VD1_IF0_LUMA_X0, (mif->luma_x_end0 << 16) | // cntl_luma_x_end0 (mif->luma_x_start0 << 0) // cntl_luma_x_start0 ); WRITE_MPEG_REG(VD1_IF0_LUMA_Y0, (mif->luma_y_end0 << 16) | // cntl_luma_y_end0 (mif->luma_y_start0 << 0) // cntl_luma_y_start0 ); WRITE_MPEG_REG(VD1_IF0_CHROMA_X0, (mif->chroma_x_end0 << 16) | (mif->chroma_x_start0 << 0) ); WRITE_MPEG_REG(VD1_IF0_CHROMA_Y0, (mif->chroma_y_end0 << 16) | (mif->chroma_y_start0 << 0) ); // Repeat or skip WRITE_MPEG_REG(VD1_IF0_RPT_LOOP, (0 << 28) | (0 << 24) | (0 << 20) | (0 << 16) | (<API key> << 12) | (<API key> << 8) | (<API key> << 4) | (luma0_rpt_loop_end << 0) ) ; WRITE_MPEG_REG(<API key>, luma0_rpt_loop_pat); WRITE_MPEG_REG(<API key>, <API key>); // Dummy pixel value WRITE_MPEG_REG(VD1_IF0_DUMMY_PIXEL, 0x00808000); // Picture 1 unused WRITE_MPEG_REG(VD1_IF0_LUMA_X1, 0); // unused WRITE_MPEG_REG(VD1_IF0_LUMA_Y1, 0); // unused WRITE_MPEG_REG(VD1_IF0_CHROMA_X1, 0); // unused WRITE_MPEG_REG(VD1_IF0_CHROMA_Y1, 0); // unused WRITE_MPEG_REG(VD1_IF0_LUMA_PSEL, 0); // unused only one picture WRITE_MPEG_REG(VD1_IF0_CHROMA_PSEL, 0); // unused only one picture if ((mif->set_separate_en == 1)) { // 4:2:0 block mode. set_vd1_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 1, // vfmt_en 1, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length mif->chroma_x_end0 - mif->chroma_x_start0 + 1 , // c length 0); // hz repeat. } else { set_vd1_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 0, // vfmt_en 0, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length ((mif->luma_x_end0 >> 1) - (mif->luma_x_start0 >> 1) + 1) , //c length 0); // hz repeat. } } //enable deinterlace pre module separated for pre post separate tests. void enable_di_pre( DI_MIF_t *di_inp_mif, DI_MIF_t *di_mem_mif, DI_MIF_t *di_chan2_mif, DI_SIM_MIF_t *di_nrwr_mif, DI_SIM_MIF_t *di_mtnwr_mif, int nr_en, int mtn_en, int pd32_check_en, int pd22_check_en, int hist_check_en, #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) int nr_hfilt_en, int nr_hfilt_mb_en, int mtn_modify_en, #endif int pre_field_num, int pre_viu_link, int hold_line) { int hist_check_only; #if defined(CONFIG_ARCH_MESON2) int nr_zone_0, nr_zone_1, nr_zone_2; if (<API key> == 0) { nr_zone_0 = 1; nr_zone_1 = 3; nr_zone_2 = 5; } else { nr_zone_0 = 3; nr_zone_1 = 6; nr_zone_2 = 10; } #endif hist_check_only = hist_check_en && !nr_en && !mtn_en && !pd22_check_en && !pd32_check_en ; if (nr_en | mtn_en | pd22_check_en || pd32_check_en) { set_di_mem_mif(di_mem_mif, 0, hold_line); // set urgent 0 if (!vdin_en) { set_di_inp_mif(di_inp_mif, 0, hold_line); // set urgent 0 } } if (pd22_check_en || hist_check_only) { set_di_chan2_mif(di_chan2_mif, 0, hold_line); // set urgent 0. } // set nr wr mif interface. if (nr_en) { WRITE_MPEG_REG(DI_NRWR_X, (di_nrwr_mif->start_x << 16) | (di_nrwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_NRWR_Y, (di_nrwr_mif->start_y << 16) | (di_nrwr_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_NRWR_CTRL, di_nrwr_mif->canvas_num); // canvas index. #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_NR_CTRL0, (1 << 31) | // nr yuv enable. (1 << 30) | // nr range. 3 point (0 << 29) | // max of 3 point. (nr_hfilt_en << 28) | // nr hfilter enable. (nr_hfilt_mb_en << 27) | // nr hfilter motion_blur enable. (nr_zone_2 << 16) | // zone 2 (nr_zone_1 << 8) | // zone 1 (nr_zone_0 << 0)); // zone 0 WRITE_MPEG_REG(DI_NR_CTRL2, (10 << 24) | //intra noise level (1 << 16) | // intra no noise level. (10 << 8) | // inter noise level. (1 << 0)); // inter no noise level. WRITE_MPEG_REG(DI_NR_CTRL3, (16 << 16) | // if any one of 3 point mtn larger than 16 don't use 3 point. 720); // if one line eq cnt is larger than this number, this line is not conunted. #endif } // motion wr mif. if (mtn_en) { WRITE_MPEG_REG(DI_MTNWR_X, (di_mtnwr_mif->start_x << 16) | (di_mtnwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNWR_Y, (di_mtnwr_mif->start_y << 16) | (di_mtnwr_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNWR_CTRL, di_mtnwr_mif->canvas_num | // canvas index. (0 << 8)); // urgent. #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_MTN_CTRL, (1 << 31) | // lpf enable. (1 << 30) | // mtn uv enable. (mtn_modify_en << 29) | // no mtn modify. (2 << 24) | // char diff count. (40 << 16) | // black level. (196 << 8) | // white level. (64 << 0)); // char diff level. WRITE_MPEG_REG(DI_MTN_CTRL1, (3 << 8) | // mtn shift if mtn modifty_en 0); // mtn reduce before shift. #endif } // reset pre WRITE_MPEG_REG(DI_PRE_CTRL, READ_MPEG_REG(DI_PRE_CTRL) | 1 << 31); // frame reset for the pre modules. #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_PRE_CTRL, nr_en | // NR enable (mtn_en << 1) | // MTN_EN (pd32_check_en << 2) | // check 3:2 pulldown (pd22_check_en << 3) | // check 2:2 pulldown (1 << 4) | // 2:2 check mid pixel come from next field after MTN. (hist_check_en << 5) | // hist check enable (hist_check_only << 6) | // hist check use chan2. ((!nr_en) << 7) | // hist check use data before noise reduction. ((pd22_check_en || hist_check_only) << 8) | // chan 2 enable for 2:2 pull down check. (pd22_check_en << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (0 << 12) | // pre viu link (hold_line << 16) | // pre hold line number (pre_field_num << 29) | // pre field number. (0x1 << 30) // pre soft rst, pre frame rst. ); #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_PRE_CTRL, nr_en | // NR enable (mtn_en << 1) | // MTN_EN (pd32_check_en << 2) | // check 3:2 pulldown (pd22_check_en << 3) | // check 2:2 pulldown (1 << 4) | // 2:2 check mid pixel come from next field after MTN. (hist_check_en << 5) | // hist check enable (1 << 6) | // hist check use chan2. ((!nr_en) << 7) | // hist check use data before noise reduction. ((pd22_check_en || hist_check_only) << 8) | // chan 2 enable for 2:2 pull down check. (pd22_check_en << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (0 << 12) | // pre viu link (hold_line << 16) | // pre hold line number (1 << 22) | // MTN after NR. (pre_field_num << 29) | // pre field number. (0x1 << 30) // pre soft rst, pre frame rst. ); #endif } // enable di post module for separate test. void enable_di_post( DI_MIF_t *di_buf0_mif, DI_MIF_t *di_buf1_mif, DI_SIM_MIF_t *di_diwr_mif, DI_SIM_MIF_t *di_mtncrd_mif, DI_SIM_MIF_t *di_mtnprd_mif, int ei_en, int blend_en, int blend_mtn_en, int blend_mode, int di_vpp_en, int di_ddr_en, #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) int blend_mtn_filt_en, int blend_data_filt_en, int post_mb_en, #endif int post_field_num, int hold_line) { int ei_only; int buf1_en; ei_only = ei_en && !blend_en && (di_vpp_en || di_ddr_en); buf1_en = (!ei_only && (di_ddr_en || di_vpp_en)); if (ei_en || di_vpp_en || di_ddr_en) { set_di_if0_mif(di_buf0_mif, di_vpp_en, hold_line); } if (!ei_only && (di_ddr_en || di_vpp_en)) { set_di_if1_mif(di_buf1_mif, di_vpp_en, hold_line); } // motion for current display field. if (blend_mtn_en) { WRITE_MPEG_REG(DI_MTNPRD_X, (di_mtnprd_mif->start_x << 16) | (di_mtnprd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNPRD_Y, (di_mtnprd_mif->start_y << 16) | (di_mtnprd_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNCRD_X, (di_mtncrd_mif->start_x << 16) | (di_mtncrd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNCRD_Y, (di_mtncrd_mif->start_y << 16) | (di_mtncrd_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNRD_CTRL, (di_mtnprd_mif->canvas_num << 8) | //mtnp canvas index. (1 << 16) | // urgent di_mtncrd_mif->canvas_num); // current field mtn canvas index. } if (di_ddr_en) { WRITE_MPEG_REG(DI_DIWR_X, (di_diwr_mif->start_x << 16) | (di_diwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_DIWR_Y, (di_diwr_mif->start_y << 16) | (di_diwr_mif->end_y * 2 + 1)); // start_y 0 end_y 479. WRITE_MPEG_REG(DI_DIWR_CTRL, di_diwr_mif->canvas_num | // canvas index. (di_vpp_en << 8)); // urgent. } if (ei_only == 0) { #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_BLEND_CTRL, (READ_MPEG_REG(DI_BLEND_CTRL) & (~((1 << 25) | (3 << 20)))) | // clean some bit we need to set. (blend_mtn_en << 26) | // blend mtn enable. (0 << 25) | // blend with the mtn of the pre display field and next display field. (1 << 24) | // blend with pre display field. (blend_mode << 20) // motion adaptive blend. ); #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_BLEND_CTRL, (post_mb_en << 28) | // post motion blur enable. (0 << 27) | // mtn3p(l, c, r) max. (0 << 26) | // mtn3p(l, c, r) min. (0 << 25) | // mtn3p(l, c, r) ave. (1 << 24) | // mtntopbot max (blend_mtn_filt_en << 23) | // blend mtn filter enable. (blend_data_filt_en << 22) | // blend data filter enable. (blend_mode << 20) | // motion adaptive blend. 25 // kdeint. ); WRITE_MPEG_REG(DI_BLEND_CTRL1, (196 << 24) | // char level (64 << 16) | // angle thredhold. (40 << 8) | // all_af filt thd. (64)); // all 4 equal WRITE_MPEG_REG(DI_BLEND_CTRL2, (4 << 8) | // mtn no mov level. (48)); //black level. #endif } #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_POST_CTRL, ((ei_en | blend_en) << 0) | // line buffer 0 enable (0 << 1) | // line buffer 1 enable (ei_en << 2) | // ei enable (blend_mtn_en << 3) | // mtn line buffer enable (blend_mtn_en << 4) | // mtnp read mif enable (blend_en << 5) | // di blend enble. (1 << 6) | // di mux output enable (di_ddr_en << 7) | // di write to SDRAM enable. (di_vpp_en << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (1 << 12) | // post viu link (hold_line << 16) | // post hold line number (post_field_num << 29) | // post field number. (0x1 << 30) // post soft rst post frame rst. ); #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_POST_CTRL, ((ei_en | blend_en) << 0) | // line buffer 0 enable (0 << 1) | // line buffer 1 enable (ei_en << 2) | // ei enable (blend_mtn_en << 3) | // mtn line buffer enable (blend_mtn_en << 4) | // mtnp read mif enable (blend_en << 5) | // di blend enble. (1 << 6) | // di mux output enable (di_ddr_en << 7) | // di write to SDRAM enable. (di_vpp_en << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (di_vpp_en << 12) | // post viu link (hold_line << 16) | // post hold line number (post_field_num << 29) | // post field number. (0x1 << 30) // post soft rst post frame rst. ); #endif } int di_pre_mode_check(int cur_field) { int i; WRITE_MPEG_REG(DI_INFO_ADDR, 0); for (i = 0; i <= 68; i++) { di_info[cur_field][i] = READ_MPEG_REG(DI_INFO_DATA); } #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_INFO_ADDR, 77); for (i = 77; i <= 82; i++) { di_info[cur_field][i] = READ_MPEG_REG(DI_INFO_DATA); } #endif return (0); } int di_post_mode_check(int cur_field) { int i; WRITE_MPEG_REG(DI_INFO_ADDR, 69); for (i = 69; i <= 76; i++) { di_info[cur_field][i] = READ_MPEG_REG(DI_INFO_DATA); } return (0); } void enable_region_blend( int reg0_en, int reg0_start_x, int reg0_end_x, int reg0_start_y, int reg0_end_y, int reg0_mode, int reg1_en, int reg1_start_x, int reg1_end_x, int reg1_start_y, int reg1_end_y, int reg1_mode, int reg2_en, int reg2_start_x, int reg2_end_x, int reg2_start_y, int reg2_end_y, int reg2_mode, int reg3_en, int reg3_start_x, int reg3_end_x, int reg3_start_y, int reg3_end_y, int reg3_mode) { WRITE_MPEG_REG(DI_BLEND_REG0_X, (reg0_start_x << 16) | reg0_end_x); WRITE_MPEG_REG(DI_BLEND_REG0_Y, (reg0_start_y << 16) | reg0_end_y); WRITE_MPEG_REG(DI_BLEND_REG1_X, (reg1_start_x << 16) | reg1_end_x); WRITE_MPEG_REG(DI_BLEND_REG1_Y, (reg1_start_y << 16) | reg1_end_y); WRITE_MPEG_REG(DI_BLEND_REG2_X, (reg2_start_x << 16) | reg2_end_x); WRITE_MPEG_REG(DI_BLEND_REG2_Y, (reg2_start_y << 16) | reg2_end_y); WRITE_MPEG_REG(DI_BLEND_REG3_X, (reg3_start_x << 16) | reg3_end_x); WRITE_MPEG_REG(DI_BLEND_REG3_Y, (reg3_start_y << 16) | reg3_end_y); WRITE_MPEG_REG(DI_BLEND_CTRL, (READ_MPEG_REG(DI_BLEND_CTRL) & (~(0xfff << 8))) | (reg0_mode << 8) | (reg1_mode << 10) | (reg2_mode << 12) | (reg3_mode << 14) | (reg0_en << 16) | (reg1_en << 17) | (reg2_en << 18) | (reg3_en << 19)); } int check_p32_p22(int cur_field, int pre_field, int pre2_field) { unsigned int cur_data, pre_data, pre2_data; unsigned int cur_num, pre_num, pre2_num; unsigned int data_diff, num_diff; di_p22_info = di_p22_info << 1; cur_data = di_info[cur_field][2]; pre_data = di_info[pre_field][2]; pre2_data = di_info[pre2_field][2]; cur_num = di_info[cur_field][4] & 0xffffff; pre_num = di_info[pre_field][4] & 0xffffff; pre2_num = di_info[pre2_field][4] & 0xffffff; if (cur_data * 2 <= pre_data && pre2_data * 2 <= pre_data && cur_num * 2 <= pre_num && pre2_num * 2 <= pre_num) { di_p22_info |= 1; } di_p32_info = di_p32_info << 1; di_p32_info_2 = di_p32_info_2 << 1; di_p22_info_2 = di_p22_info_2 << 1; cur_data = di_info[cur_field][0]; cur_num = di_info[cur_field][1] & 0xffffff; pre_data = di_info[pre_field][0]; pre_num = di_info[pre_field][1] & 0xffffff; data_diff = cur_data > pre_data ? cur_data - pre_data : pre_data - cur_data; num_diff = cur_num > pre_num ? cur_num - pre_num : pre_num - cur_num; if ((di_p22_info & 0x1) && data_diff * 10 <= cur_data && num_diff * 10 <= cur_num) { di_p22_info_2 |= 1; } if (di_p32_counter > 0 || di_p32_info == 0) { if (cur_data * 2 <= pre_data && cur_num * 50 <= pre_num) { di_p32_info |= 1; last_big_data = pre_data; last_big_num = pre_num; di_p32_counter = -1; } else { last_big_data = 0; last_big_num = 0; if ((di_p32_counter & 0x1) && data_diff * 5 <= cur_data && num_diff * 5 <= cur_num) { di_p32_info_2 |= 1; } } } else { if (cur_data * 2 <= last_big_data && cur_num * 50 <= last_big_num) { di_p32_info |= 1; di_p32_counter = -1; } } di_p32_counter++; return 0; } void <API key>(void) { if (pre_field_counter != di_checked_field) { di_checked_field = pre_field_counter; di_mode_check(pre_field_counter % 4); #ifdef DEBUG debug_array[(pre_field_counter & 0x3ff) * 4] = di_info[pre_field_counter % 4][0]; debug_array[(pre_field_counter & 0x3ff) * 4 + 1] = di_info[pre_field_counter % 4][1] & 0xffffff; debug_array[(pre_field_counter & 0x3ff) * 4 + 2] = di_info[pre_field_counter % 4][2]; debug_array[(pre_field_counter & 0x3ff) * 4 + 3] = di_info[pre_field_counter % 4][4]; #endif if (pre_field_counter >= 3) { check_p32_p22(pre_field_counter % 4, (pre_field_counter + 3) % 4, (pre_field_counter + 2) % 4); #if defined(CONFIG_ARCH_MESON) pattern_22 = pattern_22 << 1; if (di_info[pre_field_counter % 4][4] < di_info[(pre_field_counter + 3) % 4][4]) { pattern_22 |= 1; } #endif } } di_chan2_mif.canvas0_addr0 = <API key> + (field_counter + 3) % 4; di_mem_mif.canvas0_addr0 = <API key> + (field_counter + 2) % 4; blend_mode = 3; #if defined(CONFIG_ARCH_MESON) di_buf0_mif.canvas0_addr0 = <API key> + (field_counter + 3) % 4; // 2:2 check if (((di_p22_info & PATTERN22_MARK) == (<API key> & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (<API key> & PATTERN22_MARK))) { blend_mode = 1; } else if (((di_p22_info & PATTERN22_MARK) == (<API key> & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (<API key> & PATTERN22_MARK))) { blend_mode = 0; } #elif defined(CONFIG_ARCH_MESON2) di_buf1_mif.canvas0_addr0 = <API key> + (field_counter + 1) % 4; if (((di_p22_info & PATTERN22_MARK) == (<API key> & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (<API key> & PATTERN22_MARK))) { di_buf1_mif.canvas0_addr0 = <API key> + (field_counter + 3) % 4; blend_mode = 1; } else if (((di_p22_info & PATTERN22_MARK) == (<API key> & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (<API key> & PATTERN22_MARK))) { di_buf1_mif.canvas0_addr0 = <API key> + (field_counter + 1) % 4; blend_mode = 0; } #endif // pull down pattern check if (pattern_len == 0) { int i, j, pattern, pattern_2, mask; for (j = 5 ; j < 22 ; j++) { mask = (1 << j) - 1; pattern = di_p32_info & mask; pattern_2 = di_p32_info_2 & mask; if (pattern != 0 && pattern_2 != 0 && pattern != mask) { for (i = j ; i < j * 3 ; i += j) if (((di_p32_info >> i) & mask) != pattern || ((di_p32_info_2 >> i) & mask) != pattern_2) { break; } if (i == j * 3) { #if defined(CONFIG_ARCH_MESON) if (pattern_22 & (1 << (j - 1))) { blend_mode = 1; } else { blend_mode = 0; } #elif defined(CONFIG_ARCH_MESON2) if (di_info[(field_counter + 3) % 4][4] < di_info[(field_counter + 2) % 4][4]) { di_buf1_mif.canvas0_addr0 = <API key> + (field_counter + 3) % 4; blend_mode = 1; } else { di_buf1_mif.canvas0_addr0 = <API key> + (field_counter + 1) % 4; blend_mode = 0; } #endif pattern_len = j; break; } } } } else { int i, pattern, pattern_2, mask; mask = (1 << pattern_len) - 1; pattern = di_p32_info & mask; pattern_2 = di_p32_info_2 & mask; for (i = pattern_len ; i < pattern_len * 3 ; i += pattern_len) if (((di_p32_info >> i) & mask) != pattern || ((di_p32_info_2 >> i) & mask) != pattern_2) { break; } if (i == pattern_len * 3) { #if defined(CONFIG_ARCH_MESON) if (pattern_22 & (1 << (pattern_len - 1))) { blend_mode = 1; } else { blend_mode = 0; } #elif defined(CONFIG_ARCH_MESON2) if (di_info[(field_counter + 3) % 4][4] < di_info[(field_counter + 2) % 4][4]) { di_buf1_mif.canvas0_addr0 = <API key> + (field_counter + 3) % 4; blend_mode = 1; } else { di_buf1_mif.canvas0_addr0 = <API key> + (field_counter + 1) % 4; blend_mode = 0; } #endif } else { pattern_len = 0; } } di_nrwr_mif.canvas_num = <API key> + field_counter % 4; di_mtnwr_mif.canvas_num = <API key> + 4 + field_counter % 4; di_mtncrd_mif.canvas_num = <API key> + 4 + (field_counter + 2) % 4; di_mtnprd_mif.canvas_num = <API key> + 4 + (field_counter + 3) % 4; } void pattern_check_pre(void) { di_pre_mode_check(pre_field_counter % 4); #ifdef DEBUG debug_array[(pre_field_counter & 0x3ff) * 4] = di_info[pre_field_counter % 4][0]; debug_array[(pre_field_counter & 0x3ff) * 4 + 1] = di_info[pre_field_counter % 4][1] & 0xffffff; debug_array[(pre_field_counter & 0x3ff) * 4 + 2] = di_info[pre_field_counter % 4][2]; debug_array[(pre_field_counter & 0x3ff) * 4 + 3] = di_info[pre_field_counter % 4][4]; #endif if (pre_field_counter >= 3) { check_p32_p22(pre_field_counter % 4, (pre_field_counter - 1) % 4, (pre_field_counter - 2) % 4); if (di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode == 3) { if (((di_p22_info & PATTERN22_MARK) == (<API key> & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (<API key> & PATTERN22_MARK))) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 1; } else if (((di_p22_info & PATTERN22_MARK) == (<API key> & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (<API key> & PATTERN22_MARK))) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 0; } else if (pattern_len == 0) { di_buf_pool[(pre_field_counter - 2) % DI_BUF_NUM].blend_mode = 3; } if (pattern_len == 0) { int i, j, pattern, pattern_2, mask; for (j = 5 ; j < 22 ; j++) { mask = (1 << j) - 1; pattern = di_p32_info & mask; pattern_2 = di_p32_info_2 & mask; if (pattern != 0 && pattern_2 != 0 && pattern != mask) { for (i = j ; i < j * PATTERN32_NUM ; i += j) if (((di_p32_info >> i) & mask) != pattern || ((di_p32_info_2 >> i) & mask) != pattern_2) { break; } if (i == j * PATTERN32_NUM) { if ((pattern_len == 5) && ((pattern & (pattern - 1)) == 0)) { if ((di_p32_info & 0x1) || (di_p32_info & 0x2) || (di_p32_info & 0x8)) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 0; } else { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 1; } } else { if ((pattern & (pattern - 1)) != 0) { if (di_info[pre_field_counter % 4][4] < di_info[(pre_field_counter - 1) % 4][4]) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 1; } else { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 0; } } } pattern_len = j; break; } } } } else { int i, pattern, pattern_2, mask; mask = (1 << pattern_len) - 1; pattern = di_p32_info & mask; pattern_2 = di_p32_info_2 & mask; for (i = pattern_len ; i < pattern_len * PATTERN32_NUM ; i += pattern_len) if (((di_p32_info >> i) & mask) != pattern || ((di_p32_info_2 >> i) & mask) != pattern_2) { break; } if (i == pattern_len * PATTERN32_NUM) { if ((pattern_len == 5) && ((pattern & (pattern - 1)) == 0)) { if ((di_p32_info & 0x1) || (di_p32_info & 0x2) || (di_p32_info & 0x8)) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 0; } else { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 1; } } else { if ((pattern & (pattern - 1)) != 0) { if (di_info[pre_field_counter % 4][4] < di_info[(pre_field_counter - 1) % 4][4]) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 1; } else { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 0; } } } } else { pattern_len = 0; di_buf_pool[(pre_field_counter - 2) % DI_BUF_NUM].blend_mode = 3; } } } } } void set_vdin_par(int flag, vframe_t *buf) { vdin_en = flag; memcpy(&dummy_buf, buf, sizeof(vframe_t)); } void di_pre_process(void) { unsigned temp = READ_MPEG_REG(DI_INTR_CTRL); unsigned status = READ_MPEG_REG(DI_PRE_CTRL) & 0x2; #if defined(CONFIG_ARCH_MESON2) int nr_hfilt_en, nr_hfilt_mb_en; if (<API key> == 2) { nr_hfilt_en = 1; nr_hfilt_mb_en = 1; } else { nr_hfilt_en = 0; nr_hfilt_mb_en = 0; } #endif if (deinterlace_mode != 2) { return; } if ((prev_struct == 0) && (READ_MPEG_REG(DI_PRE_SIZE) != ((32 - 1) | ((64 - 1) << 16)))) { <API key>(); } if (prev_struct > 0) { #if defined(CONFIG_ARCH_MESON) if ((temp & 0xf) != (status | 0x9)) #elif defined(CONFIG_ARCH_MESON2) if ((temp & 0xf) != (status | 0x1)) #endif return; if (!vdin_en && (prog_field_count == 0) && (buf_recycle_done == 0)) { buf_recycle_done = 1; vf_put(cur_buf, RECEIVER_NAME); } if (di_pre_post_done == 0) { di_pre_post_done = 1; pattern_check_pre(); memcpy((&di_buf_pool[pre_field_counter % DI_BUF_NUM]), cur_buf, sizeof(vframe_t)); di_buf_pool[pre_field_counter % DI_BUF_NUM].blend_mode = blend_mode; di_buf_pool[pre_field_counter % DI_BUF_NUM].canvas0Addr = <API key> + 4; di_buf_pool[pre_field_counter % DI_BUF_NUM].canvas1Addr = <API key> + 4; if (prev_struct == 1) { di_buf_pool[pre_field_counter % DI_BUF_NUM].type = <API key> | VIDTYPE_VIU_422 | <API key> | VIDTYPE_VIU_FIELD; } else { di_buf_pool[pre_field_counter % DI_BUF_NUM].type = <API key> | VIDTYPE_VIU_422 | <API key> | VIDTYPE_VIU_FIELD; } pre_field_counter++; } if ((pre_field_counter >= field_counter + DI_BUF_NUM - 3) && ((pre_field_counter >= field_counter + DI_BUF_NUM - 2) || (field_counter == 0))) { #ifdef DEBUG di_pre_overflow++; #endif return; } if (!vdin_en && (prog_field_count == 0) && (!vf_peek(RECEIVER_NAME))) { #ifdef DEBUG di_pre_underflow++; #endif return; } } if (prog_field_count > 0) { blend_mode = 0; prog_field_count prev_struct = 3 - prev_struct; } else { if (vdin_en) { di_pre_recycle_buf = 1; cur_buf = &dummy_buf; } else { cur_buf = vf_peek(RECEIVER_NAME); if (!cur_buf) { return; } if ((cur_buf->duration == 0) #if defined(<API key>) || (cur_buf->width > 720) #endif ) { di_pre_recycle_buf = 0; return; } di_pre_recycle_buf = 1; cur_buf = vf_get(RECEIVER_NAME); } if (((cur_buf->type & VIDTYPE_TYPEMASK) == <API key> && prev_struct == 1) || ((cur_buf->type & VIDTYPE_TYPEMASK) == <API key> && prev_struct == 2)) { if (!vdin_en) { vf_put(cur_buf, RECEIVER_NAME); } return; } di_inp_top_mif.canvas0_addr0 = di_inp_bot_mif.canvas0_addr0 = cur_buf->canvas0Addr & 0xff; di_inp_top_mif.canvas0_addr1 = di_inp_bot_mif.canvas0_addr1 = (cur_buf->canvas0Addr >> 8) & 0xff; di_inp_top_mif.canvas0_addr2 = di_inp_bot_mif.canvas0_addr2 = (cur_buf->canvas0Addr >> 16) & 0xff; blend_mode = 3; if ((cur_buf->type & VIDTYPE_TYPEMASK) == <API key>) { prev_struct = 1; prog_field_count = 0; } else if ((cur_buf->type & VIDTYPE_TYPEMASK) == <API key>) { prev_struct = 2; prog_field_count = 0; } else { if (prev_struct == 0) { prev_struct = 1; } else { prev_struct = 3 - prev_struct; } if (cur_buf->duration_pulldown > 0) { prog_field_count = 2; } else { prog_field_count = 1; } blend_mode = 1; cur_buf->duration >>= 1; cur_buf->duration_pulldown = 0; } } buf_recycle_done = 0; di_pre_post_done = 0; WRITE_MPEG_REG(DI_INTR_CTRL, temp); if ((READ_MPEG_REG(DI_PRE_SIZE) != ((cur_buf->width - 1) | ((cur_buf->height / 2 - 1) << 16)))) { WRITE_MPEG_REG(DI_INTR_CTRL, 0x000f000f); initial_di_pre(cur_buf->width, cur_buf->height / 2, PRE_HOLD_LINE); di_checked_field = (field_counter + di_checked_field + 1) % DI_BUF_NUM; pre_field_counter = field_counter = 0; di_p32_info = di_p22_info = di_p32_info_2 = di_p22_info_2 = 0; pattern_len = 0; di_mem_mif.luma_x_start0 = 0; di_mem_mif.luma_x_end0 = cur_buf->width - 1; di_mem_mif.luma_y_start0 = 0; di_mem_mif.luma_y_end0 = cur_buf->height / 2 - 1; di_chan2_mif.luma_x_start0 = 0; di_chan2_mif.luma_x_end0 = cur_buf->width - 1; di_chan2_mif.luma_y_start0 = 0; di_chan2_mif.luma_y_end0 = cur_buf->height / 2 - 1; di_nrwr_mif.start_x = 0; di_nrwr_mif.end_x = cur_buf->width - 1; di_nrwr_mif.start_y = 0; di_nrwr_mif.end_y = cur_buf->height / 2 - 1; di_mtnwr_mif.start_x = 0; di_mtnwr_mif.end_x = cur_buf->width - 1; di_mtnwr_mif.start_y = 0; di_mtnwr_mif.end_y = cur_buf->height / 2 - 1; if (cur_buf->type & VIDTYPE_VIU_422) { di_inp_top_mif.video_mode = 0; di_inp_top_mif.set_separate_en = 0; di_inp_top_mif.src_field_mode = 0; di_inp_top_mif.output_field_num = 0; di_inp_top_mif.burst_size_y = 3; di_inp_top_mif.burst_size_cb = 0; di_inp_top_mif.burst_size_cr = 0; memcpy(&di_inp_bot_mif, &di_inp_top_mif, sizeof(DI_MIF_t)); di_inp_top_mif.luma_x_start0 = 0; di_inp_top_mif.luma_x_end0 = cur_buf->width - 1; di_inp_top_mif.luma_y_start0 = 0; di_inp_top_mif.luma_y_end0 = cur_buf->height / 2 - 1; di_inp_top_mif.chroma_x_start0 = 0; di_inp_top_mif.chroma_x_end0 = 0; di_inp_top_mif.chroma_y_start0 = 0; di_inp_top_mif.chroma_y_end0 = 0; di_inp_bot_mif.luma_x_start0 = 0; di_inp_bot_mif.luma_x_end0 = cur_buf->width - 1; di_inp_bot_mif.luma_y_start0 = 0; di_inp_bot_mif.luma_y_end0 = cur_buf->height / 2 - 1; di_inp_bot_mif.chroma_x_start0 = 0; di_inp_bot_mif.chroma_x_end0 = 0; di_inp_bot_mif.chroma_y_start0 = 0; di_inp_bot_mif.chroma_y_end0 = 0; } else { di_inp_top_mif.video_mode = 0; di_inp_top_mif.set_separate_en = 1; di_inp_top_mif.src_field_mode = 1; di_inp_top_mif.burst_size_y = 3; di_inp_top_mif.burst_size_cb = 1; di_inp_top_mif.burst_size_cr = 1; memcpy(&di_inp_bot_mif, &di_inp_top_mif, sizeof(DI_MIF_t)); di_inp_top_mif.output_field_num = 0; // top di_inp_bot_mif.output_field_num = 1; // bottom di_inp_top_mif.luma_x_start0 = 0; di_inp_top_mif.luma_x_end0 = cur_buf->width - 1; di_inp_top_mif.luma_y_start0 = 0; di_inp_top_mif.luma_y_end0 = cur_buf->height - 2; di_inp_top_mif.chroma_x_start0 = 0; di_inp_top_mif.chroma_x_end0 = cur_buf->width / 2 - 1; di_inp_top_mif.chroma_y_start0 = 0; di_inp_top_mif.chroma_y_end0 = cur_buf->height / 2 - 2; di_inp_bot_mif.luma_x_start0 = 0; di_inp_bot_mif.luma_x_end0 = cur_buf->width - 1; di_inp_bot_mif.luma_y_start0 = 1; di_inp_bot_mif.luma_y_end0 = cur_buf->height - 1; di_inp_bot_mif.chroma_x_start0 = 0; di_inp_bot_mif.chroma_x_end0 = cur_buf->width / 2 - 1; di_inp_bot_mif.chroma_y_start0 = 1; di_inp_bot_mif.chroma_y_end0 = cur_buf->height / 2 - 1; } di_nrwr_mif.canvas_num = <API key>; di_mtnwr_mif.canvas_num = <API key> + 1; di_chan2_mif.canvas0_addr0 = <API key> + 2; di_mem_mif.canvas0_addr0 = <API key> + 3; di_buf0_mif.canvas0_addr0 = <API key> + 4; di_buf1_mif.canvas0_addr0 = <API key> + 5; di_mtncrd_mif.canvas_num = <API key> + 6; di_mtnprd_mif.canvas_num = <API key> + 7; <API key>( 0, cur_buf->width - 1, 0, cur_buf->height / 2 - 1, // window 0 ( start_x, end_x, start_y, end_y) 0, cur_buf->width - 1, 0, cur_buf->height / 2 - 1, // window 1 ( start_x, end_x, start_y, end_y) 0, cur_buf->width - 1, 0, cur_buf->height / 2 - 1, // window 2 ( start_x, end_x, start_y, end_y) 0, cur_buf->width - 1, 0, cur_buf->height / 2 - 1, // window 3 ( start_x, end_x, start_y, end_y) 0, cur_buf->width - 1, 0, cur_buf->height / 2 - 1, // window 4 ( start_x, end_x, start_y, end_y) 16, 16, 16, 16, 16, // windows 32 level 256, 256, 256, 256, 256, // windows 22 level 16, 256); // field 32 level; field 22 level } temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((pre_field_counter + di_checked_field) % DI_BUF_NUM); canvas_config(di_nrwr_mif.canvas_num, temp, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((pre_field_counter + di_checked_field) % DI_BUF_NUM) + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT); canvas_config(di_mtnwr_mif.canvas_num, temp, MAX_CANVAS_WIDTH / 2, MAX_CANVAS_HEIGHT / 2, 0, 0); temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((pre_field_counter + di_checked_field + DI_BUF_NUM - 1) % DI_BUF_NUM); canvas_config(di_chan2_mif.canvas0_addr0, temp, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((pre_field_counter + di_checked_field + DI_BUF_NUM - 2) % DI_BUF_NUM); canvas_config(di_mem_mif.canvas0_addr0, temp, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); WRITE_MPEG_REG(DI_PRE_CTRL, 0x3 << 30); enable_di_pre( (prev_struct == 1) ? &di_inp_top_mif : &di_inp_bot_mif, (pre_field_counter < 2) ? ((prev_struct == 1) ? &di_inp_top_mif : &di_inp_bot_mif) : &di_mem_mif, &di_chan2_mif, &di_nrwr_mif, &di_mtnwr_mif, 1, // nr enable (pre_field_counter >= 2), // mtn enable (pre_field_counter >= 2), // 3:2 pulldown check enable (pre_field_counter >= 1), // 2:2 pulldown check enable #if defined(CONFIG_ARCH_MESON) 1, // hist check_en #elif defined(CONFIG_ARCH_MESON2) 0, // hist check_en nr_hfilt_en, // nr_hfilt_en nr_hfilt_mb_en, // nr_hfilt_mb_en 1, // mtn_modify_en, #elif defined(CONFIG_ARCH_MESON3) 1, // hist check_en #endif (prev_struct == 1) ? 1 : 0, // field num for chan2. 1 bottom, 0 top. 0, // pre viu link. PRE_HOLD_LINE ); } void di_pre_isr(struct work_struct *work) { if (!vf_get_provider(RECEIVER_NAME)) { return; } di_pre_process(); } void run_deinterlace(unsigned zoom_start_x_lines, unsigned zoom_end_x_lines, unsigned zoom_start_y_lines, unsigned zoom_end_y_lines, unsigned type, int mode, int hold_line) { int di_width, di_height, di_start_x, di_end_x, di_start_y, di_end_y, size_change, position_change; #if defined(CONFIG_ARCH_MESON2) int nr_hfilt_en, nr_hfilt_mb_en, post_mb_en; if (<API key> == 2) { nr_hfilt_en = 1; nr_hfilt_mb_en = 1; post_mb_en = 1; } else { nr_hfilt_en = 0; nr_hfilt_mb_en = 0; post_mb_en = 0; } #endif di_start_x = zoom_start_x_lines; di_end_x = zoom_end_x_lines; di_width = di_end_x - di_start_x + 1; di_start_y = (zoom_start_y_lines + 1) & 0xfffffffe; di_end_y = (zoom_end_y_lines - 1) | 0x1; di_height = di_end_y - di_start_y + 1; if (deinterlace_mode == 1) { int i; unsigned long addr = di_mem_start; size_change = (READ_MPEG_REG(DI_POST_SIZE) != ((di_width - 1) | ((di_height - 1) << 16))); position_change = ((di_inp_top_mif.luma_x_start0 != di_start_x) || (di_inp_top_mif.luma_y_start0 != di_start_y)); if (size_change || position_change) { if (size_change) { initial_di_prepost(di_width, di_height / 2, di_width, di_height, hold_line); pattern_22 = 0; di_p32_info = di_p22_info = di_p32_info_2 = di_p22_info_2 = 0; pattern_len = 0; } di_mem_mif.luma_x_start0 = di_start_x; di_mem_mif.luma_x_end0 = di_end_x; di_mem_mif.luma_y_start0 = di_start_y / 2; di_mem_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_buf0_mif.luma_x_start0 = di_start_x; di_buf0_mif.luma_x_end0 = di_end_x; di_buf0_mif.luma_y_start0 = di_start_y / 2; di_buf0_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_chan2_mif.luma_x_start0 = di_start_x; di_chan2_mif.luma_x_end0 = di_end_x; di_chan2_mif.luma_y_start0 = di_start_y / 2; di_chan2_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_nrwr_mif.start_x = di_start_x; di_nrwr_mif.end_x = di_end_x; di_nrwr_mif.start_y = di_start_y / 2; di_nrwr_mif.end_y = (di_end_y + 1) / 2 - 1; di_mtnwr_mif.start_x = di_start_x; di_mtnwr_mif.end_x = di_end_x; di_mtnwr_mif.start_y = di_start_y / 2; di_mtnwr_mif.end_y = (di_end_y + 1) / 2 - 1; di_mtncrd_mif.start_x = di_start_x; di_mtncrd_mif.end_x = di_end_x; di_mtncrd_mif.start_y = di_start_y / 2; di_mtncrd_mif.end_y = (di_end_y + 1) / 2 - 1; <API key>( di_start_x, di_end_x, di_start_y, (di_end_y + 1) / 2 - 1, // window 0 ( start_x, end_x, start_y, end_y) di_start_x, di_end_x, di_start_y, (di_end_y + 1) / 2 - 1, // window 1 ( start_x, end_x, start_y, end_y) di_start_x, di_end_x, di_start_y, (di_end_y + 1) / 2 - 1, // window 2 ( start_x, end_x, start_y, end_y) di_start_x, di_end_x, di_start_y, (di_end_y + 1) / 2 - 1, // window 3 ( start_x, end_x, start_y, end_y) di_start_x, di_end_x, di_start_y, (di_end_y + 1) / 2 - 1, // window 4 ( start_x, end_x, start_y, end_y) 16, 16, 16, 16, 16, // windows 32 level 256, 256, 256, 256, 256, // windows 22 level 16, 256); // field 32 level; field 22 level pre_field_counter = field_counter = di_checked_field = 0; if (type & VIDTYPE_VIU_422) { di_inp_top_mif.video_mode = 0; di_inp_top_mif.set_separate_en = 0; di_inp_top_mif.src_field_mode = 0; di_inp_top_mif.output_field_num = 0; di_inp_top_mif.burst_size_y = 3; di_inp_top_mif.burst_size_cb = 0; di_inp_top_mif.burst_size_cr = 0; memcpy(&di_inp_bot_mif, &di_inp_top_mif, sizeof(DI_MIF_t)); di_inp_top_mif.luma_x_start0 = di_start_x; di_inp_top_mif.luma_x_end0 = di_end_x; di_inp_top_mif.luma_y_start0 = di_start_y; di_inp_top_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_inp_top_mif.chroma_x_start0 = 0; di_inp_top_mif.chroma_x_end0 = 0; di_inp_top_mif.chroma_y_start0 = 0; di_inp_top_mif.chroma_y_end0 = 0; di_inp_bot_mif.luma_x_start0 = di_start_x; di_inp_bot_mif.luma_x_end0 = di_end_x; di_inp_bot_mif.luma_y_start0 = di_start_y; di_inp_bot_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_inp_bot_mif.chroma_x_start0 = 0; di_inp_bot_mif.chroma_x_end0 = 0; di_inp_bot_mif.chroma_y_start0 = 0; di_inp_bot_mif.chroma_y_end0 = 0; } else { di_inp_top_mif.video_mode = 0; di_inp_top_mif.set_separate_en = 1; di_inp_top_mif.src_field_mode = 1; di_inp_top_mif.burst_size_y = 3; di_inp_top_mif.burst_size_cb = 1; di_inp_top_mif.burst_size_cr = 1; memcpy(&di_inp_bot_mif, &di_inp_top_mif, sizeof(DI_MIF_t)); di_inp_top_mif.output_field_num = 0; // top di_inp_bot_mif.output_field_num = 1; // bottom di_inp_top_mif.luma_x_start0 = di_start_x; di_inp_top_mif.luma_x_end0 = di_end_x; di_inp_top_mif.luma_y_start0 = di_start_y; di_inp_top_mif.luma_y_end0 = di_end_y - 1; di_inp_top_mif.chroma_x_start0 = di_start_x / 2; di_inp_top_mif.chroma_x_end0 = (di_end_x + 1) / 2 - 1; di_inp_top_mif.chroma_y_start0 = di_start_y / 2; di_inp_top_mif.chroma_y_end0 = (di_end_y + 1) / 2 - 2; di_inp_bot_mif.luma_x_start0 = di_start_x; di_inp_bot_mif.luma_x_end0 = di_end_x; di_inp_bot_mif.luma_y_start0 = di_start_y + 1; di_inp_bot_mif.luma_y_end0 = di_end_y; di_inp_bot_mif.chroma_x_start0 = di_start_x / 2; di_inp_bot_mif.chroma_x_end0 = (di_end_x + 1) / 2 - 1; di_inp_bot_mif.chroma_y_start0 = di_start_y / 2 + 1; di_inp_bot_mif.chroma_y_end0 = (di_end_y + 1) / 2 - 1; } for (i = 0 ; i < 4 ; i++) { canvas_config(<API key> + i, addr, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); addr += MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT; } for (i = 4 ; i < 8 ; i++) { canvas_config(<API key> + i, addr, MAX_CANVAS_WIDTH / 2, MAX_CANVAS_HEIGHT / 2, 0, 0); addr += MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT / 4; } di_inp_top_mif.canvas0_addr0 = di_inp_bot_mif.canvas0_addr0 = <API key>; di_inp_top_mif.canvas0_addr1 = di_inp_bot_mif.canvas0_addr1 = <API key> + 1; di_inp_top_mif.canvas0_addr2 = di_inp_bot_mif.canvas0_addr2 = <API key> + 2; } <API key>(); #if defined(CONFIG_ARCH_MESON) if ((type & VIDTYPE_TYPEMASK) == <API key>) { <API key>( &di_inp_top_mif, &di_mem_mif, (field_counter < 1 ? &di_inp_top_mif : &di_buf0_mif), NULL, &di_chan2_mif, &di_nrwr_mif, NULL, &di_mtnwr_mif, &di_mtncrd_mif, NULL, (pre_field_counter != field_counter || field_counter == 0), // noise reduction enable (field_counter >= 2), // motion check enable (pre_field_counter != field_counter && field_counter >= 2), // 3:2 pulldown check enable (pre_field_counter != field_counter && field_counter >= 1), // 2:2 pulldown check enable (pre_field_counter != field_counter || field_counter == 0), // video luma histogram check enable 1, // edge interpolation module enable. (field_counter >= 2), // blend enable. (field_counter >= 2), // blend with mtn. (field_counter < 2 ? 2 : blend_mode), // blend mode 1, // deinterlace output to VPP. 0, // deinterlace output to DDR SDRAM at same time. (field_counter >= 1), // 1 = current display field is bottom field, we need generated top field. (field_counter >= 1), // pre field num: 1 = current chan2 input field is bottom field. (field_counter >= 1), // prepost link. for the first field it look no need to be propost_link. hold_line ); } else { <API key>( &di_inp_bot_mif, &di_mem_mif, (field_counter < 1 ? &di_inp_bot_mif : &di_buf0_mif), NULL, &di_chan2_mif, &di_nrwr_mif, NULL, &di_mtnwr_mif, &di_mtncrd_mif, NULL, (pre_field_counter != field_counter || field_counter == 0), // noise reduction enable (field_counter >= 2), // motion check enable (pre_field_counter != field_counter && field_counter >= 2), // 3:2 pulldown check enable (pre_field_counter != field_counter && field_counter >= 1), // 2:2 pulldown check enable (pre_field_counter != field_counter || field_counter == 0), // video luma histogram check enable 1, // edge interpolation module enable. (field_counter >= 2), // blend enable. (field_counter >= 2), // blend with mtn. (field_counter < 2 ? 2 : blend_mode), // blend mode: 3 motion adapative blend. 1, // deinterlace output to VPP. 0, // deinterlace output to DDR SDRAM at same time. (field_counter < 1), // 1 = current display field is bottom field, we need generated top field. (field_counter < 1), // pre field num. 1 = current chan2 input field is bottom field. (field_counter >= 1), // prepost link. for the first field it look no need to be propost_link. hold_line ); } #elif defined(CONFIG_ARCH_MESON2) if ((type & VIDTYPE_TYPEMASK) == <API key>) { <API key>( &di_inp_top_mif, (field_counter < 2 ? &di_inp_top_mif : &di_mem_mif), NULL, &di_buf1_mif, &di_chan2_mif, &di_nrwr_mif, NULL, &di_mtnwr_mif, &di_mtncrd_mif, &di_mtnprd_mif, (pre_field_counter != field_counter || field_counter == 0), // noise reduction enable (field_counter >= 2), // motion check enable (pre_field_counter != field_counter && field_counter >= 2), // 3:2 pulldown check enable (pre_field_counter != field_counter && field_counter >= 1), // 2:2 pulldown check enable (pre_field_counter != field_counter || field_counter == 0), // video luma histogram check enable 1, // edge interpolation module enable. (field_counter >= 3), // blend enable. (field_counter >= 3), // blend with mtn. (field_counter < 3 ? 2 : blend_mode), // blend mode 1, // deinterlace output to VPP. 0, // deinterlace output to DDR SDRAM at same time. nr_hfilt_en, // nr_hfilt_en nr_hfilt_mb_en, // nr_hfilt_mb_en 1, // mtn_modify_en, 1, // blend_mtn_filt_en 1, // blend_data_filt_en post_mb_en, // post_mb_en 0, // 1 = current display field is bottom field, we need generated top field. 1, // pre field num: 1 = current chan2 input field is bottom field. (field_counter >= 2), // prepost link. for the first field it look no need to be propost_link. hold_line ); } else { <API key>( &di_inp_bot_mif, (field_counter < 2 ? &di_inp_top_mif : &di_mem_mif), NULL, &di_buf1_mif, &di_chan2_mif, &di_nrwr_mif, NULL, &di_mtnwr_mif, &di_mtncrd_mif, &di_mtnprd_mif, (pre_field_counter != field_counter || field_counter == 0), // noise reduction enable (field_counter >= 2), // motion check enable (pre_field_counter != field_counter && field_counter >= 2), // 3:2 pulldown check enable (pre_field_counter != field_counter && field_counter >= 1), // 2:2 pulldown check enable (pre_field_counter != field_counter || field_counter == 0), // video luma histogram check enable 1, // edge interpolation module enable. (field_counter >= 3), // blend enable. (field_counter >= 3), // blend with mtn. (field_counter < 3 ? 2 : blend_mode), // blend mode: 3 motion adapative blend. 1, // deinterlace output to VPP. 0, // deinterlace output to DDR SDRAM at same time. nr_hfilt_en, // nr_hfilt_en nr_hfilt_mb_en, // nr_hfilt_mb_en 1, // mtn_modify_en, 1, // blend_mtn_filt_en 1, // blend_data_filt_en post_mb_en, // post_mb_en 1, // 1 = current display field is bottom field, we need generated top field. 0, // pre field num. 1 = current chan2 input field is bottom field. (field_counter >= 2), // prepost link. for the first field it look no need to be propost_link. hold_line ); } #endif pre_field_counter = field_counter; } else { int post_blend_en, post_blend_mode; if (READ_MPEG_REG(DI_POST_SIZE) != ((di_width - 1) | ((di_height - 1) << 16)) || (di_buf0_mif.luma_x_start0 != di_start_x) || (di_buf0_mif.luma_y_start0 != di_start_y / 2)) { initial_di_post(di_width, di_height, hold_line); di_buf0_mif.luma_x_start0 = di_start_x; di_buf0_mif.luma_x_end0 = di_end_x; di_buf0_mif.luma_y_start0 = di_start_y / 2; di_buf0_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_buf1_mif.luma_x_start0 = di_start_x; di_buf1_mif.luma_x_end0 = di_end_x; di_buf1_mif.luma_y_start0 = di_start_y / 2; di_buf1_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_mtncrd_mif.start_x = di_start_x; di_mtncrd_mif.end_x = di_end_x; di_mtncrd_mif.start_y = di_start_y / 2; di_mtncrd_mif.end_y = (di_end_y + 1) / 2 - 1; di_mtnprd_mif.start_x = di_start_x; di_mtnprd_mif.end_x = di_end_x; di_mtnprd_mif.start_y = di_start_y / 2; di_mtnprd_mif.end_y = (di_end_y + 1) / 2 - 1; } post_blend_en = 1; post_blend_mode = mode; if ((post_blend_mode == 3) && (field_counter <= 2)) { post_blend_en = 0; post_blend_mode = 2; } enable_di_post( &di_buf0_mif, &di_buf1_mif, NULL, &di_mtncrd_mif, &di_mtnprd_mif, 1, // ei enable post_blend_en, // blend enable post_blend_en, // blend mtn enable post_blend_mode, // blend mode. 1, // di_vpp_en. 0, // di_ddr_en. #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) 1, // blend_mtn_filt_en 1, // blend_data_filt_en post_mb_en, // post_mb_en #endif (type & VIDTYPE_TYPEMASK) == <API key> ? 0 : 1, // 1 bottom generate top hold_line ); } } void di_pre_timer_func(unsigned long arg) { struct timer_list *timer = (struct timer_list *)arg; schedule_work(&di_pre_work); timer->expires = jiffies + DI_PRE_INTERVAL; add_timer(timer); } void deinterlace_init(void) { di_mem_mif.chroma_x_start0 = 0; di_mem_mif.chroma_x_end0 = 0; di_mem_mif.chroma_y_start0 = 0; di_mem_mif.chroma_y_end0 = 0; di_mem_mif.video_mode = 0; di_mem_mif.set_separate_en = 0; di_mem_mif.src_field_mode = 0; di_mem_mif.output_field_num = 0; di_mem_mif.burst_size_y = 3; di_mem_mif.burst_size_cb = 0; di_mem_mif.burst_size_cr = 0; di_mem_mif.canvas0_addr1 = 0; di_mem_mif.canvas0_addr2 = 0; memcpy(&di_buf0_mif, &di_mem_mif, sizeof(DI_MIF_t)); memcpy(&di_buf1_mif, &di_mem_mif, sizeof(DI_MIF_t)); memcpy(&di_chan2_mif, &di_buf1_mif, sizeof(DI_MIF_t)); WRITE_MPEG_REG(DI_PRE_HOLD, (1 << 31) | (31 << 16) | 31); #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_NRMTN_CTRL0, 0xb00a0603); #endif INIT_WORK(&di_pre_work, di_pre_isr); init_timer(&di_pre_timer); di_pre_timer.data = (ulong) & di_pre_timer; di_pre_timer.function = di_pre_timer_func; di_pre_timer.expires = jiffies + DI_PRE_INTERVAL; add_timer(&di_pre_timer); } static int deinterlace_probe(struct platform_device *pdev) { struct resource *mem; printk("Amlogic deinterlace init\n"); if (!(mem = <API key>(pdev, IORESOURCE_MEM, 0))) { printk("\ndeinterlace memory resource undefined.\n"); return -EFAULT; } // declare deinterlace memory di_mem_start = mem->start; printk("Deinterlace memory: start = 0x%x, end = 0x%x\n", di_mem_start, mem->end); deinterlace_init(); return 0; } static int deinterlace_remove(struct platform_device *pdev) { printk("Amlogic deinterlace release\n"); del_timer_sync(&di_pre_timer); return 0; } static struct platform_driver deinterlace_driver = { .probe = deinterlace_probe, .remove = deinterlace_remove, .driver = { .name = "deinterlace", } }; static int __init <API key>(void) { if (<API key>(&deinterlace_driver)) { printk("failed to register deinterlace module\n"); return -ENODEV; } return 0; } static void __exit <API key>(void) { <API key>(&deinterlace_driver); return; } MODULE_PARM_DESC(deinterlace_mode, "\n deinterlace mode \n"); module_param(deinterlace_mode, int, 0664); #if defined(CONFIG_ARCH_MESON2) MODULE_PARM_DESC(<API key>, "\n noise reduction level \n"); module_param(<API key>, int, 0664); #endif module_init(<API key>); module_exit(<API key>); MODULE_DESCRIPTION("AMLOGIC deinterlace driver"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Qi Wang <qi.wang@amlogic.com>");
#pragma once #include <functional> #include <utility> #include <variant> namespace Common { // A Lazy object holds a value. If a Lazy object is constructed using // a function as an argument, that function will be called to compute // the value the first time any code tries to access the value. template <typename T> class Lazy { public: Lazy() : m_value(T()) {} Lazy(const std::variant<T, std::function<T()>>& value) : m_value(value) {} Lazy(std::variant<T, std::function<T()>>&& value) : m_value(std::move(value)) {} const Lazy<T>& operator=(const std::variant<T, std::function<T()>>& value) { m_value = value; return *this; } const Lazy<T>& operator=(std::variant<T, std::function<T()>>&& value) { m_value = std::move(value); return *this; } const T& operator*() const { return *ComputeValue(); } const T* operator->() const { return ComputeValue(); } T& operator*() { return *ComputeValue(); } T* operator->() { return ComputeValue(); } private: T* ComputeValue() const { if (!std::holds_alternative<T>(m_value)) m_value = std::get<std::function<T()>>(m_value)(); return &std::get<T>(m_value); } mutable std::variant<T, std::function<T()>> m_value; }; }
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ #ifndef <API key> #define <API key> #include "st.h" #define <API key> (<API key> ()) #define <API key>(obj) (<API key> ((obj), <API key>, <API key>)) #define <API key>(klass) (<API key> ((klass), <API key>, <API key>)) #define <API key>(obj) (<API key> ((obj), <API key>)) #define <API key>(klass) (<API key> ((klass), <API key>)) #define <API key>(obj) (<API key> ((obj), <API key>, <API key>)) typedef struct { float min_size; float natural_size; /* <private> */ guint _refcount; } <API key>; #define <API key> (<API key> ()) GType <API key> (void); typedef struct <API key> <API key>; typedef struct <API key> <API key>; typedef struct <API key> <API key>; struct <API key> { StContainer parent; <API key> *priv; }; struct <API key> { StContainerClass parent_class; }; GType <API key> (void) G_GNUC_CONST; guint <API key> (<API key> *self); gboolean <API key> (<API key> *self, ClutterActor *child); void <API key> (<API key> *self, ClutterActor *child, gboolean skip); #endif /* <API key> */
#include "config.h" #include "system.h" #include "coretypes.h" #include "opts.h" #include "toplev.h" #include "hash-set.h" #include "machmode.h" #include "vec.h" #include "double-int.h" #include "input.h" #include "alias.h" #include "symtab.h" #include "options.h" #include "wide-int.h" #include "inchash.h" #include "real.h" #include "fixed-value.h" #include "tree.h" #include "fold-const.h" #include "stor-layout.h" #include "diagnostic-core.h" #include "tm.h" #include "predict.h" #include "basic-block.h" #include "hash-map.h" #include "is-a.h" #include "plugin-api.h" #include "hard-reg-set.h" #include "input.h" #include "function.h" #include "ipa-ref.h" #include "cgraph.h" #include "tree-ssa-operands.h" #include "tree-pass.h" #include "langhooks.h" #include "bitmap.h" #include "inchash.h" #include "alloc-pool.h" #include "symbol-summary.h" #include "ipa-prop.h" #include "common.h" #include "debug.h" #include "tree-ssa-alias.h" #include "internal-fn.h" #include "gimple-expr.h" #include "gimple.h" #include "lto.h" #include "lto-tree.h" #include "lto-streamer.h" #include "lto-section-names.h" #include "tree-streamer.h" #include "splay-tree.h" #include "lto-partition.h" #include "data-streamer.h" #include "context.h" #include "pass_manager.h" #include "ipa-inline.h" #include "params.h" #include "ipa-utils.h" #include "gomp-constants.h" /* Number of parallel tasks to run, -1 if we want to use GNU Make jobserver. */ static int lto_parallelism; static GTY(()) tree <API key>; static GTY(()) const unsigned char *<API key>; /* Returns a hash code for P. */ static hashval_t hash_name (const void *p) { const struct lto_section_slot *ds = (const struct lto_section_slot *) p; return (hashval_t) htab_hash_string (ds->name); } /* Returns nonzero if P1 and P2 are equal. */ static int eq_name (const void *p1, const void *p2) { const struct lto_section_slot *s1 = (const struct lto_section_slot *) p1; const struct lto_section_slot *s2 = (const struct lto_section_slot *) p2; return strcmp (s1->name, s2->name) == 0; } /* Free lto_section_slot */ static void free_with_string (void *arg) { struct lto_section_slot *s = (struct lto_section_slot *)arg; free (CONST_CAST (char *, s->name)); free (arg); } /* Create section hash table */ htab_t <API key> (void) { return htab_create (37, hash_name, eq_name, free_with_string); } /* Delete an allocated integer KEY in the splay tree. */ static void <API key> (splay_tree_key key) { free ((void *) key); } /* Compare splay tree node ids A and B. */ static int <API key> (splay_tree_key a, splay_tree_key b) { unsigned HOST_WIDE_INT ai; unsigned HOST_WIDE_INT bi; ai = *(unsigned HOST_WIDE_INT *) a; bi = *(unsigned HOST_WIDE_INT *) b; if (ai < bi) return -1; else if (ai > bi) return 1; return 0; } /* Look up splay tree node by ID in splay tree T. */ static splay_tree_node <API key> (splay_tree t, unsigned HOST_WIDE_INT id) { return splay_tree_lookup (t, (splay_tree_key) &id); } /* Check if KEY has ID. */ static bool <API key> (splay_tree_key key, unsigned HOST_WIDE_INT id) { return *(unsigned HOST_WIDE_INT *) key == id; } /* Insert a splay tree node into tree T with ID as key and FILE_DATA as value. The ID is allocated separately because we need HOST_WIDE_INTs which may be wider than a splay_tree_key. */ static void <API key> (splay_tree t, unsigned HOST_WIDE_INT id, struct lto_file_decl_data *file_data) { unsigned HOST_WIDE_INT *idp = XCNEW (unsigned HOST_WIDE_INT); *idp = id; splay_tree_insert (t, (splay_tree_key) idp, (splay_tree_value) file_data); } /* Create a splay tree. */ static splay_tree lto_splay_tree_new (void) { return splay_tree_new (<API key>, <API key>, NULL); } /* Return true when NODE has a clone that is analyzed (i.e. we need to load its body even if the node itself is not needed). */ static bool <API key> (struct cgraph_node *node) { struct cgraph_node *orig = node; node = node->clones; if (node) while (node != orig) { if (node->analyzed) return true; if (node->clones) node = node->clones; else if (node->next_sibling_clone) node = node->next_sibling_clone; else { while (node != orig && !node->next_sibling_clone) node = node->clone_of; if (node != orig) node = node->next_sibling_clone; } } return false; } /* Read the function body for the function associated with NODE. */ static void <API key> (struct cgraph_node *node) { tree decl; decl = node->decl; /* Read in functions with body (analyzed nodes) and also functions that are needed to produce virtual clones. */ if ((node->has_gimple_body_p () && node->analyzed) || node-><API key> || <API key> (node)) { /* Clones don't need to be read. */ if (node->clone_of) return; if (<API key> (decl) && !<API key>) <API key> = <API key> (decl); } /* Let the middle end know about the function. */ <API key> (decl, 1, 0); } /* Decode the content of memory pointed to by DATA in the in decl state object STATE. DATA_IN points to a data_in structure for decoding. Return the address after the decoded object in the input. */ static const uint32_t * <API key> (struct data_in *data_in, const uint32_t *data, struct lto_in_decl_state *state) { uint32_t ix; tree decl; uint32_t i, j; ix = *data++; decl = <API key> (data_in->reader_cache, ix); if (!<API key> (decl)) { gcc_assert (decl == void_type_node); decl = NULL_TREE; } state->fn_decl = decl; for (i = 0; i < LTO_N_DECL_STREAMS; i++) { uint32_t size = *data++; vec<tree, va_gc> *decls = NULL; vec_alloc (decls, size); for (j = 0; j < size; j++) vec_safe_push (decls, <API key> (data_in->reader_cache, data[j])); state->streams[i] = decls; data += size; } return data; } /* Global canonical type table. */ static htab_t <API key>; static hash_map<const_tree, hashval_t> *<API key>; static unsigned long <API key>; static unsigned long <API key>; static void <API key> (tree type, inchash::hash &hstate); static hashval_t <API key> (const void *p); static void <API key> (tree t, hashval_t hash); /* Returning a hash value for gimple type TYPE. The hash value returned is equal for types considered compatible by <API key>. */ static hashval_t hash_canonical_type (tree type) { inchash::hash hstate; /* Combine a few common features of types so that types are grouped into smaller sets; when searching for existing matching types to merge, only existing types having the same features as the new type will be checked. */ hstate.add_int (TREE_CODE (type)); hstate.add_int (TYPE_MODE (type)); /* Incorporate common features of numerical types. */ if (INTEGRAL_TYPE_P (type) || SCALAR_FLOAT_TYPE_P (type) || FIXED_POINT_TYPE_P (type) || TREE_CODE (type) == OFFSET_TYPE || POINTER_TYPE_P (type)) { hstate.add_int (TYPE_UNSIGNED (type)); hstate.add_int (TYPE_PRECISION (type)); } if (VECTOR_TYPE_P (type)) { hstate.add_int (<API key> (type)); hstate.add_int (TYPE_UNSIGNED (type)); } if (TREE_CODE (type) == COMPLEX_TYPE) hstate.add_int (TYPE_UNSIGNED (type)); /* For pointer and reference types, fold in information about the type pointed to but do not recurse to the pointed-to type. */ if (POINTER_TYPE_P (type)) { hstate.add_int (TYPE_ADDR_SPACE (TREE_TYPE (type))); hstate.add_int (TREE_CODE (TREE_TYPE (type))); } /* For integer types hash only the string flag. */ if (TREE_CODE (type) == INTEGER_TYPE) hstate.add_int (TYPE_STRING_FLAG (type)); /* For array types hash the domain bounds and the string flag. */ if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type)) { hstate.add_int (TYPE_STRING_FLAG (type)); /* OMP lowering can introduce error_mark_node in place of random local decls in types. */ if (TYPE_MIN_VALUE (TYPE_DOMAIN (type)) != error_mark_node) inchash::add_expr (TYPE_MIN_VALUE (TYPE_DOMAIN (type)), hstate); if (TYPE_MAX_VALUE (TYPE_DOMAIN (type)) != error_mark_node) inchash::add_expr (TYPE_MAX_VALUE (TYPE_DOMAIN (type)), hstate); } /* Recurse for aggregates with a single element type. */ if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == COMPLEX_TYPE || TREE_CODE (type) == VECTOR_TYPE) <API key> (TREE_TYPE (type), hstate); /* Incorporate function return and argument types. */ if (TREE_CODE (type) == FUNCTION_TYPE || TREE_CODE (type) == METHOD_TYPE) { unsigned na; tree p; /* For method types also incorporate their parent class. */ if (TREE_CODE (type) == METHOD_TYPE) <API key> (<API key> (type), hstate); <API key> (TREE_TYPE (type), hstate); for (p = TYPE_ARG_TYPES (type), na = 0; p; p = TREE_CHAIN (p)) { <API key> (TREE_VALUE (p), hstate); na++; } hstate.add_int (na); } if (<API key> (type)) { unsigned nf; tree f; for (f = TYPE_FIELDS (type), nf = 0; f; f = TREE_CHAIN (f)) if (TREE_CODE (f) == FIELD_DECL) { <API key> (TREE_TYPE (f), hstate); nf++; } hstate.add_int (nf); } return hstate.end(); } /* Returning a hash value for gimple type TYPE combined with VAL. */ static void <API key> (tree type, inchash::hash &hstate) { hashval_t v; /* An already processed type. */ if (TYPE_CANONICAL (type)) { type = TYPE_CANONICAL (type); v = <API key> (type); } else { /* Canonical types should not be able to form SCCs by design, this recursion is just because we do not register canonical types in optimal order. To avoid quadratic behavior also register the type here. */ v = hash_canonical_type (type); <API key> (type, v); } hstate.add_int (v); } /* Returns the hash for a canonical type P. */ static hashval_t <API key> (const void *p) { <API key>++; hashval_t *slot = <API key>->get ((const_tree) p); gcc_assert (slot != NULL); return *slot; } /* The TYPE_CANONICAL merging machinery. It should closely resemble the middle-end types_compatible_p function. It needs to avoid claiming types are different for types that should be treated the same with respect to TBAA. Canonical types are also used for IL consistency checks via the <API key> predicate which does not handle all type kinds itself but falls back to pointer-comparison of TYPE_CANONICAL for aggregates for example. */ /* Return true iff T1 and T2 are structurally identical for what TBAA is concerned. */ static bool <API key> (tree t1, tree t2) { /* Before starting to set up the SCC machinery handle simple cases. */ /* Check first for the obvious case of pointer identity. */ if (t1 == t2) return true; /* Check that we have two types to compare. */ if (t1 == NULL_TREE || t2 == NULL_TREE) return false; /* If the types have been previously registered and found equal they still are. */ if (TYPE_CANONICAL (t1) && TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2)) return true; /* Can't be the same type if the types don't have the same code. */ if (TREE_CODE (t1) != TREE_CODE (t2)) return false; /* Qualifiers do not matter for canonical type comparison purposes. */ /* Void types and nullptr types are always the same. */ if (TREE_CODE (t1) == VOID_TYPE || TREE_CODE (t1) == NULLPTR_TYPE) return true; /* Can't be the same type if they have different mode. */ if (TYPE_MODE (t1) != TYPE_MODE (t2)) return false; /* Non-aggregate types can be handled cheaply. */ if (INTEGRAL_TYPE_P (t1) || SCALAR_FLOAT_TYPE_P (t1) || FIXED_POINT_TYPE_P (t1) || TREE_CODE (t1) == VECTOR_TYPE || TREE_CODE (t1) == COMPLEX_TYPE || TREE_CODE (t1) == OFFSET_TYPE || POINTER_TYPE_P (t1)) { /* Can't be the same type if they have different sign or precision. */ if (TYPE_PRECISION (t1) != TYPE_PRECISION (t2) || TYPE_UNSIGNED (t1) != TYPE_UNSIGNED (t2)) return false; if (TREE_CODE (t1) == INTEGER_TYPE && TYPE_STRING_FLAG (t1) != TYPE_STRING_FLAG (t2)) return false; /* For canonical type comparisons we do not want to build SCCs so we cannot compare pointed-to types. But we can, for now, require the same pointed-to type kind and match what <API key> would do. */ if (POINTER_TYPE_P (t1)) { if (TYPE_ADDR_SPACE (TREE_TYPE (t1)) != TYPE_ADDR_SPACE (TREE_TYPE (t2))) return false; if (TREE_CODE (TREE_TYPE (t1)) != TREE_CODE (TREE_TYPE (t2))) return false; } /* Tail-recurse to components. */ if (TREE_CODE (t1) == VECTOR_TYPE || TREE_CODE (t1) == COMPLEX_TYPE) return <API key> (TREE_TYPE (t1), TREE_TYPE (t2)); return true; } /* Do type-specific comparisons. */ switch (TREE_CODE (t1)) { case ARRAY_TYPE: /* Array types are the same if the element types are the same and the number of elements are the same. */ if (!<API key> (TREE_TYPE (t1), TREE_TYPE (t2)) || TYPE_STRING_FLAG (t1) != TYPE_STRING_FLAG (t2) || <API key> (t1) != <API key> (t2)) return false; else { tree i1 = TYPE_DOMAIN (t1); tree i2 = TYPE_DOMAIN (t2); /* For an incomplete external array, the type domain can be NULL_TREE. Check this condition also. */ if (i1 == NULL_TREE && i2 == NULL_TREE) return true; else if (i1 == NULL_TREE || i2 == NULL_TREE) return false; else { tree min1 = TYPE_MIN_VALUE (i1); tree min2 = TYPE_MIN_VALUE (i2); tree max1 = TYPE_MAX_VALUE (i1); tree max2 = TYPE_MAX_VALUE (i2); /* The minimum/maximum values have to be the same. */ if ((min1 == min2 || (min1 && min2 && ((TREE_CODE (min1) == PLACEHOLDER_EXPR && TREE_CODE (min2) == PLACEHOLDER_EXPR) || operand_equal_p (min1, min2, 0)))) && (max1 == max2 || (max1 && max2 && ((TREE_CODE (max1) == PLACEHOLDER_EXPR && TREE_CODE (max2) == PLACEHOLDER_EXPR) || operand_equal_p (max1, max2, 0))))) return true; else return false; } } case METHOD_TYPE: case FUNCTION_TYPE: /* Function types are the same if the return type and arguments types are the same. */ if (!<API key> (TREE_TYPE (t1), TREE_TYPE (t2))) return false; if (!<API key> (t1, t2)) return false; if (TYPE_ARG_TYPES (t1) == TYPE_ARG_TYPES (t2)) return true; else { tree parms1, parms2; for (parms1 = TYPE_ARG_TYPES (t1), parms2 = TYPE_ARG_TYPES (t2); parms1 && parms2; parms1 = TREE_CHAIN (parms1), parms2 = TREE_CHAIN (parms2)) { if (!<API key> (TREE_VALUE (parms1), TREE_VALUE (parms2))) return false; } if (parms1 || parms2) return false; return true; } case RECORD_TYPE: case UNION_TYPE: case QUAL_UNION_TYPE: { tree f1, f2; /* For aggregate types, all the fields must be the same. */ for (f1 = TYPE_FIELDS (t1), f2 = TYPE_FIELDS (t2); f1 || f2; f1 = TREE_CHAIN (f1), f2 = TREE_CHAIN (f2)) { /* Skip non-fields. */ while (f1 && TREE_CODE (f1) != FIELD_DECL) f1 = TREE_CHAIN (f1); while (f2 && TREE_CODE (f2) != FIELD_DECL) f2 = TREE_CHAIN (f2); if (!f1 || !f2) break; /* The fields must have the same name, offset and type. */ if (<API key> (f1) != <API key> (f2) || !<API key> (f1, f2) || !<API key> (TREE_TYPE (f1), TREE_TYPE (f2))) return false; } /* If one aggregate has more fields than the other, they are not the same. */ if (f1 || f2) return false; return true; } default: gcc_unreachable (); } } /* Returns nonzero if P1 and P2 are equal. */ static int <API key> (const void *p1, const void *p2) { const_tree t1 = (const_tree) p1; const_tree t2 = (const_tree) p2; return <API key> (CONST_CAST_TREE (t1), CONST_CAST_TREE (t2)); } /* Main worker for <API key>. */ static void <API key> (tree t, hashval_t hash) { void **slot; gcc_checking_assert (TYPE_P (t) && !TYPE_CANONICAL (t)); slot = <API key> (<API key>, t, hash, INSERT); if (*slot) { tree new_type = (tree)(*slot); gcc_checking_assert (new_type != t); TYPE_CANONICAL (t) = new_type; } else { TYPE_CANONICAL (t) = t; *slot = (void *) t; /* Cache the just computed hash value. */ <API key>++; bool existed_p = <API key>->put (t, hash); gcc_assert (!existed_p); } } /* Register type T in the global type table gimple_types and set TYPE_CANONICAL of T accordingly. This is used by LTO to merge structurally equivalent types for type-based aliasing purposes across different TUs and languages. ??? This merging does not exactly match how the tree.c middle-end functions will assign TYPE_CANONICAL when new types are created during optimization (which at least happens for pointer and array types). */ static void <API key> (tree t) { if (TYPE_CANONICAL (t)) return; <API key> (t, hash_canonical_type (t)); } /* Re-compute TYPE_CANONICAL for NODE and related types. */ static void <API key> (tree node, bool first_p) { if (!node || !TYPE_P (node)) return; if (first_p) TYPE_CANONICAL (node) = NULL_TREE; if (POINTER_TYPE_P (node) || TREE_CODE (node) == COMPLEX_TYPE || TREE_CODE (node) == ARRAY_TYPE) <API key> (TREE_TYPE (node), first_p); if (!first_p) <API key> (node); } /* Remember trees that contains references to declarations. */ static GTY(()) vec <tree, va_gc> *tree_with_vars; #define CHECK_VAR(tt) \ do \ { \ if ((tt) && <API key> (tt) \ && (TREE_PUBLIC (tt) || DECL_EXTERNAL (tt))) \ return true; \ } while (0) #define CHECK_NO_VAR(tt) \ gcc_checking_assert (!(tt) || !<API key> (tt)) /* Check presence of pointers to decls in fields of a tree_typed T. */ static inline bool <API key> (tree t) { CHECK_NO_VAR (TREE_TYPE (t)); return false; } /* Check presence of pointers to decls in fields of a tree_common T. */ static inline bool <API key> (tree t) { if (<API key> (t)) return true; CHECK_NO_VAR (TREE_CHAIN (t)); return false; } /* Check presence of pointers to decls in fields of a decl_minimal T. */ static inline bool <API key> (tree t) { if (<API key> (t)) return true; CHECK_NO_VAR (DECL_NAME (t)); CHECK_VAR (DECL_CONTEXT (t)); return false; } /* Check presence of pointers to decls in fields of a decl_common T. */ static inline bool <API key> (tree t) { if (<API key> (t)) return true; CHECK_VAR (DECL_SIZE (t)); CHECK_VAR (DECL_SIZE_UNIT (t)); CHECK_VAR (DECL_INITIAL (t)); CHECK_NO_VAR (DECL_ATTRIBUTES (t)); CHECK_VAR (<API key> (t)); return false; } /* Check presence of pointers to decls in fields of a decl_with_vis T. */ static inline bool <API key> (tree t) { if (<API key> (t)) return true; /* Accessor macro has side-effects, use field-name here. */ CHECK_NO_VAR (t->decl_with_vis.assembler_name); return false; } /* Check presence of pointers to decls in fields of a decl_non_common T. */ static inline bool <API key> (tree t) { if (<API key> (t)) return true; CHECK_NO_VAR (DECL_RESULT_FLD (t)); return false; } /* Check presence of pointers to decls in fields of a decl_non_common T. */ static bool <API key> (tree t) { if (<API key> (t)) return true; CHECK_NO_VAR (DECL_ARGUMENTS (t)); CHECK_NO_VAR (DECL_VINDEX (t)); CHECK_VAR (<API key> (t)); return false; } /* Check presence of pointers to decls in fields of a field_decl T. */ static bool <API key> (tree t) { if (<API key> (t)) return true; CHECK_VAR (DECL_FIELD_OFFSET (t)); CHECK_NO_VAR (DECL_BIT_FIELD_TYPE (t)); CHECK_NO_VAR (DECL_QUALIFIER (t)); CHECK_NO_VAR (<API key> (t)); CHECK_NO_VAR (DECL_FCONTEXT (t)); return false; } /* Check presence of pointers to decls in fields of a type T. */ static bool <API key> (tree t) { if (<API key> (t)) return true; CHECK_NO_VAR (TYPE_CACHED_VALUES (t)); CHECK_VAR (TYPE_SIZE (t)); CHECK_VAR (TYPE_SIZE_UNIT (t)); CHECK_NO_VAR (TYPE_ATTRIBUTES (t)); CHECK_NO_VAR (TYPE_NAME (t)); CHECK_VAR (TYPE_MINVAL (t)); CHECK_VAR (TYPE_MAXVAL (t)); /* Accessor is for derived node types only. */ CHECK_NO_VAR (t->type_non_common.binfo); CHECK_VAR (TYPE_CONTEXT (t)); CHECK_NO_VAR (TYPE_CANONICAL (t)); CHECK_NO_VAR (TYPE_MAIN_VARIANT (t)); CHECK_NO_VAR (TYPE_NEXT_VARIANT (t)); return false; } /* Check presence of pointers to decls in fields of a BINFO T. */ static bool <API key> (tree t) { unsigned HOST_WIDE_INT i, n; if (<API key> (t)) return true; CHECK_VAR (BINFO_VTABLE (t)); CHECK_NO_VAR (BINFO_OFFSET (t)); CHECK_NO_VAR (BINFO_VIRTUALS (t)); CHECK_NO_VAR (BINFO_VPTR_FIELD (t)); n = vec_safe_length (BINFO_BASE_ACCESSES (t)); for (i = 0; i < n; i++) CHECK_NO_VAR (BINFO_BASE_ACCESS (t, i)); /* Do not walk <API key>, BINFO_SUBVTT_INDEX and BINFO_VPTR_INDEX; these are used by C++ FE only. */ n = BINFO_N_BASE_BINFOS (t); for (i = 0; i < n; i++) CHECK_NO_VAR (BINFO_BASE_BINFO (t, i)); return false; } /* Check presence of pointers to decls in fields of a CONSTRUCTOR T. */ static bool <API key> (tree t) { unsigned HOST_WIDE_INT idx; constructor_elt *ce; if (<API key> (t)) return true; for (idx = 0; vec_safe_iterate (CONSTRUCTOR_ELTS (t), idx, &ce); idx++) { CHECK_NO_VAR (ce->index); CHECK_VAR (ce->value); } return false; } /* Check presence of pointers to decls in fields of an expression tree T. */ static bool <API key> (tree t) { int i; if (<API key> (t)) return true; for (i = TREE_OPERAND_LENGTH (t) - 1; i >= 0; --i) CHECK_VAR (TREE_OPERAND (t, i)); return false; } /* Check presence of pointers to decls in fields of an OMP_CLAUSE T. */ static bool <API key> (tree t) { int i; if (<API key> (t)) return true; for (i = omp_clause_num_ops[OMP_CLAUSE_CODE (t)] - 1; i >= 0; --i) CHECK_VAR (OMP_CLAUSE_OPERAND (t, i)); return false; } /* Check presence of pointers to decls that needs later fixup in T. */ static bool mentions_vars_p (tree t) { switch (TREE_CODE (t)) { case IDENTIFIER_NODE: break; case TREE_LIST: CHECK_VAR (TREE_VALUE (t)); CHECK_VAR (TREE_PURPOSE (t)); CHECK_NO_VAR (TREE_CHAIN (t)); break; case FIELD_DECL: return <API key> (t); case LABEL_DECL: case CONST_DECL: case PARM_DECL: case RESULT_DECL: case IMPORTED_DECL: case NAMESPACE_DECL: case NAMELIST_DECL: return <API key> (t); case VAR_DECL: return <API key> (t); case TYPE_DECL: return <API key> (t); case FUNCTION_DECL: return <API key> (t); case TREE_BINFO: return <API key> (t); case PLACEHOLDER_EXPR: return <API key> (t); case BLOCK: case <API key>: case OPTIMIZATION_NODE: case TARGET_OPTION_NODE: break; case CONSTRUCTOR: return <API key> (t); case OMP_CLAUSE: return <API key> (t); default: if (TYPE_P (t)) { if (<API key> (t)) return true; } else if (EXPR_P (t)) { if (<API key> (t)) return true; } else if (CONSTANT_CLASS_P (t)) CHECK_NO_VAR (TREE_TYPE (t)); else gcc_unreachable (); } return false; } /* Return the resolution for the decl with index INDEX from DATA_IN. */ static enum <API key> get_resolution (struct data_in *data_in, unsigned index) { if (data_in->globals_resolution.exists ()) { <API key> ret; /* We can have references to not emitted functions in <API key> at least. So we can and have to indeed return LDPR_UNKNOWN in some cases. */ if (data_in->globals_resolution.length () <= index) return LDPR_UNKNOWN; ret = data_in->globals_resolution[index]; return ret; } else /* Delay resolution finding until decl merging. */ return LDPR_UNKNOWN; } /* We need to record resolutions until symbol table is read. */ static void register_resolution (struct lto_file_decl_data *file_data, tree decl, enum <API key> resolution) { if (resolution == LDPR_UNKNOWN) return; if (!file_data->resolution_map) file_data->resolution_map = new hash_map<tree, <API key>>; file_data->resolution_map->put (decl, resolution); } /* Register DECL with the global symbol table and change its name if necessary to avoid name clashes for static globals across different files. */ static void <API key> (struct data_in *data_in, tree decl, unsigned ix) { tree context; /* Variable has file scope, not local. */ if (!TREE_PUBLIC (decl) && !((context = <API key> (decl)) && auto_var_in_fn_p (decl, context))) <API key> (decl, 1, 0); /* If this variable has already been declared, queue the declaration for merging. */ if (TREE_PUBLIC (decl)) register_resolution (data_in->file_data, decl, get_resolution (data_in, ix)); } /* Register DECL with the global symbol table and change its name if necessary to avoid name clashes for static globals across different files. DATA_IN contains descriptors and tables for the file being read. */ static void <API key> (struct data_in *data_in, tree decl, unsigned ix) { /* If this variable has already been declared, queue the declaration for merging. */ if (TREE_PUBLIC (decl) && !DECL_ABSTRACT_P (decl)) register_resolution (data_in->file_data, decl, get_resolution (data_in, ix)); } /* For the type T re-materialize it in the type variant list and the pointer/reference-to chains. */ static void <API key> (tree t) { /* The following re-creates proper variant lists while fixing up the variant leaders. We do not stream TYPE_NEXT_VARIANT so the variant list state before fixup is broken. */ /* If we are not our own variant leader link us into our new leaders variant list. */ if (TYPE_MAIN_VARIANT (t) != t) { tree mv = TYPE_MAIN_VARIANT (t); TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (mv); TYPE_NEXT_VARIANT (mv) = t; } /* The following reconstructs the pointer chains of the new pointed-to type if we are a main variant. We do not stream those so they are broken before fixup. */ if (TREE_CODE (t) == POINTER_TYPE && TYPE_MAIN_VARIANT (t) == t) { TYPE_NEXT_PTR_TO (t) = TYPE_POINTER_TO (TREE_TYPE (t)); TYPE_POINTER_TO (TREE_TYPE (t)) = t; } else if (TREE_CODE (t) == REFERENCE_TYPE && TYPE_MAIN_VARIANT (t) == t) { TYPE_NEXT_REF_TO (t) = TYPE_REFERENCE_TO (TREE_TYPE (t)); TYPE_REFERENCE_TO (TREE_TYPE (t)) = t; } } /* We keep prevailing tree SCCs in a hashtable with manual collision handling (in case all hashes compare the same) and keep the colliding entries in the tree_scc->next chain. */ struct tree_scc { tree_scc *next; /* Hash of the whole SCC. */ hashval_t hash; /* Number of trees in the SCC. */ unsigned len; /* Number of possible entries into the SCC (tree nodes [0..entry_len-1] which share the same individual tree hash). */ unsigned entry_len; /* The members of the SCC. We only need to remember the first entry node candidate for prevailing SCCs (but of course have access to all entries for SCCs we are processing). ??? For prevailing SCCs we really only need hash and the first entry candidate, but that's too awkward to implement. */ tree entries[1]; }; struct tree_scc_hasher : typed_noop_remove <tree_scc> { typedef tree_scc value_type; typedef tree_scc compare_type; static inline hashval_t hash (const value_type *); static inline bool equal (const value_type *, const compare_type *); }; hashval_t tree_scc_hasher::hash (const value_type *scc) { return scc->hash; } bool tree_scc_hasher::equal (const value_type *scc1, const compare_type *scc2) { if (scc1->hash != scc2->hash || scc1->len != scc2->len || scc1->entry_len != scc2->entry_len) return false; return true; } static hash_table<tree_scc_hasher> *tree_scc_hash; static struct obstack <API key>; static unsigned long num_merged_types; static unsigned long <API key>; static unsigned long num_type_scc_trees; static unsigned long total_scc_size; static unsigned long num_sccs_read; static unsigned long <API key>; static unsigned long num_sccs_merged; static unsigned long num_scc_compares; static unsigned long <API key>; /* Compare the two entries T1 and T2 of two SCCs that are possibly equal, recursing through in-SCC tree edges. Returns true if the SCCs entered through T1 and T2 are equal and fills in *MAP with the pairs of SCC entries we visited, starting with (*MAP)[0] = T1 and (*MAP)[1] = T2. */ static bool compare_tree_sccs_1 (tree t1, tree t2, tree **map) { enum tree_code code; /* Mark already visited nodes. */ TREE_ASM_WRITTEN (t2) = 1; /* Push the pair onto map. */ (*map)[0] = t1; (*map)[1] = t2; *map = *map + 2; /* Compare value-fields. */ #define compare_values(X) \ do { \ if (X(t1) != X(t2)) \ return false; \ } while (0) compare_values (TREE_CODE); code = TREE_CODE (t1); if (!TYPE_P (t1)) { compare_values (TREE_SIDE_EFFECTS); compare_values (TREE_CONSTANT); compare_values (TREE_READONLY); compare_values (TREE_PUBLIC); } compare_values (TREE_ADDRESSABLE); compare_values (TREE_THIS_VOLATILE); if (DECL_P (t1)) compare_values (DECL_UNSIGNED); else if (TYPE_P (t1)) compare_values (TYPE_UNSIGNED); if (TYPE_P (t1)) compare_values (TYPE_ARTIFICIAL); else compare_values (TREE_NO_WARNING); compare_values (TREE_NOTHROW); compare_values (TREE_STATIC); if (code != TREE_BINFO) compare_values (TREE_PRIVATE); compare_values (TREE_PROTECTED); compare_values (TREE_DEPRECATED); if (TYPE_P (t1)) { compare_values (TYPE_SATURATING); compare_values (TYPE_ADDR_SPACE); } else if (code == SSA_NAME) compare_values (<API key>); if (<API key> (code, TS_INT_CST)) { if (!wi::eq_p (t1, t2)) return false; } if (<API key> (code, TS_REAL_CST)) { /* ??? No suitable compare routine available. */ REAL_VALUE_TYPE r1 = TREE_REAL_CST (t1); REAL_VALUE_TYPE r2 = TREE_REAL_CST (t2); if (r1.cl != r2.cl || r1.decimal != r2.decimal || r1.sign != r2.sign || r1.signalling != r2.signalling || r1.canonical != r2.canonical || r1.uexp != r2.uexp) return false; for (unsigned i = 0; i < SIGSZ; ++i) if (r1.sig[i] != r2.sig[i]) return false; } if (<API key> (code, TS_FIXED_CST)) if (!fixed_compare (EQ_EXPR, TREE_FIXED_CST_PTR (t1), TREE_FIXED_CST_PTR (t2))) return false; /* We don't want to compare locations, so there is nothing do compare for TS_DECL_MINIMAL. */ if (<API key> (code, TS_DECL_COMMON)) { compare_values (DECL_MODE); compare_values (DECL_NONLOCAL); compare_values (DECL_VIRTUAL_P); compare_values (DECL_IGNORED_P); compare_values (DECL_ABSTRACT_P); compare_values (DECL_ARTIFICIAL); compare_values (DECL_USER_ALIGN); compare_values (DECL_PRESERVE_P); compare_values (DECL_EXTERNAL); compare_values (DECL_GIMPLE_REG_P); compare_values (DECL_ALIGN); if (code == LABEL_DECL) { compare_values (EH_LANDING_PAD_NR); compare_values (LABEL_DECL_UID); } else if (code == FIELD_DECL) { compare_values (DECL_PACKED); compare_values (<API key>); compare_values (DECL_OFFSET_ALIGN); } else if (code == VAR_DECL) { compare_values (<API key>); compare_values (DECL_NONLOCAL_FRAME); } if (code == RESULT_DECL || code == PARM_DECL || code == VAR_DECL) { compare_values (DECL_BY_REFERENCE); if (code == VAR_DECL || code == PARM_DECL) compare_values (<API key>); } } if (<API key> (code, TS_DECL_WRTL)) compare_values (DECL_REGISTER); if (<API key> (code, TS_DECL_WITH_VIS)) { compare_values (DECL_COMMON); compare_values (DECL_DLLIMPORT_P); compare_values (DECL_WEAK); compare_values (<API key>); compare_values (DECL_COMDAT); compare_values (DECL_VISIBILITY); compare_values (<API key>); if (code == VAR_DECL) { compare_values (DECL_HARD_REGISTER); /* <API key> is set during final asm output only. */ compare_values (<API key>); } } if (<API key> (code, TS_FUNCTION_DECL)) { compare_values (DECL_BUILT_IN_CLASS); compare_values (<API key>); compare_values (<API key>); compare_values (DECL_UNINLINABLE); compare_values (<API key>); compare_values (DECL_IS_NOVOPS); compare_values (<API key>); compare_values (DECL_IS_MALLOC); compare_values (<API key>); compare_values (<API key>); compare_values (DECL_STATIC_CHAIN); compare_values (<API key>); compare_values (<API key>); compare_values (DECL_NO_LIMIT_STACK); compare_values (<API key>); compare_values (DECL_PURE_P); compare_values (<API key>); compare_values (DECL_FINAL_P); compare_values (<API key>); compare_values (<API key>); if (DECL_BUILT_IN_CLASS (t1) != NOT_BUILT_IN) compare_values (DECL_FUNCTION_CODE); } if (<API key> (code, TS_TYPE_COMMON)) { compare_values (TYPE_MODE); compare_values (TYPE_STRING_FLAG); compare_values (TYPE_NO_FORCE_BLK); compare_values (<API key>); if (<API key> (t1)) { compare_values (<API key>); compare_values (TYPE_FINAL_P); } else if (code == ARRAY_TYPE) compare_values (<API key>); compare_values (TYPE_PACKED); compare_values (TYPE_RESTRICT); compare_values (TYPE_USER_ALIGN); compare_values (TYPE_READONLY); compare_values (TYPE_PRECISION); compare_values (TYPE_ALIGN); compare_values (TYPE_ALIAS_SET); } /* We don't want to compare locations, so there is nothing do compare for TS_EXP. */ /* BLOCKs are function local and we don't merge anything there, so simply refuse to merge. */ if (<API key> (code, TS_BLOCK)) return false; if (<API key> (code, <API key>)) if (strcmp (<API key> (t1), <API key> (t2)) != 0) return false; if (<API key> (code, TS_TARGET_OPTION)) if (!cl_target_option_eq (TREE_TARGET_OPTION (t1), TREE_TARGET_OPTION (t2))) return false; if (<API key> (code, TS_OPTIMIZATION)) if (memcmp (TREE_OPTIMIZATION (t1), TREE_OPTIMIZATION (t2), sizeof (struct cl_optimization)) != 0) return false; if (<API key> (code, TS_BINFO)) if (vec_safe_length (BINFO_BASE_ACCESSES (t1)) != vec_safe_length (BINFO_BASE_ACCESSES (t2))) return false; if (<API key> (code, TS_CONSTRUCTOR)) compare_values (CONSTRUCTOR_NELTS); if (<API key> (code, TS_IDENTIFIER)) if (IDENTIFIER_LENGTH (t1) != IDENTIFIER_LENGTH (t2) || memcmp (IDENTIFIER_POINTER (t1), IDENTIFIER_POINTER (t2), IDENTIFIER_LENGTH (t1)) != 0) return false; if (<API key> (code, TS_STRING)) if (TREE_STRING_LENGTH (t1) != TREE_STRING_LENGTH (t2) || memcmp (TREE_STRING_POINTER (t1), TREE_STRING_POINTER (t2), TREE_STRING_LENGTH (t1)) != 0) return false; if (code == OMP_CLAUSE) { compare_values (OMP_CLAUSE_CODE); switch (OMP_CLAUSE_CODE (t1)) { case OMP_CLAUSE_DEFAULT: compare_values (<API key>); break; case OMP_CLAUSE_SCHEDULE: compare_values (<API key>); break; case OMP_CLAUSE_DEPEND: compare_values (<API key>); break; case OMP_CLAUSE_MAP: compare_values (OMP_CLAUSE_MAP_KIND); break; case <API key>: compare_values (<API key>); break; case <API key>: compare_values (<API key>); compare_values (<API key>); compare_values (<API key>); break; default: break; } } #undef compare_values /* Compare pointer fields. */ /* Recurse. Search & Replaced from DFS_write_tree_body. Folding the early checks into the compare_tree_edges recursion macro makes debugging way quicker as you are able to break on compare_tree_sccs_1 and simply finish until a call returns false to spot the SCC members with the difference. */ #define compare_tree_edges(E1, E2) \ do { \ tree t1_ = (E1), t2_ = (E2); \ if (t1_ != t2_ \ && (!t1_ || !t2_ \ || !TREE_VISITED (t2_) \ || (!TREE_ASM_WRITTEN (t2_) \ && !compare_tree_sccs_1 (t1_, t2_, map)))) \ return false; \ /* Only non-NULL trees outside of the SCC may compare equal. */ \ gcc_checking_assert (t1_ != t2_ || (!t2_ || !TREE_VISITED (t2_))); \ } while (0) if (<API key> (code, TS_TYPED)) { if (code != IDENTIFIER_NODE) compare_tree_edges (TREE_TYPE (t1), TREE_TYPE (t2)); } if (<API key> (code, TS_VECTOR)) { unsigned i; /* Note that the number of elements for EXPR has already been emitted in EXPR's header (see <API key>). */ for (i = 0; i < VECTOR_CST_NELTS (t1); ++i) compare_tree_edges (VECTOR_CST_ELT (t1, i), VECTOR_CST_ELT (t2, i)); } if (<API key> (code, TS_COMPLEX)) { compare_tree_edges (TREE_REALPART (t1), TREE_REALPART (t2)); compare_tree_edges (TREE_IMAGPART (t1), TREE_IMAGPART (t2)); } if (<API key> (code, TS_DECL_MINIMAL)) { compare_tree_edges (DECL_NAME (t1), DECL_NAME (t2)); /* ??? Global decls from different TUs have non-matching <API key>. Only consider a small set of decls equivalent, we should not end up merging others. */ if ((code == TYPE_DECL || code == NAMESPACE_DECL || code == IMPORTED_DECL || code == CONST_DECL || (<API key> (t1) && (TREE_PUBLIC (t1) || DECL_EXTERNAL (t1)))) && DECL_FILE_SCOPE_P (t1) && DECL_FILE_SCOPE_P (t2)) ; else compare_tree_edges (DECL_CONTEXT (t1), DECL_CONTEXT (t2)); } if (<API key> (code, TS_DECL_COMMON)) { compare_tree_edges (DECL_SIZE (t1), DECL_SIZE (t2)); compare_tree_edges (DECL_SIZE_UNIT (t1), DECL_SIZE_UNIT (t2)); compare_tree_edges (DECL_ATTRIBUTES (t1), DECL_ATTRIBUTES (t2)); if ((code == VAR_DECL || code == PARM_DECL) && <API key> (t1)) compare_tree_edges (DECL_VALUE_EXPR (t1), DECL_VALUE_EXPR (t2)); if (code == VAR_DECL && <API key> (t1)) compare_tree_edges (DECL_DEBUG_EXPR (t1), DECL_DEBUG_EXPR (t2)); /* LTO specific edges. */ if (code != FUNCTION_DECL && code != <API key>) compare_tree_edges (DECL_INITIAL (t1), DECL_INITIAL (t2)); } if (<API key> (code, TS_DECL_NON_COMMON)) { if (code == FUNCTION_DECL) { tree a1, a2; for (a1 = DECL_ARGUMENTS (t1), a2 = DECL_ARGUMENTS (t2); a1 || a2; a1 = TREE_CHAIN (a1), a2 = TREE_CHAIN (a2)) compare_tree_edges (a1, a2); compare_tree_edges (DECL_RESULT (t1), DECL_RESULT (t2)); } else if (code == TYPE_DECL) compare_tree_edges (DECL_ORIGINAL_TYPE (t1), DECL_ORIGINAL_TYPE (t2)); } if (<API key> (code, TS_DECL_WITH_VIS)) { /* Make sure we don't inadvertently set the assembler name. */ if (<API key> (t1)) compare_tree_edges (DECL_ASSEMBLER_NAME (t1), DECL_ASSEMBLER_NAME (t2)); } if (<API key> (code, TS_FIELD_DECL)) { compare_tree_edges (DECL_FIELD_OFFSET (t1), DECL_FIELD_OFFSET (t2)); compare_tree_edges (DECL_BIT_FIELD_TYPE (t1), DECL_BIT_FIELD_TYPE (t2)); compare_tree_edges (<API key> (t1), <API key> (t2)); compare_tree_edges (<API key> (t1), <API key> (t2)); compare_tree_edges (DECL_FCONTEXT (t1), DECL_FCONTEXT (t2)); } if (<API key> (code, TS_FUNCTION_DECL)) { compare_tree_edges (<API key> (t1), <API key> (t2)); compare_tree_edges (DECL_VINDEX (t1), DECL_VINDEX (t2)); compare_tree_edges (<API key> (t1), <API key> (t2)); compare_tree_edges (<API key> (t1), <API key> (t2)); } if (<API key> (code, TS_TYPE_COMMON)) { compare_tree_edges (TYPE_SIZE (t1), TYPE_SIZE (t2)); compare_tree_edges (TYPE_SIZE_UNIT (t1), TYPE_SIZE_UNIT (t2)); compare_tree_edges (TYPE_ATTRIBUTES (t1), TYPE_ATTRIBUTES (t2)); compare_tree_edges (TYPE_NAME (t1), TYPE_NAME (t2)); /* Do not compare TYPE_POINTER_TO or TYPE_REFERENCE_TO. They will be reconstructed during fixup. */ /* Do not compare TYPE_NEXT_VARIANT, we reconstruct the variant lists during fixup. */ compare_tree_edges (TYPE_MAIN_VARIANT (t1), TYPE_MAIN_VARIANT (t2)); /* ??? Global types from different TUs have non-matching <API key>. Still merge them if they are otherwise equal. */ if (TYPE_FILE_SCOPE_P (t1) && TYPE_FILE_SCOPE_P (t2)) ; else compare_tree_edges (TYPE_CONTEXT (t1), TYPE_CONTEXT (t2)); /* TYPE_CANONICAL is re-computed during type merging, so do not compare it here. */ compare_tree_edges (TYPE_STUB_DECL (t1), TYPE_STUB_DECL (t2)); } if (<API key> (code, TS_TYPE_NON_COMMON)) { if (code == ENUMERAL_TYPE) compare_tree_edges (TYPE_VALUES (t1), TYPE_VALUES (t2)); else if (code == ARRAY_TYPE) compare_tree_edges (TYPE_DOMAIN (t1), TYPE_DOMAIN (t2)); else if (<API key> (t1)) { tree f1, f2; for (f1 = TYPE_FIELDS (t1), f2 = TYPE_FIELDS (t2); f1 || f2; f1 = TREE_CHAIN (f1), f2 = TREE_CHAIN (f2)) compare_tree_edges (f1, f2); compare_tree_edges (TYPE_BINFO (t1), TYPE_BINFO (t2)); } else if (code == FUNCTION_TYPE || code == METHOD_TYPE) compare_tree_edges (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2)); if (!POINTER_TYPE_P (t1)) compare_tree_edges (TYPE_MINVAL (t1), TYPE_MINVAL (t2)); compare_tree_edges (TYPE_MAXVAL (t1), TYPE_MAXVAL (t2)); } if (<API key> (code, TS_LIST)) { compare_tree_edges (TREE_PURPOSE (t1), TREE_PURPOSE (t2)); compare_tree_edges (TREE_VALUE (t1), TREE_VALUE (t2)); compare_tree_edges (TREE_CHAIN (t1), TREE_CHAIN (t2)); } if (<API key> (code, TS_VEC)) for (int i = 0; i < TREE_VEC_LENGTH (t1); i++) compare_tree_edges (TREE_VEC_ELT (t1, i), TREE_VEC_ELT (t2, i)); if (<API key> (code, TS_EXP)) { for (int i = 0; i < TREE_OPERAND_LENGTH (t1); i++) compare_tree_edges (TREE_OPERAND (t1, i), TREE_OPERAND (t2, i)); /* BLOCKs are function local and we don't merge anything there. */ if (TREE_BLOCK (t1) || TREE_BLOCK (t2)) return false; } if (<API key> (code, TS_BINFO)) { unsigned i; tree t; /* Lengths have already been compared above. */ FOR_EACH_VEC_ELT (*BINFO_BASE_BINFOS (t1), i, t) compare_tree_edges (t, BINFO_BASE_BINFO (t2, i)); <API key> (BINFO_BASE_ACCESSES (t1), i, t) compare_tree_edges (t, BINFO_BASE_ACCESS (t2, i)); compare_tree_edges (BINFO_OFFSET (t1), BINFO_OFFSET (t2)); compare_tree_edges (BINFO_VTABLE (t1), BINFO_VTABLE (t2)); compare_tree_edges (BINFO_VPTR_FIELD (t1), BINFO_VPTR_FIELD (t2)); /* Do not walk <API key>, BINFO_SUBVTT_INDEX and BINFO_VPTR_INDEX; these are used by C++ FE only. */ } if (<API key> (code, TS_CONSTRUCTOR)) { unsigned i; tree index, value; /* Lengths have already been compared above. */ <API key> (CONSTRUCTOR_ELTS (t1), i, index, value) { compare_tree_edges (index, CONSTRUCTOR_ELT (t2, i)->index); compare_tree_edges (value, CONSTRUCTOR_ELT (t2, i)->value); } } if (code == OMP_CLAUSE) { int i; for (i = 0; i < omp_clause_num_ops[OMP_CLAUSE_CODE (t1)]; i++) compare_tree_edges (OMP_CLAUSE_OPERAND (t1, i), OMP_CLAUSE_OPERAND (t2, i)); compare_tree_edges (OMP_CLAUSE_CHAIN (t1), OMP_CLAUSE_CHAIN (t2)); } #undef compare_tree_edges return true; } /* Compare the tree scc SCC to the prevailing candidate PSCC, filling out MAP if they are equal. */ static bool compare_tree_sccs (tree_scc *pscc, tree_scc *scc, tree *map) { /* Assume SCC entry hashes are sorted after their cardinality. Which means we can simply take the first n-tuple of equal hashes (which is recorded as entry_len) and do n SCC entry candidate comparisons. */ for (unsigned i = 0; i < pscc->entry_len; ++i) { tree *mapp = map; <API key>++; if (compare_tree_sccs_1 (pscc->entries[0], scc->entries[i], &mapp)) { /* Equal - no need to reset TREE_VISITED or TREE_ASM_WRITTEN on the scc as all trees will be freed. */ return true; } /* Reset TREE_ASM_WRITTEN on scc for the next compare or in case the SCC prevails. */ for (unsigned j = 0; j < scc->len; ++j) TREE_ASM_WRITTEN (scc->entries[j]) = 0; } return false; } /* QSort sort function to sort a map of two pointers after the 2nd pointer. */ static int cmp_tree (const void *p1_, const void *p2_) { tree *p1 = (tree *)(const_cast<void *>(p1_)); tree *p2 = (tree *)(const_cast<void *>(p2_)); if (p1[1] == p2[1]) return 0; return ((uintptr_t)p1[1] < (uintptr_t)p2[1]) ? -1 : 1; } /* Try to unify the SCC with nodes FROM to FROM + LEN in CACHE and hash value SCC_HASH with an already recorded SCC. Return true if that was successful, otherwise return false. */ static bool unify_scc (struct data_in *data_in, unsigned from, unsigned len, unsigned scc_entry_len, hashval_t scc_hash) { bool unified_p = false; struct <API key> *cache = data_in->reader_cache; tree_scc *scc = (tree_scc *) alloca (sizeof (tree_scc) + (len - 1) * sizeof (tree)); scc->next = NULL; scc->hash = scc_hash; scc->len = len; scc->entry_len = scc_entry_len; for (unsigned i = 0; i < len; ++i) { tree t = <API key> (cache, from + i); scc->entries[i] = t; /* Do not merge SCCs with local entities inside them. Also do not merge <API key>. */ if (TREE_CODE (t) == <API key> || (<API key> (t) && !(TREE_PUBLIC (t) || DECL_EXTERNAL (t))) || TREE_CODE (t) == LABEL_DECL) { /* Avoid doing any work for these cases and do not worry to record the SCCs for further merging. */ return false; } } /* Look for the list of candidate SCCs to compare against. */ tree_scc **slot; slot = tree_scc_hash->find_slot_with_hash (scc, scc_hash, INSERT); if (*slot) { /* Try unifying against each candidate. */ num_scc_compares++; /* Set TREE_VISITED on the scc so we can easily identify tree nodes outside of the scc when following tree edges. Make sure that TREE_ASM_WRITTEN is unset so we can use it as 2nd bit to track whether we visited the SCC member during the compare. We cannot use TREE_VISITED on the pscc members as the extended scc and pscc can overlap. */ for (unsigned i = 0; i < scc->len; ++i) { TREE_VISITED (scc->entries[i]) = 1; gcc_checking_assert (!TREE_ASM_WRITTEN (scc->entries[i])); } tree *map = XALLOCAVEC (tree, 2 * len); for (tree_scc *pscc = *slot; pscc; pscc = pscc->next) { if (!compare_tree_sccs (pscc, scc, map)) continue; /* Found an equal SCC. */ unified_p = true; <API key> num_sccs_merged++; <API key> += len; #ifdef ENABLE_CHECKING for (unsigned i = 0; i < len; ++i) { tree t = map[2*i+1]; enum tree_code code = TREE_CODE (t); /* IDENTIFIER_NODEs should be singletons and are merged by the streamer. The others should be singletons, too, and we should not merge them in any way. */ gcc_assert (code != <API key> && code != IDENTIFIER_NODE && !<API key> (t)); } #endif /* Fixup the streamer cache with the prevailing nodes according to the tree node mapping computed by compare_tree_sccs. */ if (len == 1) <API key> (cache, pscc->entries[0], from); else { tree *map2 = XALLOCAVEC (tree, 2 * len); for (unsigned i = 0; i < len; ++i) { map2[i*2] = (tree)(uintptr_t)(from + i); map2[i*2+1] = scc->entries[i]; } qsort (map2, len, 2 * sizeof (tree), cmp_tree); qsort (map, len, 2 * sizeof (tree), cmp_tree); for (unsigned i = 0; i < len; ++i) <API key> (cache, map[2*i], (uintptr_t)map2[2*i]); } /* Free the tree nodes from the read SCC. */ data_in->location_cache.<API key> (); for (unsigned i = 0; i < len; ++i) { enum tree_code code; if (TYPE_P (scc->entries[i])) num_merged_types++; code = TREE_CODE (scc->entries[i]); if (<API key> (code, TS_CONSTRUCTOR)) vec_free (CONSTRUCTOR_ELTS (scc->entries[i])); ggc_free (scc->entries[i]); } break; } /* Reset TREE_VISITED if we didn't unify the SCC with another. */ if (!unified_p) for (unsigned i = 0; i < scc->len; ++i) TREE_VISITED (scc->entries[i]) = 0; } /* If we didn't unify it to any candidate duplicate the relevant pieces to permanent storage and link it into the chain. */ if (!unified_p) { tree_scc *pscc = XOBNEWVAR (&<API key>, tree_scc, sizeof (tree_scc)); memcpy (pscc, scc, sizeof (tree_scc)); pscc->next = (*slot); *slot = pscc; } return unified_p; } /* Read all the symbols from buffer DATA, using descriptors in DECL_DATA. RESOLUTIONS is the set of symbols picked by the linker (read from the resolution file when the linker plugin is being used). */ static void lto_read_decls (struct lto_file_decl_data *decl_data, const void *data, vec<<API key>> resolutions) { const struct lto_decl_header *header = (const struct lto_decl_header *) data; const int decl_offset = sizeof (struct lto_decl_header); const int main_offset = decl_offset + header->decl_state_size; const int string_offset = main_offset + header->main_size; struct data_in *data_in; unsigned int i; const uint32_t *data_ptr, *data_end; uint32_t num_decl_states; lto_input_block ib_main ((const char *) data + main_offset, header->main_size, decl_data->mode_table); data_in = lto_data_in_create (decl_data, (const char *) data + string_offset, header->string_size, resolutions); /* We do not uniquify the pre-loaded cache entries, those are middle-end internal types that should not be merged. */ /* Read the global declarations and types. */ while (ib_main.p < ib_main.len) { tree t; unsigned from = data_in->reader_cache->nodes.length (); /* Read and uniquify SCCs as in the input stream. */ enum LTO_tags tag = <API key> (&ib_main); if (tag == LTO_tree_scc) { unsigned len_; unsigned scc_entry_len; hashval_t scc_hash = lto_input_scc (&ib_main, data_in, &len_, &scc_entry_len); unsigned len = data_in->reader_cache->nodes.length () - from; gcc_assert (len == len_); total_scc_size += len; num_sccs_read++; /* We have the special case of size-1 SCCs that are pre-merged by means of identifier and string sharing for example. ??? Maybe we should avoid streaming those as SCCs. */ tree first = <API key> (data_in->reader_cache, from); if (len == 1 && (TREE_CODE (first) == IDENTIFIER_NODE || TREE_CODE (first) == INTEGER_CST || TREE_CODE (first) == <API key> || <API key> (first))) continue; /* Try to unify the SCC with already existing ones. */ if (!flag_ltrans && unify_scc (data_in, from, len, scc_entry_len, scc_hash)) continue; /* Tree merging failed, mark entries in location cache as permanent. */ data_in->location_cache.<API key> (); bool seen_type = false; for (unsigned i = 0; i < len; ++i) { tree t = <API key> (data_in->reader_cache, from + i); /* Reconstruct the type variant and pointer-to/reference-to chains. */ if (TYPE_P (t)) { seen_type = true; <API key>++; <API key> (t); } /* Compute the canonical type of all types. ??? Should be able to assert that !TYPE_CANONICAL. */ if (TYPE_P (t) && !TYPE_CANONICAL (t)) { <API key> (t); if (odr_type_p (t)) register_odr_type (t); } /* Link shared INTEGER_CSTs into TYPE_CACHED_VALUEs of its type which is also member of this SCC. */ if (TREE_CODE (t) == INTEGER_CST && !TREE_OVERFLOW (t)) cache_integer_cst (t); /* Register TYPE_DECLs with the debuginfo machinery. */ if (!flag_wpa && TREE_CODE (t) == TYPE_DECL) { /* Dwarf2out needs location information. TODO: Moving this out of the streamer loop may noticealy improve ltrans linemap memory use. */ data_in->location_cache.<API key> (); debug_hooks->type_decl (t, !DECL_FILE_SCOPE_P (t)); } if (!flag_ltrans) { /* Register variables and functions with the symbol table. */ if (TREE_CODE (t) == VAR_DECL) <API key> (data_in, t, from + i); else if (TREE_CODE (t) == FUNCTION_DECL && !DECL_BUILT_IN (t)) <API key> (data_in, t, from + i); /* Scan the tree for references to global functions or variables and record those for later fixup. */ if (mentions_vars_p (t)) vec_safe_push (tree_with_vars, t); } } if (seen_type) num_type_scc_trees += len; } else { /* Pickle stray references. */ t = lto_input_tree_1 (&ib_main, data_in, tag, 0); gcc_assert (t && data_in->reader_cache->nodes.length () == from); } } data_in->location_cache.<API key> (); /* Read in lto_in_decl_state objects. */ data_ptr = (const uint32_t *) ((const char*) data + decl_offset); data_end = (const uint32_t *) ((const char*) data_ptr + header->decl_state_size); num_decl_states = *data_ptr++; gcc_assert (num_decl_states > 0); decl_data->global_decl_state = <API key> (); data_ptr = <API key> (data_in, data_ptr, decl_data->global_decl_state); /* Read in per-function decl states and enter them in hash table. */ decl_data-><API key> = hash_table<decl_state_hasher>::create_ggc (37); for (i = 1; i < num_decl_states; i++) { struct lto_in_decl_state *state = <API key> (); data_ptr = <API key> (data_in, data_ptr, state); lto_in_decl_state **slot = decl_data-><API key>->find_slot (state, INSERT); gcc_assert (*slot == NULL); *slot = state; } if (data_ptr != data_end) internal_error ("bytecode stream: garbage at the end of symbols section"); /* Set the current decl state to be the global state. */ decl_data->current_decl_state = decl_data->global_decl_state; lto_data_in_delete (data_in); } /* Custom version of strtoll, which is not portable. */ static int64_t lto_parse_hex (const char *p) { int64_t ret = 0; for (; *p != '\0'; ++p) { char c = *p; unsigned char part; ret <<= 4; if (c >= '0' && c <= '9') part = c - '0'; else if (c >= 'a' && c <= 'f') part = c - 'a' + 10; else if (c >= 'A' && c <= 'F') part = c - 'A' + 10; else internal_error ("could not parse hex number"); ret |= part; } return ret; } /* Read resolution for file named FILE_NAME. The resolution is read from RESOLUTION. */ static void lto_resolution_read (splay_tree file_ids, FILE *resolution, lto_file *file) { /* We require that objects in the resolution file are in the same order as the lto1 command line. */ unsigned int name_len; char *obj_name; unsigned int num_symbols; unsigned int i; struct lto_file_decl_data *file_data; splay_tree_node nd = NULL; if (!resolution) return; name_len = strlen (file->filename); obj_name = XNEWVEC (char, name_len + 1); fscanf (resolution, " "); /* Read white space. */ fread (obj_name, sizeof (char), name_len, resolution); obj_name[name_len] = '\0'; if (filename_cmp (obj_name, file->filename) != 0) internal_error ("unexpected file name %s in linker resolution file. " "Expected %s", obj_name, file->filename); if (file->offset != 0) { int t; char offset_p[17]; int64_t offset; t = fscanf (resolution, "@0x%16s", offset_p); if (t != 1) internal_error ("could not parse file offset"); offset = lto_parse_hex (offset_p); if (offset != file->offset) internal_error ("unexpected offset"); } free (obj_name); fscanf (resolution, "%u", &num_symbols); for (i = 0; i < num_symbols; i++) { int t; unsigned index; unsigned HOST_WIDE_INT id; char r_str[27]; enum <API key> r = (enum <API key>) 0; unsigned int j; unsigned int <API key> = sizeof (lto_resolution_str) / sizeof (char *); res_pair rp; t = fscanf (resolution, "%u " <API key> " %26s %*[^\n]\n", &index, &id, r_str); if (t != 3) internal_error ("invalid line in the resolution file"); for (j = 0; j < <API key>; j++) { if (strcmp (lto_resolution_str[j], r_str) == 0) { r = (enum <API key>) j; break; } } if (j == <API key>) internal_error ("invalid resolution in the resolution file"); if (!(nd && <API key> (nd->key, id))) { nd = <API key> (file_ids, id); if (nd == NULL) internal_error ("resolution sub id %wx not in object file", id); } file_data = (struct lto_file_decl_data *)nd->value; /* The indexes are very sparse. To save memory save them in a compact format that is only unpacked later when the subfile is processed. */ rp.res = r; rp.index = index; file_data->respairs.safe_push (rp); if (file_data->max_index < index) file_data->max_index = index; } } /* List of file_decl_datas */ struct file_data_list { struct lto_file_decl_data *first, *last; }; /* Is the name for a id'ed LTO section? */ static int lto_section_with_id (const char *name, unsigned HOST_WIDE_INT *id) { const char *s; if (strncmp (name, section_name_prefix, strlen (section_name_prefix))) return 0; s = strrchr (name, '.'); return s && sscanf (s, "." <API key>, id) == 1; } /* Create file_data of each sub file id */ static int <API key> (struct lto_section_slot *ls, splay_tree file_ids, struct file_data_list *list) { struct lto_section_slot s_slot, *new_slot; unsigned HOST_WIDE_INT id; splay_tree_node nd; void **hash_slot; char *new_name; struct lto_file_decl_data *file_data; if (!lto_section_with_id (ls->name, &id)) return 1; /* Find hash table of sub module id */ nd = <API key> (file_ids, id); if (nd != NULL) { file_data = (struct lto_file_decl_data *)nd->value; } else { file_data = ggc_alloc<lto_file_decl_data> (); memset(file_data, 0, sizeof (struct lto_file_decl_data)); file_data->id = id; file_data->section_hash_table = <API key> ();; <API key> (file_ids, id, file_data); /* Maintain list in linker order */ if (!list->first) list->first = file_data; if (list->last) list->last->next = file_data; list->last = file_data; } /* Copy section into sub module hash table */ new_name = XDUPVEC (char, ls->name, strlen (ls->name) + 1); s_slot.name = new_name; hash_slot = htab_find_slot (file_data->section_hash_table, &s_slot, INSERT); gcc_assert (*hash_slot == NULL); new_slot = XDUP (struct lto_section_slot, ls); new_slot->name = new_name; *hash_slot = new_slot; return 1; } /* Read declarations and other initializations for a FILE_DATA. */ static void lto_file_finalize (struct lto_file_decl_data *file_data, lto_file *file) { const char *data; size_t len; vec<<API key>> resolutions = vNULL; int i; res_pair *rp; /* Create vector for fast access of resolution. We do this lazily to save memory. */ resolutions.safe_grow_cleared (file_data->max_index + 1); for (i = 0; file_data->respairs.iterate (i, &rp); i++) resolutions[rp->index] = rp->res; file_data->respairs.release (); file_data->renaming_hash_table = <API key> (); file_data->file_name = file->filename; #ifdef ACCEL_COMPILER <API key> (file_data); #else file_data->mode_table = <API key>; #endif data = <API key> (file_data, LTO_section_decls, NULL, &len); if (data == NULL) { internal_error ("cannot read LTO decls from %s", file_data->file_name); return; } /* Frees resolutions */ lto_read_decls (file_data, data, resolutions); <API key> (file_data, LTO_section_decls, NULL, data, len); } /* Finalize FILE_DATA in FILE and increase COUNT. */ static int <API key> (lto_file *file, struct lto_file_decl_data *file_data, int *count) { lto_file_finalize (file_data, file); if (symtab->dump_file) fprintf (symtab->dump_file, "Creating file %s with sub id " <API key> "\n", file_data->file_name, file_data->id); (*count)++; return 0; } /* Generate a TREE representation for all types and external decls entities in FILE. Read all of the globals out of the file. Then read the cgraph and process the .o index into the cgraph nodes so that it can open the .o file to load the functions and ipa information. */ static struct lto_file_decl_data * lto_file_read (lto_file *file, FILE *resolution_file, int *count) { struct lto_file_decl_data *file_data = NULL; splay_tree file_ids; htab_t section_hash_table; struct lto_section_slot *section; struct file_data_list file_list; struct lto_section_list section_list; memset (&section_list, 0, sizeof (struct lto_section_list)); section_hash_table = <API key> (file, &section_list); /* Find all sub modules in the object and put their sections into new hash tables in a splay tree. */ file_ids = lto_splay_tree_new (); memset (&file_list, 0, sizeof (struct file_data_list)); for (section = section_list.first; section != NULL; section = section->next) <API key> (section, file_ids, &file_list); /* Add resolutions to file ids */ lto_resolution_read (file_ids, resolution_file, file); /* Finalize each lto file for each submodule in the merged object */ for (file_data = file_list.first; file_data != NULL; file_data = file_data->next) <API key> (file, file_data, count); splay_tree_delete (file_ids); htab_delete (section_hash_table); return file_list.first; } #if HAVE_MMAP_FILE && HAVE_SYSCONF && defined _SC_PAGE_SIZE #define LTO_MMAP_IO 1 #endif #if LTO_MMAP_IO /* Page size of machine is used for mmap and munmap calls. */ static size_t page_mask; #endif /* Get the section data of length LEN from FILENAME starting at OFFSET. The data segment must be freed by the caller when the caller is finished. Returns NULL if all was not well. */ static char * <API key> (struct lto_file_decl_data *file_data, intptr_t offset, size_t len) { char *result; static int fd = -1; static char *fd_name; #if LTO_MMAP_IO intptr_t computed_len; intptr_t computed_offset; intptr_t diff; #endif /* Keep a single-entry file-descriptor cache. The last file we touched will get closed at exit. ??? Eventually we want to add a more sophisticated larger cache or rather fix function body streaming to not stream them in practically random order. */ if (fd != -1 && filename_cmp (fd_name, file_data->file_name) != 0) { free (fd_name); close (fd); fd = -1; } if (fd == -1) { fd = open (file_data->file_name, O_RDONLY|O_BINARY); if (fd == -1) { fatal_error (input_location, "Cannot open %s", file_data->file_name); return NULL; } fd_name = xstrdup (file_data->file_name); } #if LTO_MMAP_IO if (!page_mask) { size_t page_size = sysconf (_SC_PAGE_SIZE); page_mask = ~(page_size - 1); } computed_offset = offset & page_mask; diff = offset - computed_offset; computed_len = len + diff; result = (char *) mmap (NULL, computed_len, PROT_READ, MAP_PRIVATE, fd, computed_offset); if (result == MAP_FAILED) { fatal_error (input_location, "Cannot map %s", file_data->file_name); return NULL; } return result + diff; #else result = (char *) xmalloc (len); if (lseek (fd, offset, SEEK_SET) != offset || read (fd, result, len) != (ssize_t) len) { free (result); fatal_error (input_location, "Cannot read %s", file_data->file_name); result = NULL; } #ifdef __MINGW32__ /* Native windows doesn't supports delayed unlink on opened file. So we close file here again. This produces higher I/O load, but at least it prevents to have dangling file handles preventing unlink. */ free (fd_name); fd_name = NULL; close (fd); fd = -1; #endif return result; #endif } /* Get the section data from FILE_DATA of SECTION_TYPE with NAME. NAME will be NULL unless the section type is for a function body. */ static const char * get_section_data (struct lto_file_decl_data *file_data, enum lto_section_type section_type, const char *name, size_t *len) { htab_t section_hash_table = file_data->section_hash_table; struct lto_section_slot *f_slot; struct lto_section_slot s_slot; const char *section_name = <API key> (section_type, name, file_data); char *data = NULL; *len = 0; s_slot.name = section_name; f_slot = (struct lto_section_slot *) htab_find (section_hash_table, &s_slot); if (f_slot) { data = <API key> (file_data, f_slot->start, f_slot->len); *len = f_slot->len; } free (CONST_CAST (char *, section_name)); return data; } /* Free the section data from FILE_DATA of SECTION_TYPE with NAME that starts at OFFSET and has LEN bytes. */ static void free_section_data (struct lto_file_decl_data *file_data ATTRIBUTE_UNUSED, enum lto_section_type section_type ATTRIBUTE_UNUSED, const char *name ATTRIBUTE_UNUSED, const char *offset, size_t len ATTRIBUTE_UNUSED) { #if LTO_MMAP_IO intptr_t computed_len; intptr_t computed_offset; intptr_t diff; #endif #if LTO_MMAP_IO computed_offset = ((intptr_t) offset) & page_mask; diff = (intptr_t) offset - computed_offset; computed_len = len + diff; munmap ((caddr_t) computed_offset, computed_len); #else free (CONST_CAST(char *, offset)); #endif } static lto_file *current_lto_file; /* Helper for qsort; compare partitions and return one with smaller size. We sort from greatest to smallest so parallel build doesn't stale on the longest compilation being executed too late. */ static int cmp_partitions_size (const void *a, const void *b) { const struct <API key> *pa = *(struct <API key> *const *)a; const struct <API key> *pb = *(struct <API key> *const *)b; return pb->insns - pa->insns; } /* Helper for qsort; compare partitions and return one with smaller order. */ static int <API key> (const void *a, const void *b) { const struct <API key> *pa = *(struct <API key> *const *)a; const struct <API key> *pb = *(struct <API key> *const *)b; int ordera = -1, orderb = -1; if (<API key> (pa->encoder)) ordera = <API key> (pa->encoder, 0)->order; if (<API key> (pb->encoder)) orderb = <API key> (pb->encoder, 0)->order; return orderb - ordera; } /* Actually stream out ENCODER into TEMP_FILENAME. */ static void do_stream_out (char *temp_filename, <API key> encoder) { lto_file *file = lto_obj_file_open (temp_filename, true); if (!file) fatal_error (input_location, "lto_obj_file_open() failed"); <API key> (file); <API key> (encoder); <API key> (NULL); lto_obj_file_close (file); free (file); } /* Wait for forked process and signal errors. */ #ifdef HAVE_WORKING_FORK static void wait_for_child () { int status; do { #ifndef WCONTINUED #define WCONTINUED 0 #endif int w = waitpid (0, &status, WUNTRACED | WCONTINUED); if (w == -1) fatal_error (input_location, "waitpid failed"); if (WIFEXITED (status) && WEXITSTATUS (status)) fatal_error (input_location, "streaming subprocess failed"); else if (WIFSIGNALED (status)) fatal_error (input_location, "streaming subprocess was killed by signal"); } while (!WIFEXITED (status) && !WIFSIGNALED (status)); } #endif /* Stream out ENCODER into TEMP_FILENAME Fork if that seems to help. */ static void stream_out (char *temp_filename, <API key> encoder, bool ARG_UNUSED (last)) { #ifdef HAVE_WORKING_FORK static int nruns; if (lto_parallelism <= 1) { do_stream_out (temp_filename, encoder); return; } /* Do not run more than LTO_PARALLELISM streamings FIXME: we ignore limits on jobserver. */ if (lto_parallelism > 0 && nruns >= lto_parallelism) { wait_for_child (); nruns } /* If this is not the last parallel partition, execute new streaming process. */ if (!last) { pid_t cpid = fork (); if (!cpid) { setproctitle ("lto1-wpa-streaming"); do_stream_out (temp_filename, encoder); exit (0); } /* Fork failed; lets do the job ourseleves. */ else if (cpid == -1) do_stream_out (temp_filename, encoder); else nruns++; } /* Last partition; stream it and wait for all children to die. */ else { int i; do_stream_out (temp_filename, encoder); for (i = 0; i < nruns; i++) wait_for_child (); } asm_nodes_output = true; #else do_stream_out (temp_filename, encoder); #endif } /* Write all output files in WPA mode and the file with the list of LTRANS units. */ static void lto_wpa_write_files (void) { unsigned i, n_sets; ltrans_partition part; FILE *<API key>; char *temp_filename; vec <char *>temp_filenames = vNULL; size_t blen; /* Open the LTRANS output list. */ if (!ltrans_output_list) fatal_error (input_location, "no LTRANS output list filename provided"); timevar_push (TV_WHOPR_WPA); FOR_EACH_VEC_ELT (ltrans_partitions, i, part) lto_stats.<API key> += <API key> (part->encoder); timevar_pop (TV_WHOPR_WPA); timevar_push (TV_WHOPR_WPA_IO); /* Generate a prefix for the LTRANS unit files. */ blen = strlen (ltrans_output_list); temp_filename = (char *) xmalloc (blen + sizeof ("2147483648.o")); strcpy (temp_filename, ltrans_output_list); if (blen > sizeof (".out") && strcmp (temp_filename + blen - sizeof (".out") + 1, ".out") == 0) temp_filename[blen - sizeof (".out") + 1] = '\0'; blen = strlen (temp_filename); n_sets = ltrans_partitions.length (); /* Sort partitions by size so small ones are compiled last. FIXME: Even when not reordering we may want to output one list for parallel make and other for final link command. */ if (!<API key> || !flag_profile_use) ltrans_partitions.qsort (<API key> ? cmp_partitions_size : <API key>); for (i = 0; i < n_sets; i++) { ltrans_partition part = ltrans_partitions[i]; /* Write all the nodes in SET. */ sprintf (temp_filename + blen, "%u.o", i); if (!quiet_flag) fprintf (stderr, " %s (%s %i insns)", temp_filename, part->name, part->insns); if (symtab->dump_file) { <API key> lsei; fprintf (symtab->dump_file, "Writing partition %s to file %s, %i insns\n", part->name, temp_filename, part->insns); fprintf (symtab->dump_file, " Symbols in partition: "); for (lsei = <API key> (part->encoder); !lsei_end_p (lsei); <API key> (&lsei)) { symtab_node *node = lsei_node (lsei); fprintf (symtab->dump_file, "%s ", node->asm_name ()); } fprintf (symtab->dump_file, "\n Symbols in boundary: "); for (lsei = lsei_start (part->encoder); !lsei_end_p (lsei); lsei_next (&lsei)) { symtab_node *node = lsei_node (lsei); if (!<API key> (part->encoder, node)) { fprintf (symtab->dump_file, "%s ", node->asm_name ()); cgraph_node *cnode = dyn_cast <cgraph_node *> (node); if (cnode && <API key> (part->encoder, cnode)) fprintf (symtab->dump_file, "(body included)"); else { varpool_node *vnode = dyn_cast <varpool_node *> (node); if (vnode && <API key> (part->encoder, vnode)) fprintf (symtab->dump_file, "(initializer included)"); } } } fprintf (symtab->dump_file, "\n"); } gcc_checking_assert (<API key> (part->encoder) || !i); stream_out (temp_filename, part->encoder, i == n_sets - 1); part->encoder = NULL; temp_filenames.safe_push (xstrdup (temp_filename)); } <API key> = fopen (ltrans_output_list, "w"); if (<API key> == NULL) fatal_error (input_location, "opening LTRANS output list %s: %m", ltrans_output_list); for (i = 0; i < n_sets; i++) { unsigned int len = strlen (temp_filenames[i]); if (fwrite (temp_filenames[i], 1, len, <API key>) < len || fwrite ("\n", 1, 1, <API key>) < 1) fatal_error (input_location, "writing to LTRANS output list %s: %m", ltrans_output_list); free (temp_filenames[i]); } temp_filenames.release(); lto_stats.num_output_files += n_sets; /* Close the LTRANS output list. */ if (fclose (<API key>)) fatal_error (input_location, "closing LTRANS output list %s: %m", ltrans_output_list); <API key>(); free (temp_filename); timevar_pop (TV_WHOPR_WPA_IO); } /* If TT is a variable or function decl replace it with its prevailing variant. */ #define LTO_SET_PREVAIL(tt) \ do {\ if ((tt) && <API key> (tt) \ && (TREE_PUBLIC (tt) || DECL_EXTERNAL (tt))) \ { \ tt = <API key> (tt); \ fixed = true; \ } \ } while (0) /* Ensure that TT isn't a replacable var of function decl. */ #define LTO_NO_PREVAIL(tt) \ gcc_assert (!(tt) || !<API key> (tt)) /* Given a tree T replace all fields referring to variables or functions with their prevailing variant. */ static void <API key> (tree t) { enum tree_code code = TREE_CODE (t); bool fixed = false; gcc_checking_assert (code != TREE_BINFO); LTO_NO_PREVAIL (TREE_TYPE (t)); if (<API key> (code, TS_COMMON)) LTO_NO_PREVAIL (TREE_CHAIN (t)); if (DECL_P (t)) { LTO_NO_PREVAIL (DECL_NAME (t)); LTO_SET_PREVAIL (DECL_CONTEXT (t)); if (<API key> (code, TS_DECL_COMMON)) { LTO_SET_PREVAIL (DECL_SIZE (t)); LTO_SET_PREVAIL (DECL_SIZE_UNIT (t)); LTO_SET_PREVAIL (DECL_INITIAL (t)); LTO_NO_PREVAIL (DECL_ATTRIBUTES (t)); LTO_SET_PREVAIL (<API key> (t)); } if (<API key> (code, TS_DECL_WITH_VIS)) { LTO_NO_PREVAIL (t->decl_with_vis.assembler_name); } if (<API key> (code, TS_DECL_NON_COMMON)) { LTO_NO_PREVAIL (DECL_RESULT_FLD (t)); } if (<API key> (code, TS_FUNCTION_DECL)) { LTO_NO_PREVAIL (DECL_ARGUMENTS (t)); LTO_SET_PREVAIL (<API key> (t)); LTO_NO_PREVAIL (DECL_VINDEX (t)); } if (<API key> (code, TS_FIELD_DECL)) { LTO_SET_PREVAIL (DECL_FIELD_OFFSET (t)); LTO_NO_PREVAIL (DECL_BIT_FIELD_TYPE (t)); LTO_NO_PREVAIL (DECL_QUALIFIER (t)); LTO_NO_PREVAIL (<API key> (t)); LTO_NO_PREVAIL (DECL_FCONTEXT (t)); } } else if (TYPE_P (t)) { LTO_NO_PREVAIL (TYPE_CACHED_VALUES (t)); LTO_SET_PREVAIL (TYPE_SIZE (t)); LTO_SET_PREVAIL (TYPE_SIZE_UNIT (t)); LTO_NO_PREVAIL (TYPE_ATTRIBUTES (t)); LTO_NO_PREVAIL (TYPE_NAME (t)); LTO_SET_PREVAIL (TYPE_MINVAL (t)); LTO_SET_PREVAIL (TYPE_MAXVAL (t)); LTO_NO_PREVAIL (t->type_non_common.binfo); LTO_SET_PREVAIL (TYPE_CONTEXT (t)); LTO_NO_PREVAIL (TYPE_CANONICAL (t)); LTO_NO_PREVAIL (TYPE_MAIN_VARIANT (t)); LTO_NO_PREVAIL (TYPE_NEXT_VARIANT (t)); } else if (EXPR_P (t)) { int i; for (i = TREE_OPERAND_LENGTH (t) - 1; i >= 0; --i) LTO_SET_PREVAIL (TREE_OPERAND (t, i)); } else if (TREE_CODE (t) == CONSTRUCTOR) { unsigned i; tree val; <API key> (CONSTRUCTOR_ELTS (t), i, val) LTO_SET_PREVAIL (val); } else { switch (code) { case TREE_LIST: LTO_SET_PREVAIL (TREE_VALUE (t)); LTO_SET_PREVAIL (TREE_PURPOSE (t)); LTO_NO_PREVAIL (TREE_PURPOSE (t)); break; default: gcc_unreachable (); } } /* If we fixed nothing, then we missed something seen by mentions_vars_p. */ gcc_checking_assert (fixed); } #undef LTO_SET_PREVAIL #undef LTO_NO_PREVAIL /* Helper function of lto_fixup_decls. Walks the var and fn streams in STATE, replaces var and function decls with the corresponding prevailing def. */ static void lto_fixup_state (struct lto_in_decl_state *state) { unsigned i, si; /* Although we only want to replace FUNCTION_DECLs and VAR_DECLs, we still need to walk from all DECLs to find the reachable FUNCTION_DECLs and VAR_DECLs. */ for (si = 0; si < LTO_N_DECL_STREAMS; si++) { vec<tree, va_gc> *trees = state->streams[si]; for (i = 0; i < vec_safe_length (trees); i++) { tree t = (*trees)[i]; if (<API key> (t) && (TREE_PUBLIC (t) || DECL_EXTERNAL (t))) (*trees)[i] = <API key> (t); } } } /* Fix the decls from all FILES. Replaces each decl with the corresponding prevailing one. */ static void lto_fixup_decls (struct lto_file_decl_data **files) { unsigned int i; tree t; if (tree_with_vars) FOR_EACH_VEC_ELT ((*tree_with_vars), i, t) <API key> (t); for (i = 0; files[i]; i++) { struct lto_file_decl_data *file = files[i]; struct lto_in_decl_state *state = file->global_decl_state; lto_fixup_state (state); hash_table<decl_state_hasher>::iterator iter; lto_in_decl_state *elt; <API key> (*file-><API key>, elt, lto_in_decl_state *, iter) lto_fixup_state (elt); } } static GTY((length ("lto_stats.num_input_files + 1"))) struct lto_file_decl_data **all_file_decl_data; /* Turn file datas for sub files into a single array, so that they look like separate files for further passes. */ static void lto_flatten_files (struct lto_file_decl_data **orig, int count, int last_file_ix) { struct lto_file_decl_data *n, *next; int i, k; lto_stats.num_input_files = count; all_file_decl_data = <API key><<API key>> (count + 1); /* Set the hooks so that all of the ipa passes can read in their data. */ lto_set_in_hooks (all_file_decl_data, get_section_data, free_section_data); for (i = 0, k = 0; i < last_file_ix; i++) { for (n = orig[i]; n != NULL; n = next) { all_file_decl_data[k++] = n; next = n->next; n->next = NULL; } } all_file_decl_data[k] = NULL; gcc_assert (k == count); } /* Input file data before flattening (i.e. splitting them to subfiles to support incremental linking. */ static int real_file_count; static GTY((length ("real_file_count + 1"))) struct lto_file_decl_data **real_file_decl_data; static void print_lto_report_1 (void); /* Read all the symbols from the input files FNAMES. NFILES is the number of files requested in the command line. Instantiate a global call graph by aggregating all the sub-graphs found in each file. */ static void <API key> (unsigned nfiles, const char **fnames) { unsigned int i, last_file_ix; FILE *resolution; int count = 0; struct lto_file_decl_data **decl_data; symtab_node *snode; symtab->initialize (); timevar_push (TV_IPA_LTO_DECL_IN); #ifdef ACCEL_COMPILER section_name_prefix = <API key>; <API key> = true; #endif real_file_decl_data = decl_data = <API key><<API key>> (nfiles + 1); real_file_count = nfiles; /* Read the resolution file. */ resolution = NULL; if (<API key>) { int t; unsigned num_objects; resolution = fopen (<API key>, "r"); if (resolution == NULL) fatal_error (input_location, "could not open symbol resolution file: %m"); t = fscanf (resolution, "%u", &num_objects); gcc_assert (t == 1); /* True, since the plugin splits the archives. */ gcc_assert (num_objects == nfiles); } symtab->state = LTO_STREAMING; <API key> = new hash_map<const_tree, hashval_t> (251); <API key> = htab_create (16381, <API key>, <API key>, NULL); gcc_obstack_init (&<API key>); tree_scc_hash = new hash_table<tree_scc_hasher> (4096); /* Register the common node types with the canonical type machinery so we properly share alias-sets across languages and TUs. Do not expose the common nodes as type merge target - those that should be are already exposed so by pre-loading the LTO streamer caches. Do two passes - first clear TYPE_CANONICAL and then re-compute it. */ for (i = 0; i < itk_none; ++i) <API key> (integer_types[i], true); for (i = 0; i < stk_type_kind_last; ++i) <API key> (sizetype_tab[i], true); for (i = 0; i < TI_MAX; ++i) <API key> (global_trees[i], true); for (i = 0; i < itk_none; ++i) <API key> (integer_types[i], false); for (i = 0; i < stk_type_kind_last; ++i) <API key> (sizetype_tab[i], false); for (i = 0; i < TI_MAX; ++i) <API key> (global_trees[i], false); if (!quiet_flag) fprintf (stderr, "Reading object files:"); /* Read all of the object files specified on the command line. */ for (i = 0, last_file_ix = 0; i < nfiles; ++i) { struct lto_file_decl_data *file_data = NULL; if (!quiet_flag) { fprintf (stderr, " %s", fnames[i]); fflush (stderr); } current_lto_file = lto_obj_file_open (fnames[i], false); if (!current_lto_file) break; file_data = lto_file_read (current_lto_file, resolution, &count); if (!file_data) { lto_obj_file_close (current_lto_file); free (current_lto_file); current_lto_file = NULL; break; } decl_data[last_file_ix++] = file_data; lto_obj_file_close (current_lto_file); free (current_lto_file); current_lto_file = NULL; } lto_flatten_files (decl_data, count, last_file_ix); lto_stats.num_input_files = count; ggc_free(decl_data); real_file_decl_data = NULL; if (<API key>) fclose (resolution); /* Show the LTO report before launching LTRANS. */ if (flag_lto_report || (flag_wpa && flag_lto_report_wpa)) print_lto_report_1 (); /* Free gimple type merging datastructures. */ delete tree_scc_hash; tree_scc_hash = NULL; obstack_free (&<API key>, NULL); htab_delete (<API key>); <API key> = NULL; delete <API key>; <API key> = NULL; /* At this stage we know that majority of GGC memory is reachable. Growing the limits prevents unnecesary invocation of GGC. */ ggc_grow (); ggc_collect (); /* Set the hooks so that all of the ipa passes can read in their data. */ lto_set_in_hooks (all_file_decl_data, get_section_data, free_section_data); timevar_pop (TV_IPA_LTO_DECL_IN); if (!quiet_flag) fprintf (stderr, "\nReading the callgraph\n"); timevar_push (<API key>); /* Read the symtab. */ input_symtab (); <API key> (); /* Store resolutions into the symbol table. */ <API key> *res; FOR_EACH_SYMBOL (snode) if (snode->real_symbol_p () && snode->lto_file_data && snode->lto_file_data->resolution_map && (res = snode->lto_file_data->resolution_map->get (snode->decl))) snode->resolution = *res; for (i = 0; all_file_decl_data[i]; i++) if (all_file_decl_data[i]->resolution_map) { delete all_file_decl_data[i]->resolution_map; all_file_decl_data[i]->resolution_map = NULL; } timevar_pop (<API key>); if (!quiet_flag) fprintf (stderr, "Merging declarations\n"); timevar_push (<API key>); /* Merge global decls. In ltrans mode we read merged cgraph, we do not need to care about resolving symbols again, we only need to replace duplicated declarations read from the callgraph and from function sections. */ if (!flag_ltrans) { <API key> (); /* If there were errors during symbol merging bail out, we have no good way to recover here. */ if (seen_error ()) fatal_error (input_location, "errors during merging of translation units"); /* Fixup all decls. */ lto_fixup_decls (all_file_decl_data); } if (tree_with_vars) ggc_free (tree_with_vars); tree_with_vars = NULL; ggc_collect (); timevar_pop (<API key>); /* Each pass will set the appropriate timer. */ if (!quiet_flag) fprintf (stderr, "Reading summaries\n"); /* Read the IPA summary data. */ if (flag_ltrans) <API key> (); else ipa_read_summaries (); for (i = 0; all_file_decl_data[i]; i++) { gcc_assert (all_file_decl_data[i]->symtab_node_encoder); <API key> (all_file_decl_data[i]->symtab_node_encoder); all_file_decl_data[i]->symtab_node_encoder = NULL; <API key> (all_file_decl_data[i]->global_decl_state); all_file_decl_data[i]->global_decl_state = NULL; all_file_decl_data[i]->current_decl_state = NULL; } /* Finally merge the cgraph according to the decl merging decisions. */ timevar_push (<API key>); if (symtab->dump_file) { fprintf (symtab->dump_file, "Before merging:\n"); symtab_node::dump_table (symtab->dump_file); } if (!flag_ltrans) { <API key> (); /* Removal of unreachable symbols is needed to make verify_symtab to pass; we are still having duplicated comdat groups containing local statics. We could also just remove them while merging. */ symtab-><API key> (dump_file); } ggc_collect (); symtab->state = IPA_SSA; /* FIXME: Technically all node removals happening here are useless, because WPA should not stream them. */ if (flag_ltrans) symtab-><API key> (dump_file); timevar_pop (<API key>); /* Indicate that the cgraph is built and ready. */ symtab-><API key> = true; ggc_free (all_file_decl_data); all_file_decl_data = NULL; } /* Materialize all the bodies for all the nodes in the callgraph. */ static void materialize_cgraph (void) { struct cgraph_node *node; timevar_id_t lto_timer; if (!quiet_flag) fprintf (stderr, flag_wpa ? "Materializing decls:" : "Reading function bodies:"); FOR_EACH_FUNCTION (node) { if (node->lto_file_data) { <API key> (node); lto_stats.<API key>++; } } /* Start the appropriate timer depending on the mode that we are operating in. */ lto_timer = (flag_wpa) ? TV_WHOPR_WPA : (flag_ltrans) ? TV_WHOPR_LTRANS : TV_LTO; timevar_push (lto_timer); <API key> = NULL; set_cfun (NULL); if (!quiet_flag) fprintf (stderr, "\n"); timevar_pop (lto_timer); } /* Show various memory usage statistics related to LTO. */ static void print_lto_report_1 (void) { const char *pfx = (flag_lto) ? "LTO" : (flag_wpa) ? "WPA" : "LTRANS"; fprintf (stderr, "%s statistics\n", pfx); fprintf (stderr, "[%s] read %lu SCCs of average size %f\n", pfx, num_sccs_read, total_scc_size / (double)num_sccs_read); fprintf (stderr, "[%s] %lu tree bodies read in total\n", pfx, total_scc_size); if (flag_wpa && tree_scc_hash) { fprintf (stderr, "[%s] tree SCC table: size %ld, %ld elements, " "collision ratio: %f\n", pfx, (long) tree_scc_hash->size (), (long) tree_scc_hash->elements (), tree_scc_hash->collisions ()); hash_table<tree_scc_hasher>::iterator hiter; tree_scc *scc, *max_scc = NULL; unsigned max_length = 0; <API key> (*tree_scc_hash, scc, x, hiter) { unsigned length = 0; tree_scc *s = scc; for (; s; s = s->next) length++; if (length > max_length) { max_length = length; max_scc = scc; } } fprintf (stderr, "[%s] tree SCC max chain length %u (size %u)\n", pfx, max_length, max_scc->len); fprintf (stderr, "[%s] Compared %lu SCCs, %lu collisions (%f)\n", pfx, num_scc_compares, <API key>, <API key> / (double) num_scc_compares); fprintf (stderr, "[%s] Merged %lu SCCs\n", pfx, num_sccs_merged); fprintf (stderr, "[%s] Merged %lu tree bodies\n", pfx, <API key>); fprintf (stderr, "[%s] Merged %lu types\n", pfx, num_merged_types); fprintf (stderr, "[%s] %lu types prevailed (%lu associated trees)\n", pfx, <API key>, num_type_scc_trees); fprintf (stderr, "[%s] GIMPLE canonical type table: size %ld, " "%ld elements, %ld searches, %ld collisions (ratio: %f)\n", pfx, (long) htab_size (<API key>), (long) htab_elements (<API key>), (long) <API key>->searches, (long) <API key>->collisions, htab_collisions (<API key>)); fprintf (stderr, "[%s] GIMPLE canonical type pointer-map: " "%lu elements, %ld searches\n", pfx, <API key>, <API key>); } print_lto_report (pfx); } /* Perform whole program analysis (WPA) on the callgraph and write out the optimization plan. */ static void <API key> (void) { symtab_node *node; lto_parallelism = 1; /* TODO: jobserver communicatoin is not supported, yet. */ if (!strcmp (flag_wpa, "jobserver")) lto_parallelism = -1; else { lto_parallelism = atoi (flag_wpa); if (lto_parallelism <= 0) lto_parallelism = 0; } timevar_start (TV_PHASE_OPT_GEN); /* Note that since we are in WPA mode, materialize_cgraph will not actually read in all the function bodies. It only materializes the decls and cgraph nodes so that analysis can be performed. */ materialize_cgraph (); /* Reading in the cgraph uses different timers, start timing WPA now. */ timevar_push (TV_WHOPR_WPA); if (pre_ipa_mem_report) { fprintf (stderr, "Memory consumption before IPA\n"); dump_memory_report (false); } symtab-><API key> = true; if (symtab->dump_file) symtab_node::dump_table (symtab->dump_file); <API key> (NULL); symtab->state = IPA_SSA; <API key> (g->get_passes ()-><API key>); if (symtab->dump_file) { fprintf (symtab->dump_file, "Optimized "); symtab_node::dump_table (symtab->dump_file); } #ifdef ENABLE_CHECKING symtab_node::verify_symtab_nodes (); #endif <API key> (NULL); /* We are about to launch the final LTRANS phase, stop the WPA timer. */ timevar_pop (TV_WHOPR_WPA); timevar_push (<API key>); if (flag_lto_partition == LTO_PARTITION_1TO1) lto_1_to_1_map (); else if (flag_lto_partition == LTO_PARTITION_MAX) lto_max_map (); else if (flag_lto_partition == LTO_PARTITION_ONE) lto_balanced_map (1); else if (flag_lto_partition == <API key>) lto_balanced_map (PARAM_VALUE (<API key>)); else gcc_unreachable (); /* Inline summaries are needed for balanced partitioning. Free them now so the memory can be used for streamer caches. */ inline_free_summary (); /* AUX pointers are used by partitioning code to bookkeep number of partitions symbol is in. This is no longer needed. */ FOR_EACH_SYMBOL (node) node->aux = NULL; lto_stats.<API key> += ltrans_partitions.length (); /* Find out statics that need to be promoted to globals with hidden visibility because they are accessed from multiple partitions. */ <API key> (); timevar_pop (<API key>); timevar_stop (TV_PHASE_OPT_GEN); /* Collect a last time - in lto_wpa_write_files we may end up forking with the idea that this doesn't increase memory usage. So we absoultely do not want to collect after that. */ ggc_collect (); timevar_start (TV_PHASE_STREAM_OUT); if (!quiet_flag) { fprintf (stderr, "\nStreaming out"); fflush (stderr); } lto_wpa_write_files (); if (!quiet_flag) fprintf (stderr, "\n"); timevar_stop (TV_PHASE_STREAM_OUT); if (post_ipa_mem_report) { fprintf (stderr, "Memory consumption after IPA\n"); dump_memory_report (false); } /* Show the LTO report before launching LTRANS. */ if (flag_lto_report || (flag_wpa && flag_lto_report_wpa)) print_lto_report_1 (); if (mem_report_wpa) dump_memory_report (true); } static GTY(()) tree <API key>; /* Return the LTO personality function decl. */ tree lto_eh_personality (void) { if (!<API key>) { /* Use the first personality DECL for our personality if we don't support multiple ones. This ensures that we don't artificially create the need for them in a single-language program. */ if (<API key> && !<API key> ()) <API key> = <API key>; else <API key> = lhd_gcc_personality (); } return <API key>; } /* Set the process name based on the LTO mode. */ static void lto_process_name (void) { if (flag_lto) setproctitle ("lto1-lto"); if (flag_wpa) setproctitle ("lto1-wpa"); if (flag_ltrans) setproctitle ("lto1-ltrans"); } /* Initialize the LTO front end. */ static void lto_init (void) { lto_process_name (); <API key> (); lto_reader_init (); lto_set_in_hooks (NULL, get_section_data, free_section_data); memset (&lto_stats, 0, sizeof (lto_stats)); <API key> (NULL); <API key> (); #ifndef ACCEL_COMPILER unsigned char *table = ggc_vec_alloc<unsigned char> (MAX_MACHINE_MODE); for (int m = 0; m < MAX_MACHINE_MODE; m++) table[m] = m; <API key> = table; #endif } /* Main entry point for the GIMPLE front end. This front end has three main personalities: - LTO (-flto). All the object files on the command line are loaded in memory and processed as a single translation unit. This is the traditional link-time optimization behavior. - WPA (-fwpa). Only the callgraph and summary information for files in the command file are loaded. A single callgraph (without function bodies) is instantiated for the whole set of files. IPA passes are only allowed to analyze the call graph and make transformation decisions. The callgraph is partitioned, each partition is written to a new object file together with the transformation decisions. - LTRANS (-fltrans). Similar to -flto but it prevents the IPA summary files from running again. Since WPA computed summary information and decided what transformations to apply, LTRANS simply applies them. */ void lto_main (void) { /* LTO is called as a front end, even though it is not a front end. Because it is called as a front end, TV_PHASE_PARSING and TV_PARSE_GLOBAL are active, and we need to turn them off while doing LTO. Later we turn them back on so they are active up in toplev.c. */ timevar_pop (TV_PARSE_GLOBAL); timevar_stop (TV_PHASE_PARSING); timevar_start (TV_PHASE_SETUP); /* Initialize the LTO front end. */ lto_init (); timevar_stop (TV_PHASE_SETUP); timevar_start (TV_PHASE_STREAM_IN); /* Read all the symbols and call graph from all the files in the command line. */ <API key> (num_in_fnames, in_fnames); timevar_stop (TV_PHASE_STREAM_IN); if (!seen_error ()) { /* If WPA is enabled analyze the whole call graph and create an optimization plan. Otherwise, read in all the function bodies and continue with optimization. */ if (flag_wpa) <API key> (); else { timevar_start (TV_PHASE_OPT_GEN); materialize_cgraph (); if (!flag_ltrans) <API key> (); /* Let the middle end know that we have read and merged all of the input files. */ symtab->compile (); timevar_stop (TV_PHASE_OPT_GEN); /* FIXME lto, if the processes spawned by WPA fail, we miss the chance to print WPA's report, so WPA will call print_lto_report before launching LTRANS. If LTRANS was launched directly by the driver we would not need to do this. */ if (flag_lto_report || (flag_wpa && flag_lto_report_wpa)) print_lto_report_1 (); } } /* Here we make LTO pretend to be a parser. */ timevar_start (TV_PHASE_PARSING); timevar_push (TV_PARSE_GLOBAL); } #include "gt-lto-lto.h"
<?php class <API key> { /** * possible search parameters, incl. default values * * @var array */ private $_parameters = array( 'what' => null, 'dymwhat' => null, 'dymrelated' => null, 'hits' => null, 'collapse' => null, 'where' => null, 'dywhere' => null, 'radius' => null, 'lx' => null, 'ly' => null, 'rx' => null, 'ry' => null, 'transformgeocode' => null, 'sort' => null, 'spatial' => null, 'sepcomm' => null, 'filter' => null, // can be ONLINER or OFFLINER 'openingtime' => null, // can be now or HH::MM 'kategorie' => null, 'site' => null, 'typ' => null, 'name' => null, 'page' => null, 'city' => null, 'plz' => null, 'strasse' => null, 'bundesland' => null, ); /** * possible collapse values * * @var array */ private $<API key> = array( true, false, 'ADDRESS_COMPANY', 'DOMAIN' ); /** * sets a new search word * alias for setWhat * * @param string $searchValue * @return <API key> */ public function setSearchValue($searchValue) { return $this->setWhat($searchValue); } /** * sets a new search word * * @param string $searchValue * @return <API key> */ public function setWhat($searchValue) { $this->_parameters['what'] = $searchValue; return $this; } /** * enable the did you mean what feature * * @return <API key> */ public function <API key>() { $this->_parameters['dymwhat'] = 'true'; return $this; } /** * disable the did you mean what feature * * @return <API key> */ public function <API key>() { $this->_parameters['dymwhat'] = 'false'; return $this; } /** * enable the did you mean where feature * * @return <API key> */ public function <API key>() { $this->_parameters['dymwhere'] = 'true'; return $this; } /** * disable the did you mean where feature * * @return <API key> */ public function <API key>() { $this->_parameters['dymwhere'] = 'false'; return $this; } /** * enable did you mean related, if true Kihno will be corrected to Kino * * @return <API key> */ public function <API key>() { $this->_parameters['dymrelated'] = 'true'; return $this; } /** * diable did you mean related, if false Kihno will not be corrected to Kino * * @return <API key> */ public function <API key>() { $this->_parameters['dymrelated'] = 'true'; return $this; } /** * set the max result hits for this search * * @param integer $hits * @return <API key> */ public function setHits($hits = 10) { #require_once 'Zend/Validate/Between.php'; $validator = new <API key>(0, 1000); if (!$validator->isValid($hits)) { $message = $validator->getMessages(); #require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new <API key>(current($message)); } $this->_parameters['hits'] = $hits; return $this; } public function setCollapse($value) { if (!in_array($value, $this-><API key>, true)) { #require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new <API key>('Not a valid value provided.'); } $this->_parameters['collapse'] = $value; return $this; } public function setWhere($where) { #require_once 'Zend/Validate/NotEmpty.php'; $validator = new <API key>(); if (!$validator->isValid($where)) { $message = $validator->getMessages(); #require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new <API key>(current($message)); } $this->_parameters['where'] = $where; return $this; } /** * returns the defined search location (ie city, country) * * @return string */ public function getWhere() { return $this->_parameters['where']; } /** * enable the spatial search feature * * @return <API key> */ public function enableSpatial() { $this->_parameters['spatial'] = 'true'; return $this; } /** * disable the spatial search feature * * @return <API key> */ public function disableSpatial() { $this->_parameters['spatial'] = 'false'; return $this; } /** * sets spatial and the given radius for a circle search * * @param integer $radius * @return <API key> */ public function setRadius($radius) { #require_once 'Zend/Validate/Int.php'; $validator = new Zend_Validate_Int(); if (!$validator->isValid($radius)) { $message = $validator->getMessages(); #require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new <API key>(current($message)); } $this->_parameters['radius'] = $radius; $this->_parameters['transformgeocode'] = 'false'; return $this; } /** * sets the values for a rectangle search * lx = longitude left top * ly = latitude left top * rx = longitude right bottom * ry = latitude right bottom * * @param float $lx * @param float $ly * @param float $rx * @param float $ry * @return <API key> */ public function setRectangle($lx, $ly, $rx, $ry) { $this->_parameters['lx'] = $lx; $this->_parameters['ly'] = $ly; $this->_parameters['rx'] = $rx; $this->_parameters['ry'] = $ry; return $this; } /** * if set, the service returns the zipcode for the result * * @return <API key> */ public function setTransformGeoCode() { $this->_parameters['transformgeocode'] = 'true'; $this->_parameters['radius'] = null; return $this; } /** * sets the sort value * possible values are: 'relevance' and 'distance' (only with spatial enabled) * * @param string $sort * @return <API key> */ public function setSort($sort) { if (!in_array($sort, array('relevance', 'distance'))) { #require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new <API key>('Not a valid sort value provided.'); } $this->_parameters['sort'] = $sort; return $this; } /** * enable the separation of phone numbers * * @return <API key> */ public function <API key>() { $this->_parameters['sepcomm'] = 'true'; return $this; } /** * disable the separation of phone numbers * * @return <API key> */ public function <API key>() { $this->_parameters['sepcomm'] = 'true'; return $this; } /** * if this filter is set, only results with a website are returned * * @return <API key> */ public function setFilterOnliner() { $this->_parameters['filter'] = 'ONLINER'; return $this; } /** * if this filter is set, only results without a website are returned * * @return <API key> */ public function setFilterOffliner() { $this->_parameters['filter'] = 'OFFLINER'; return $this; } /** * removes the filter value * * @return <API key> */ public function disableFilter() { $this->_parameters['filter'] = null; return $this; } /** * set a filter to get just results who are open at the given time * possible values: * now = open right now * HH:MM = at the given time (ie 20:00) * * @param string $time * @return <API key> */ public function setOpeningTime($time = null) { $this->_parameters['openingtime'] = $time; return $this; } public function setCategory($category = null) { $this->_parameters['kategorie'] = $category; return $this; } public function setSite($site) { $this->_parameters['site'] = $site; return $this; } /** * sets a filter to the given document type * ie: pdf, html * * @param string $type * @return <API key> */ public function setDocumentType($type) { $this->_parameters['typ'] = $type; return $this; } /** * sets a filter for the company name * ie: Deutsche Telekom * * @param string $name * @return <API key> */ public function setName($name) { $this->_parameters['name'] = $name; return $this; } /** * sets a filter for the zip code * * @param string $zip * @return <API key> */ public function setZipCode($zip) { $this->_parameters['plz'] = $zip; return $this; } /** * sets a filter for the street * * @param string $street * @return <API key> */ public function setStreet($street) { $this->_parameters['strasse'] = $street; return $this; } /** * sets a filter for the county * * @param string $county * @return <API key> */ public function setCounty($county) { $this->_parameters['bundesland'] = $county; return $this; } /** * sets a raw parameter with the value * * @param string $key * @param mixed $value * @return unknown_type */ public function setRawParameter($key, $value) { $this->_parameters[$key] = $value; return $this; } /** * returns the parameters as an array * * @return array */ public function getSearchParameters() { $retVal = array(); foreach ($this->_parameters as $key => $value) { if ($value === null) { continue; } $param = array( 'parameter' => $key, 'value' => $value ); $retVal[] = $param; } return $retVal; } }
#include "ScriptMgr.h" #include "ScriptedCreature.h" #include "magisters_terrace.h" enum Says { SAY_AGGRO = 0, SAY_ENERGY = 1, SAY_EMPOWERED = 2, SAY_KILL = 3, SAY_DEATH = 4, EMOTE_CRYSTAL = 5 }; enum Spells { // Crystal effect spells <API key> = 44329, SPELL_MANA_RAGE = 44320, // This spell triggers 44321, which changes scale and regens mana Requires an entry in spell_script_target // Selin's spells SPELL_DRAIN_LIFE = 44294, SPELL_FEL_EXPLOSION = 44314, SPELL_DRAIN_MANA = 46153 // Heroic only }; enum Phases { PHASE_NORMAL = 1, PHASE_DRAIN = 2 }; enum Events { EVENT_FEL_EXPLOSION = 1, EVENT_DRAIN_CRYSTAL, EVENT_DRAIN_MANA, EVENT_DRAIN_LIFE, EVENT_EMPOWER }; enum Misc { ACTION_SWITCH_PHASE = 1 }; class <API key> : public CreatureScript { public: <API key>() : CreatureScript("<API key>") { } struct <API key> : public BossAI { <API key>(Creature* creature) : BossAI(creature, DATA_SELIN) { _scheduledEvents = false; } void Reset() override { Crystals.clear(); me-><API key>(Crystals, NPC_FEL_CRYSTAL, 250.0f); for (Creature* creature : Crystals) { if (!creature->IsAlive()) creature->Respawn(); creature->SetFlag(UNIT_FIELD_FLAGS, <API key>); } _Reset(); CrystalGUID.Clear(); _scheduledEvents = false; } void DoAction(int32 action) override { switch (action) { case ACTION_SWITCH_PHASE: events.SetPhase(PHASE_NORMAL); events.ScheduleEvent(EVENT_FEL_EXPLOSION, 2000, 0, PHASE_NORMAL); AttackStart(me->GetVictim()); me->GetMotionMaster()->MoveChase(me->GetVictim()); break; default: break; } } void <API key>() { if (Crystals.empty()) return; Crystals.sort(Trinity::<API key>(me)); if (Creature* CrystalChosen = Crystals.front()) { Talk(SAY_ENERGY); Talk(EMOTE_CRYSTAL); DoCast(CrystalChosen, <API key>); CrystalGUID = CrystalChosen->GetGUID(); Crystals.remove(CrystalChosen); float x, y, z; CrystalChosen->GetClosePoint(x, y, z, me->GetObjectSize(), CONTACT_DISTANCE); events.SetPhase(PHASE_DRAIN); me->SetWalk(false); me->GetMotionMaster()->MovePoint(1, x, y, z); } } void <API key>() { if (Crystals.empty()) return; for (Creature* crystal : Crystals) { if (crystal && crystal->IsAlive()) crystal->KillSelf(); } } void EnterCombat(Unit* /*who*/) override { Talk(SAY_AGGRO); _EnterCombat(); events.SetPhase(PHASE_NORMAL); events.ScheduleEvent(EVENT_FEL_EXPLOSION, 2100, 0, PHASE_NORMAL); } void KilledUnit(Unit* victim) override { if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_KILL); } void MovementInform(uint32 type, uint32 id) override { if (type == POINT_MOTION_TYPE && id == 1) { Unit* CrystalChosen = ObjectAccessor::GetUnit(*me, CrystalGUID); if (CrystalChosen && CrystalChosen->IsAlive()) { CrystalChosen->RemoveFlag(UNIT_FIELD_FLAGS, <API key>); CrystalChosen->CastSpell(me, SPELL_MANA_RAGE, true); events.ScheduleEvent(EVENT_EMPOWER, 10000, PHASE_DRAIN); } } } void JustDied(Unit* /*killer*/) override { Talk(SAY_DEATH); _JustDied(); <API key>(); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_FEL_EXPLOSION: DoCastAOE(SPELL_FEL_EXPLOSION); events.ScheduleEvent(EVENT_FEL_EXPLOSION, 2000, 0, PHASE_NORMAL); break; case EVENT_DRAIN_CRYSTAL: <API key>(); _scheduledEvents = false; break; case EVENT_DRAIN_MANA: if (Unit* target = SelectTarget(<API key>, 0, 45.0f, true)) DoCast(target, SPELL_DRAIN_MANA); events.ScheduleEvent(EVENT_DRAIN_MANA, 10000, 0, PHASE_NORMAL); break; case EVENT_DRAIN_LIFE: if (Unit* target = SelectTarget(<API key>, 0, 20.0f, true)) DoCast(target, SPELL_DRAIN_LIFE); events.ScheduleEvent(EVENT_DRAIN_LIFE, 10000, 0, PHASE_NORMAL); break; case EVENT_EMPOWER: { Talk(SAY_EMPOWERED); Creature* CrystalChosen = ObjectAccessor::GetCreature(*me, CrystalGUID); if (CrystalChosen && CrystalChosen->IsAlive()) CrystalChosen->KillSelf(); CrystalGUID.Clear(); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MoveChase(me->GetVictim()); break; } default: break; } } if (me->GetPowerPct(POWER_MANA) < 10.f) { if (events.IsInPhase(PHASE_NORMAL) && !_scheduledEvents) { _scheduledEvents = true; uint32 timer = urand(3000, 7000); events.ScheduleEvent(EVENT_DRAIN_LIFE, timer, 0, PHASE_NORMAL); if (IsHeroic()) { events.ScheduleEvent(EVENT_DRAIN_CRYSTAL, urand(10000, 15000), 0, PHASE_NORMAL); events.ScheduleEvent(EVENT_DRAIN_MANA, timer + 5000, 0, PHASE_NORMAL); } else events.ScheduleEvent(EVENT_DRAIN_CRYSTAL, urand(20000, 25000), 0, PHASE_NORMAL); } } <API key>(); } private: std::list<Creature*> Crystals; ObjectGuid CrystalGUID; bool _scheduledEvents; }; CreatureAI* GetAI(Creature* creature) const override { return GetInstanceAI<<API key>>(creature); }; }; class npc_fel_crystal : public CreatureScript { public: npc_fel_crystal() : CreatureScript("npc_fel_crystal") { } struct npc_fel_crystalAI : public ScriptedAI { npc_fel_crystalAI(Creature* creature) : ScriptedAI(creature) { } void JustDied(Unit* /*killer*/) override { if (InstanceScript* instance = me->GetInstanceScript()) { Creature* Selin = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_SELIN)); if (Selin && Selin->IsAlive()) Selin->AI()->DoAction(ACTION_SWITCH_PHASE); } } }; CreatureAI* GetAI(Creature* creature) const override { return GetInstanceAI<npc_fel_crystalAI>(creature); }; }; void <API key>() { new <API key>(); new npc_fel_crystal(); }
#ifndef <API key> #define <API key> #include "WindowWidget.hpp" #include "Screen/Window.hpp" class FixedWindowWidget : public WindowWidget { public: FixedWindowWidget() = default; FixedWindowWidget(Window *window):WindowWidget(window) {} PixelSize GetMinimumSize() const override { return GetWindow().GetSize(); } }; #endif
#ifndef EAP_H #define EAP_H #include "common/defs.h" #include "eap_common/eap_defs.h" #include "eap_peer/eap_methods.h" struct eap_sm; struct wpa_config_blob; struct wpabuf; struct eap_method_type { int vendor; u32 method; }; #ifdef IEEE8021X_EAPOL /** * enum eapol_bool_var - EAPOL boolean state variables for EAP state machine * * These variables are used in the interface between EAP peer state machine and * lower layer. These are defined in RFC 4137, Sect. 4.1. Lower layer code is * expected to maintain these variables and register a callback functions for * EAP state machine to get and set the variables. */ enum eapol_bool_var { /** * EAPOL_eapSuccess - EAP SUCCESS state reached * * EAP state machine reads and writes this value. */ EAPOL_eapSuccess, /** * EAPOL_eapRestart - Lower layer request to restart authentication * * Set to TRUE in lower layer, FALSE in EAP state machine. */ EAPOL_eapRestart, /** * EAPOL_eapFail - EAP FAILURE state reached * * EAP state machine writes this value. */ EAPOL_eapFail, /** * EAPOL_eapResp - Response to send * * Set to TRUE in EAP state machine, FALSE in lower layer. */ EAPOL_eapResp, /** * EAPOL_eapNoResp - Request has been process; no response to send * * Set to TRUE in EAP state machine, FALSE in lower layer. */ EAPOL_eapNoResp, /** * EAPOL_eapReq - EAP request available from lower layer * * Set to TRUE in lower layer, FALSE in EAP state machine. */ EAPOL_eapReq, /** * EAPOL_portEnabled - Lower layer is ready for communication * * EAP state machines reads this value. */ EAPOL_portEnabled, /** * EAPOL_altAccept - Alternate indication of success (RFC3748) * * EAP state machines reads this value. */ EAPOL_altAccept, /** * EAPOL_altReject - Alternate indication of failure (RFC3748) * * EAP state machines reads this value. */ EAPOL_altReject }; /** * enum eapol_int_var - EAPOL integer state variables for EAP state machine * * These variables are used in the interface between EAP peer state machine and * lower layer. These are defined in RFC 4137, Sect. 4.1. Lower layer code is * expected to maintain these variables and register a callback functions for * EAP state machine to get and set the variables. */ enum eapol_int_var { /** * EAPOL_idleWhile - Outside time for EAP peer timeout * * This integer variable is used to provide an outside timer that the * external (to EAP state machine) code must decrement by one every * second until the value reaches zero. This is used in the same way as * EAPOL state machine timers. EAP state machine reads and writes this * value. */ EAPOL_idleWhile }; /** * struct eapol_callbacks - Callback functions from EAP to lower layer * * This structure defines the callback functions that EAP state machine * requires from the lower layer (usually EAPOL state machine) for updating * state variables and requesting information. eapol_ctx from * eap_peer_sm_init() call will be used as the ctx parameter for these * callback functions. */ struct eapol_callbacks { /** * get_config - Get pointer to the current network configuration * @ctx: eapol_ctx from eap_peer_sm_init() call */ struct eap_peer_config * (*get_config)(void *ctx); /** * get_bool - Get a boolean EAPOL state variable * @variable: EAPOL boolean variable to get * Returns: Value of the EAPOL variable */ Boolean (*get_bool)(void *ctx, enum eapol_bool_var variable); /** * set_bool - Set a boolean EAPOL state variable * @ctx: eapol_ctx from eap_peer_sm_init() call * @variable: EAPOL boolean variable to set * @value: Value for the EAPOL variable */ void (*set_bool)(void *ctx, enum eapol_bool_var variable, Boolean value); /** * get_int - Get an integer EAPOL state variable * @ctx: eapol_ctx from eap_peer_sm_init() call * @variable: EAPOL integer variable to get * Returns: Value of the EAPOL variable */ unsigned int (*get_int)(void *ctx, enum eapol_int_var variable); /** * set_int - Set an integer EAPOL state variable * @ctx: eapol_ctx from eap_peer_sm_init() call * @variable: EAPOL integer variable to set * @value: Value for the EAPOL variable */ void (*set_int)(void *ctx, enum eapol_int_var variable, unsigned int value); /** * get_eapReqData - Get EAP-Request data * @ctx: eapol_ctx from eap_peer_sm_init() call * @len: Pointer to variable that will be set to eapReqDataLen * Returns: Reference to eapReqData (EAP state machine will not free * this) or %NULL if eapReqData not available. */ struct wpabuf * (*get_eapReqData)(void *ctx); /** * set_config_blob - Set named configuration blob * @ctx: eapol_ctx from eap_peer_sm_init() call * @blob: New value for the blob * * Adds a new configuration blob or replaces the current value of an * existing blob. */ void (*set_config_blob)(void *ctx, struct wpa_config_blob *blob); /** * get_config_blob - Get a named configuration blob * @ctx: eapol_ctx from eap_peer_sm_init() call * @name: Name of the blob * Returns: Pointer to blob data or %NULL if not found */ const struct wpa_config_blob * (*get_config_blob)(void *ctx, const char *name); /** * notify_pending - Notify that a pending request can be retried * @ctx: eapol_ctx from eap_peer_sm_init() call * * An EAP method can perform a pending operation (e.g., to get a * response from an external process). Once the response is available, * this callback function can be used to request EAPOL state machine to * retry delivering the previously received (and still unanswered) EAP * request to EAP state machine. */ void (*notify_pending)(void *ctx); /** * eap_param_needed - Notify that EAP parameter is needed * @ctx: eapol_ctx from eap_peer_sm_init() call * @field: Field indicator (e.g., <API key>) * @txt: User readable text describing the required parameter */ void (*eap_param_needed)(void *ctx, enum wpa_ctrl_req_type field, const char *txt); /** * notify_cert - Notification of a peer certificate * @ctx: eapol_ctx from eap_peer_sm_init() call * @depth: Depth in certificate chain (0 = server) * @subject: Subject of the peer certificate * @cert_hash: SHA-256 hash of the certificate * @cert: Peer certificate */ void (*notify_cert)(void *ctx, int depth, const char *subject, const char *cert_hash, const struct wpabuf *cert); }; /** * struct eap_config - Configuration for EAP state machine */ struct eap_config { /** * opensc_engine_path - OpenSC engine for OpenSSL engine support * * Usually, path to engine_opensc.so. */ const char *opensc_engine_path; /** * pkcs11_engine_path - PKCS#11 engine for OpenSSL engine support * * Usually, path to engine_pkcs11.so. */ const char *pkcs11_engine_path; /** * pkcs11_module_path - OpenSC PKCS#11 module for OpenSSL engine * * Usually, path to opensc-pkcs11.so. */ const char *pkcs11_module_path; /** * wps - WPS context data * * This is only used by EAP-WSC and can be left %NULL if not available. */ struct wps_context *wps; /** * cert_in_cb - Include server certificates in callback */ int cert_in_cb; }; struct eap_sm * eap_peer_sm_init(void *eapol_ctx, struct eapol_callbacks *eapol_cb, void *msg_ctx, struct eap_config *conf); void eap_peer_sm_deinit(struct eap_sm *sm); int eap_peer_sm_step(struct eap_sm *sm); void eap_sm_abort(struct eap_sm *sm); int eap_sm_get_status(struct eap_sm *sm, char *buf, size_t buflen, int verbose); const char * <API key>(struct eap_sm *sm); struct wpabuf * <API key>(struct eap_sm *sm, int id, int encrypted); void <API key>(struct eap_sm *sm); void <API key>(struct eap_sm *sm); void <API key>(struct eap_sm *sm); void eap_sm_request_pin(struct eap_sm *sm); void eap_sm_request_otp(struct eap_sm *sm, const char *msg, size_t msg_len); void <API key>(struct eap_sm *sm); void <API key>(struct eap_sm *sm); u32 eap_get_phase2_type(const char *name, int *vendor); struct eap_method_type * <API key>(struct eap_peer_config *config, size_t *count); void eap_set_fast_reauth(struct eap_sm *sm, int enabled); void eap_set_workaround(struct eap_sm *sm, unsigned int workaround); void <API key>(struct eap_sm *sm, int disabled); int eap_key_available(struct eap_sm *sm); void eap_notify_success(struct eap_sm *sm); void <API key>(struct eap_sm *sm); const u8 * eap_get_eapKeyData(struct eap_sm *sm, size_t *len); struct wpabuf * eap_get_eapRespData(struct eap_sm *sm); void <API key>(struct eap_sm *sm, void *ctx); void <API key>(struct eap_sm *sm); int <API key>(struct eap_peer_config *conf); int <API key>(struct eap_peer_config *conf); #endif /* IEEE8021X_EAPOL */ #endif /* EAP_H */
#include "Init.hpp" #include <curl/curl.h> void Net::Initialise() { curl_global_init(CURL_GLOBAL_WIN32); } void Net::Deinitialise() { curl_global_cleanup(); }
// Name: src/msw/mediactrl_qt.cpp // Purpose: QuickTime Media Backend for Windows // Created: 11/07/04 // RCS-ID: $Id: mediactrl_qt.cpp 45498 2007-04-16 13:03:05Z VZ $ // Licence: wxWindows licence // DECLARATIONS // Pre-compiled header stuff // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_MEDIACTRL #include "wx/mediactrl.h" #ifndef WX_PRECOMP #include "wx/log.h" #include "wx/dcclient.h" #include "wx/timer.h" #include "wx/math.h" // log10 & pow #endif #include "wx/msw/private.h" // user info and wndproc setting/getting #include "wx/dynlib.h" // Externals (somewhere in src/msw/app.cpp and src/msw/window.cpp) extern "C" WXDLLIMPEXP_BASE HINSTANCE wxGetInstance(void); #ifdef __WXWINCE__ extern WXDLLIMPEXP_CORE wxChar *wxCanvasClassName; #else extern WXDLLIMPEXP_CORE const wxChar *wxCanvasClassName; #endif LRESULT WXDLLIMPEXP_CORE APIENTRY _EXPORT wxWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); // Killed MSVC warnings //disable "cast truncates constant value" for VARIANT_BOOL values //passed as parameters in VC5 and up #ifdef _MSC_VER #pragma warning (disable:4310) #endif // wxQTMediaBackend // We don't include Quicktime headers here and define all the types // ourselves because looking for the quicktime libaries etc. would // be tricky to do and making this a dependency for the MSVC projects // would be unrealistic. // Thanks to Robert Roebling for the wxDL macro/library idea // QT Includes //#include <qtml.h> // Windoze QT include //#include <QuickTimeComponents.h> // Standard QT stuff #include "wx/dynlib.h" // QT Types typedef struct MovieRecord* Movie; typedef wxInt16 OSErr; typedef wxInt32 OSStatus; #define noErr 0 #define fsRdPerm 1 typedef unsigned char Str255[256]; #define StringPtr unsigned char* #define newMovieActive 1 #define newMovieAsyncOK (1 << 8) #define Ptr char* #define Handle Ptr* #define Fixed long #define OSType unsigned long #define CGrafPtr struct GrafPort * #define TimeScale long #define TimeBase struct TimeBaseRecord * typedef struct <API key> * ComponentInstance; #define <API key> 10000 #define Boolean int #define MovieController ComponentInstance #ifndef <API key> #if defined(__WATCOMC__) || defined(__MINGW32__) // use magic numbers for compilers which complain about multicharacter integers const OSType <API key> = 1970433056; const OSType <API key> = 1702454643; #else const OSType <API key> = 'url '; const OSType <API key> = 'eyes'; #endif #endif struct FSSpec { short vRefNum; long parID; Str255 name; // Str63 on mac, Str255 on msw }; struct Rect { short top; short left; short bottom; short right; }; struct wide { wxInt32 hi; wxUint32 lo; }; struct TimeRecord { wide value; // units TimeScale scale; // units per second TimeBase base; }; struct Point { short v; short h; }; struct EventRecord { wxUint16 what; wxUint32 message; wxUint32 when; Point where; wxUint16 modifiers; }; enum { mcTopLeftMovie = 1, mcScaleMovieToFit = 2, mcWithBadge = 4, mcNotVisible = 8, mcWithFrame = 16 }; // QT Library #define wxDL_METHOD_DEFINE( rettype, name, args, shortargs, defret ) \ typedef rettype (* name ## Type) args ; \ name ## Type pfn_ ## name; \ rettype name args \ { if (m_ok) return pfn_ ## name shortargs ; return defret; } #define <API key>( name, args, shortargs ) \ typedef void (* name ## Type) args ; \ name ## Type pfn_ ## name; \ void name args \ { if (m_ok) pfn_ ## name shortargs ; } #define wxDL_METHOD_LOAD( lib, name, success ) \ pfn_ ## name = (name ## Type) lib.GetSymbol( wxT(#name), &success ); \ if (!success) return false class WXDLLIMPEXP_MEDIA wxQuickTimeLibrary { public: ~wxQuickTimeLibrary() { if (m_dll.IsLoaded()) m_dll.Unload(); } bool Initialize(); bool IsOk() const {return m_ok;} protected: wxDynamicLibrary m_dll; bool m_ok; public: <API key>( StartMovie, (Movie m), (m) ) <API key>( StopMovie, (Movie m), (m) ) wxDL_METHOD_DEFINE( bool, IsMovieDone, (Movie m), (m), false) <API key>( <API key>, (Movie m), (m) ) wxDL_METHOD_DEFINE( OSErr, GetMoviesError, (), (), -1) wxDL_METHOD_DEFINE( OSErr, EnterMovies, (), (), -1) <API key>( ExitMovies, (), () ) wxDL_METHOD_DEFINE( OSErr, InitializeQTML, (long flags), (flags), -1) <API key>( TerminateQTML, (), () ) wxDL_METHOD_DEFINE( OSErr, <API key>, (char* inName, FSSpec* outFile, long flags), (inName, outFile, flags), -1) wxDL_METHOD_DEFINE( OSErr, OpenMovieFile, (const FSSpec * fileSpec, short * resRefNum, wxInt8 permission), (fileSpec, resRefNum, permission), -1 ) wxDL_METHOD_DEFINE( OSErr, CloseMovieFile, (short resRefNum), (resRefNum), -1) wxDL_METHOD_DEFINE( OSErr, NewMovieFromFile, (Movie * theMovie, short resRefNum, short * resId, StringPtr resName, short newMovieFlags, bool * dataRefWasChanged), (theMovie, resRefNum, resId, resName, newMovieFlags, dataRefWasChanged), -1) <API key>( SetMovieRate, (Movie m, Fixed rate), (m, rate) ) wxDL_METHOD_DEFINE( Fixed, GetMovieRate, (Movie m), (m), 0) <API key>( MoviesTask, (Movie m, long maxms), (m, maxms) ) <API key>( BlockMove, (const char* p1, const char* p2, long s), (p1,p2,s) ) wxDL_METHOD_DEFINE( Handle, NewHandleClear, (long s), (s), NULL ) wxDL_METHOD_DEFINE( OSErr, NewMovieFromDataRef, (Movie * m, short flags, short * id, Handle dataRef, OSType dataRefType), (m,flags,id,dataRef,dataRefType), -1 ) <API key>( DisposeHandle, (Handle h), (h) ) <API key>( <API key>, (Movie m, Rect* r), (m,r) ) wxDL_METHOD_DEFINE( void*, <API key>, (Movie m, long index, OSType type, long flags), (m,index,type,flags), NULL ) <API key>( <API key>, (void* hWnd, void* junk, long morejunk), (hWnd, junk, morejunk) ) wxDL_METHOD_DEFINE(void*, GetNativeWindowPort, (void* hWnd), (hWnd), NULL) <API key>(SetMovieGWorld, (Movie m, CGrafPtr port, void* whatever), (m, port, whatever) ) <API key>(DisposeMovie, (Movie m), (m) ) <API key>(SetMovieBox, (Movie m, Rect* r), (m,r)) <API key>(SetMovieTimeScale, (Movie m, long s), (m,s)) wxDL_METHOD_DEFINE(long, GetMovieDuration, (Movie m), (m), 0) wxDL_METHOD_DEFINE(TimeBase, GetMovieTimeBase, (Movie m), (m), 0) wxDL_METHOD_DEFINE(TimeScale, GetMovieTimeScale, (Movie m), (m), 0) wxDL_METHOD_DEFINE(long, GetMovieTime, (Movie m, void* cruft), (m,cruft), 0) <API key>(SetMovieTime, (Movie m, TimeRecord* tr), (m,tr) ) wxDL_METHOD_DEFINE(short, GetMovieVolume, (Movie m), (m), 0) <API key>(SetMovieVolume, (Movie m, short sVolume), (m,sVolume) ) <API key>(SetMovieTimeValue, (Movie m, long s), (m,s)) wxDL_METHOD_DEFINE(ComponentInstance, NewMovieController, (Movie m, const Rect* mr, long fl), (m,mr,fl), 0) <API key>(<API key>, (ComponentInstance ci), (ci)) wxDL_METHOD_DEFINE(int, MCSetVisible, (ComponentInstance m, int b), (m, b), 0) <API key>(PrePrerollMovie, (Movie m, long t, Fixed r, WXFARPROC p1, void* p2), (m,t,r,p1,p2) ) <API key>(PrerollMovie, (Movie m, long t, Fixed r), (m,t,r) ) wxDL_METHOD_DEFINE(Fixed, <API key>, (Movie m), (m), 0) wxDL_METHOD_DEFINE(long, GetMovieLoadState, (Movie m), (m), 0) wxDL_METHOD_DEFINE(void*, <API key>, (WXFARPROC f, int l, void* junk), (f, l, junk), 0) <API key>(<API key>, (void* f), (f)) wxDL_METHOD_DEFINE(void*, <API key>, (), (), 0) wxDL_METHOD_DEFINE(int, MCDoAction, (ComponentInstance ci, long f, void* p), (ci,f,p), 0) <API key>(<API key>, (ComponentInstance ci, Rect* r), (ci,r)) <API key>(<API key>, (CGrafPtr g), (g)) <API key>(<API key>, (MSG* p1, EventRecord* p2), (p1,p2)) <API key>(MCIsPlayerEvent, (ComponentInstance ci, EventRecord* p2), (ci, p2)) wxDL_METHOD_DEFINE(int, MCSetMovie, (ComponentInstance ci, Movie m, void* p1, Point w), (ci,m,p1,w),0) <API key>(<API key>, (ComponentInstance ci, Rect* r, void* junk, void* morejunk), (ci,r,junk,morejunk)) <API key>(<API key>, (ComponentInstance ci, WXFARPROC cb, void* ref), (ci,cb,ref)) <API key>(MCGetControllerInfo, (MovieController mc, long* flags), (mc,flags)) <API key>(BeginUpdate, (CGrafPtr port), (port)) <API key>(UpdateMovie, (Movie m), (m)) <API key>(EndUpdate, (CGrafPtr port), (port)) wxDL_METHOD_DEFINE( OSErr, <API key>, (), (), -1) }; bool wxQuickTimeLibrary::Initialize() { m_ok = false; // Turn off the wxDynamicLibrary logging as we're prepared to handle the // errors wxLogNull nolog; if (!m_dll.Load(wxT("qtmlClient.dll"))) { return false; } wxDL_METHOD_LOAD( m_dll, StartMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, StopMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, IsMovieDone, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMoviesError, m_ok ); wxDL_METHOD_LOAD( m_dll, EnterMovies, m_ok ); wxDL_METHOD_LOAD( m_dll, ExitMovies, m_ok ); wxDL_METHOD_LOAD( m_dll, InitializeQTML, m_ok ); wxDL_METHOD_LOAD( m_dll, TerminateQTML, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, OpenMovieFile, m_ok ); wxDL_METHOD_LOAD( m_dll, CloseMovieFile, m_ok ); wxDL_METHOD_LOAD( m_dll, NewMovieFromFile, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieRate, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieRate, m_ok ); wxDL_METHOD_LOAD( m_dll, MoviesTask, m_ok ); wxDL_METHOD_LOAD( m_dll, BlockMove, m_ok ); wxDL_METHOD_LOAD( m_dll, NewHandleClear, m_ok ); wxDL_METHOD_LOAD( m_dll, NewMovieFromDataRef, m_ok ); wxDL_METHOD_LOAD( m_dll, DisposeHandle, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, GetNativeWindowPort, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieGWorld, m_ok ); wxDL_METHOD_LOAD( m_dll, DisposeMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieBox, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieTimeScale, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieDuration, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieTimeBase, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieTimeScale, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieTime, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieTime, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieVolume, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieVolume, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieTimeValue, m_ok ); wxDL_METHOD_LOAD( m_dll, NewMovieController, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, MCSetVisible, m_ok ); wxDL_METHOD_LOAD( m_dll, PrePrerollMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, PrerollMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieLoadState, m_ok ); wxDL_METHOD_LOAD( m_dll, MCDoAction, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, MCIsPlayerEvent, m_ok ); wxDL_METHOD_LOAD( m_dll, MCSetMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); wxDL_METHOD_LOAD( m_dll, MCGetControllerInfo, m_ok ); wxDL_METHOD_LOAD( m_dll, BeginUpdate, m_ok ); wxDL_METHOD_LOAD( m_dll, UpdateMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, EndUpdate, m_ok ); wxDL_METHOD_LOAD( m_dll, <API key>, m_ok ); m_ok = true; return true; } class WXDLLIMPEXP_MEDIA wxQTMediaBackend : public <API key> { public: wxQTMediaBackend(); virtual ~wxQTMediaBackend(); virtual bool CreateControl(wxControl* ctrl, wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name); virtual bool Play(); virtual bool Pause(); virtual bool Stop(); virtual bool Load(const wxURI& location, const wxURI& proxy) { return wxMediaBackend::Load(location, proxy); } virtual bool Load(const wxString& fileName); virtual bool Load(const wxURI& location); virtual wxMediaState GetState(); virtual bool SetPosition(wxLongLong where); virtual wxLongLong GetPosition(); virtual wxLongLong GetDuration(); virtual void Move(int x, int y, int w, int h); wxSize GetVideoSize() const; virtual double GetPlaybackRate(); virtual bool SetPlaybackRate(double dRate); virtual double GetVolume(); virtual bool SetVolume(double); void Cleanup(); void FinishLoad(); static void PPRMProc (Movie theMovie, OSErr theErr, void* theRefCon); // TODO: Last param actually long - does this work on 64bit machines? static Boolean MCFilterProc(MovieController theController, short action, void *params, LONG_PTR refCon); static LRESULT CALLBACK QTWndProc(HWND, UINT, WPARAM, LPARAM); virtual bool ShowPlayerControls(<API key> flags); wxSize m_bestSize; // Original movie size Movie m_movie; // QT Movie handle/instance bool m_bVideo; // Whether or not we have video bool m_bPlaying; // Whether or not movie is playing wxTimer* m_timer; // Load or Play timer wxQuickTimeLibrary m_lib; // DLL to load functions from ComponentInstance m_pMC; // Movie Controller friend class wxQTMediaEvtHandler; <API key>(wxQTMediaBackend) }; // helper to hijack background erasing for the QT window class WXDLLIMPEXP_MEDIA wxQTMediaEvtHandler : public wxEvtHandler { public: wxQTMediaEvtHandler(wxQTMediaBackend *qtb, WXHWND hwnd) { m_qtb = qtb; m_hwnd = hwnd; m_qtb->m_ctrl->Connect(m_qtb->m_ctrl->GetId(), <API key>, wxEraseEventHandler(wxQTMediaEvtHandler::OnEraseBackground), NULL, this); } void OnEraseBackground(wxEraseEvent& event); private: wxQTMediaBackend *m_qtb; WXHWND m_hwnd; <API key>(wxQTMediaEvtHandler) }; // IMPLEMENTATION // wxQTMediaBackend // TODO: Use a less kludgy way to pause/get state/set state // FIXME: Greg Hazel reports that sometimes files that cannot be played // with this backend are treated as playable anyway - not verified though. <API key>(wxQTMediaBackend, wxMediaBackend) // Time between timer calls - this is the Apple recommendation to the TCL // team I believe #define MOVIE_DELAY 20 // wxQTLoadTimer // QT, esp. QT for Windows is very picky about how you go about // async loading. If you were to go through a Windows message loop // or a MoviesTask or both and then check the movie load state // it would still return 1000 (loading)... even (pre)prerolling doesn't // help. However, making a load timer like this works class wxQTLoadTimer : public wxTimer { public: wxQTLoadTimer(Movie movie, wxQTMediaBackend* parent, wxQuickTimeLibrary* pLib) : m_movie(movie), m_parent(parent), m_pLib(pLib) {} void Notify() { m_pLib->MoviesTask(m_movie, 0); // <API key> if (m_pLib->GetMovieLoadState(m_movie) >= 10000) { m_parent->FinishLoad(); delete this; } } protected: Movie m_movie; //Our movie instance wxQTMediaBackend* m_parent; //Backend pointer wxQuickTimeLibrary* m_pLib; //Interfaces }; // wxQTPlayTimer - Handle Asyncronous Playing // 1) Checks to see if the movie is done, and if not continues // streaming the movie // 2) Sends the wxEVT_MEDIA_STOP event if we have reached the end of // the movie. class wxQTPlayTimer : public wxTimer { public: wxQTPlayTimer(Movie movie, wxQTMediaBackend* parent, wxQuickTimeLibrary* pLib) : m_movie(movie), m_parent(parent), m_pLib(pLib) {} void Notify() { // OK, a little explaining - basically originally // we only called MoviesTask if the movie was actually // playing (not paused or stopped)... this was before // we realized MoviesTask actually handles repainting // of the current frame - so if you were to resize // or something it would previously not redraw that // portion of the movie. // So now we call MoviesTask always so that it repaints // correctly. m_pLib->MoviesTask(m_movie, 0); // Handle the stop event - if the movie has reached // the end, notify our handler // m_bPlaying == !(Stopped | Paused) if (m_parent->m_bPlaying) { if (m_pLib->IsMovieDone(m_movie)) { if ( m_parent->SendStopEvent() ) { m_parent->Stop(); wxASSERT(m_pLib->GetMoviesError() == noErr); m_parent->QueueFinishEvent(); } } } } protected: Movie m_movie; // Our movie instance wxQTMediaBackend* m_parent; //Backend pointer wxQuickTimeLibrary* m_pLib; //Interfaces }; // wxQTMediaBackend::QTWndProc // Forwards events to the Movie Controller so that it can // redraw itself/process messages etc.. LRESULT CALLBACK wxQTMediaBackend::QTWndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam) { wxQTMediaBackend* pThis = (wxQTMediaBackend*)wxGetWindowUserData(hWnd); MSG msg; msg.hwnd = hWnd; msg.message = nMsg; msg.wParam = wParam; msg.lParam = lParam; msg.time = 0; msg.pt.x = 0; msg.pt.y = 0; EventRecord theEvent; pThis->m_lib.<API key>(&msg, &theEvent); pThis->m_lib.MCIsPlayerEvent(pThis->m_pMC, &theEvent); return pThis->m_ctrl->MSWWindowProc(nMsg, wParam, lParam); } // wxQTMediaBackend Destructor // Sets m_timer to NULL signifying we havn't loaded anything yet wxQTMediaBackend::wxQTMediaBackend() : m_movie(NULL), m_bPlaying(false), m_timer(NULL), m_pMC(NULL) { } // wxQTMediaBackend Destructor // 1) Cleans up the QuickTime movie instance // 2) Decrements the QuickTime reference counter - if this reaches // 0, QuickTime shuts down // 3) Decrements the QuickTime Windows Media Layer reference counter - // if this reaches 0, QuickTime shuts down the Windows Media Layer wxQTMediaBackend::~wxQTMediaBackend() { if (m_movie) Cleanup(); if (m_lib.IsOk()) { if (m_pMC) { m_lib.<API key>(m_pMC); // m_pMC = NULL; } // destroy wxQTMediaEvtHandler we pushed on it m_ctrl->PopEventHandler(true); m_lib.<API key>( (CGrafPtr)m_lib.GetNativeWindowPort(m_ctrl->GetHWND())); //Note that ExitMovies() is not necessary, but //the docs are fuzzy on whether or not TerminateQTML is m_lib.ExitMovies(); m_lib.TerminateQTML(); } } // wxQTMediaBackend::CreateControl // 1) Intializes QuickTime // 2) Creates the control window bool wxQTMediaBackend::CreateControl(wxControl* ctrl, wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) { if (!m_lib.Initialize()) return false; int nError = m_lib.InitializeQTML(0); if (nError != noErr) //-2093 no dll { wxFAIL_MSG(wxString::Format(wxT("Couldn't Initialize Quicktime-%i"), nError)); return false; } m_lib.EnterMovies(); // Create window // By default wxWindow(s) is created with a border - // so we need to get rid of those // Since we don't have a child window like most other // backends, we don't need wxCLIP_CHILDREN if ( !ctrl->wxControl::Create(parent, id, pos, size, (style & ~wxBORDER_MASK) | wxBORDER_NONE, validator, name) ) { return false; } m_ctrl = wxStaticCast(ctrl, wxMediaCtrl); // Create a port association for our window so we // can use it as a WindowRef m_lib.<API key>(m_ctrl->GetHWND(), NULL, 0L); // Part of a suggestion from Greg Hazel // to repaint movie when idle m_ctrl->PushEventHandler(new wxQTMediaEvtHandler(this, m_ctrl->GetHWND())); // done return true; } // wxQTMediaBackend::Load (file version) // 1) Get an FSSpec from the Windows path name // 2) Open the movie // 3) Obtain the movie instance from the movie resource // 4) Close the movie resource // 5) Finish loading bool wxQTMediaBackend::Load(const wxString& fileName) { if (m_movie) Cleanup(); bool result = true; OSErr err = noErr; short movieResFile = 0; //= 0 because of annoying VC6 warning FSSpec sfFile; err = m_lib.<API key>( (char*) (const char*) fileName.mb_str(), &sfFile, 0); result = (err == noErr); if (result) { err = m_lib.OpenMovieFile(&sfFile, &movieResFile, fsRdPerm); result = (err == noErr); } if (result) { short movieResID = 0; Str255 movieName; err = m_lib.NewMovieFromFile( &m_movie, movieResFile, &movieResID, movieName, newMovieActive, NULL ); // wasChanged result = (err == noErr /*&& m_lib.<API key>() == noErr*/); // check m_lib.<API key>() because it may not find the // proper codec and play black video and other strange effects, // not to mention mess up the dynamic backend loading scheme // of wxMediaCtrl - so it just does what the QuickTime player does if (result) { m_lib.CloseMovieFile(movieResFile); FinishLoad(); } } return result; } // wxQTMediaBackend::PPRMProc (static) // Called when done PrePrerolling the movie. // Note that in 99% of the cases this does nothing... // Anyway we set up the loading timer here to tell us when the movie is done void wxQTMediaBackend::PPRMProc (Movie theMovie, OSErr <API key>(theErr), void* theRefCon) { wxASSERT( theMovie ); wxASSERT( theRefCon ); wxASSERT( theErr == noErr ); wxQTMediaBackend* pBE = (wxQTMediaBackend*) theRefCon; long lTime = pBE->m_lib.GetMovieTime(theMovie,NULL); Fixed rate = pBE->m_lib.<API key>(theMovie); pBE->m_lib.PrerollMovie(theMovie, lTime, rate); pBE->m_timer = new wxQTLoadTimer(pBE->m_movie, pBE, &pBE->m_lib); pBE->m_timer->Start(MOVIE_DELAY); } // wxQTMediaBackend::Load (URL Version) // 1) Build an escaped URI from location // 2) Create a handle to store the URI string // 3) Put the URI string inside the handle // 4) Make a QuickTime URL data ref from the handle with the URI in it // 5) Clean up the URI string handle // 6) Do some prerolling // 7) Finish Loading bool wxQTMediaBackend::Load(const wxURI& location) { if (m_movie) Cleanup(); wxString theURI = location.BuildURI(); Handle theHandle = m_lib.NewHandleClear(theURI.length() + 1); wxASSERT(theHandle); m_lib.BlockMove(theURI.mb_str(), *theHandle, theURI.length() + 1); // create the movie from the handle that refers to the URI OSErr err = m_lib.NewMovieFromDataRef(&m_movie, newMovieActive | newMovieAsyncOK /* | <API key> */, NULL, theHandle, <API key>); m_lib.DisposeHandle(theHandle); if (err == noErr) { long timeNow; Fixed playRate; timeNow = m_lib.GetMovieTime(m_movie, NULL); wxASSERT(m_lib.GetMoviesError() == noErr); playRate = m_lib.<API key>(m_movie); wxASSERT(m_lib.GetMoviesError() == noErr); // Note that the callback here is optional, // but without it PrePrerollMovie can be buggy // (see Apple ml). Also, some may wonder // why we need this at all - this is because // Apple docs say QuickTime streamed movies // require it if you don't use a Movie Controller, // which we don't by default. m_lib.PrePrerollMovie(m_movie, timeNow, playRate, (WXFARPROC)wxQTMediaBackend::PPRMProc, (void*)this); return true; } else return false; } // wxQTMediaBackend::FinishLoad // 1) Create the movie timer // 2) Get real size of movie for GetBestSize/sizers // 3) Set the movie time scale to something usable so that seeking // etc. will work correctly // 4) Set our Movie Controller to display the movie if it exists, // otherwise set the bounds of the Movie // 5) Refresh parent window void wxQTMediaBackend::FinishLoad() { // Create the playing/streaming timer m_timer = new wxQTPlayTimer(m_movie, (wxQTMediaBackend*) this, &m_lib); wxASSERT(m_timer); m_timer->Start(MOVIE_DELAY, wxTIMER_CONTINUOUS); // get the real size of the movie Rect outRect; memset(&outRect, 0, sizeof(Rect)); // suppress annoying VC6 warning m_lib.<API key> (m_movie, &outRect); wxASSERT(m_lib.GetMoviesError() == noErr); m_bestSize.x = outRect.right - outRect.left; m_bestSize.y = outRect.bottom - outRect.top; // Handle the movie GWorld if (m_pMC) { Point thePoint; thePoint.h = thePoint.v = 0; m_lib.MCSetMovie(m_pMC, m_movie, m_lib.GetNativeWindowPort(m_ctrl->GetHandle()), thePoint); m_lib.MCSetVisible(m_pMC, true); m_bestSize.y += 16; } else { m_lib.SetMovieGWorld(m_movie, (CGrafPtr) m_lib.GetNativeWindowPort(m_ctrl->GetHWND()), NULL); } // Set the movie to millisecond precision m_lib.SetMovieTimeScale(m_movie, 1000); wxASSERT(m_lib.GetMoviesError() == noErr); NotifyMovieLoaded(); } // wxQTMediaBackend::Play // 1) Start the QT movie // 2) Start the movie loading timer // NOTE: This will still return success even when // the movie is still loading, and as mentioned in wxQTLoadTimer // I don't know of a way to force this to be sync - so if its // still loading the function will return true but the movie will // still be in the stopped state bool wxQTMediaBackend::Play() { m_lib.StartMovie(m_movie); m_bPlaying = true; return m_lib.GetMoviesError() == noErr; } // wxQTMediaBackend::Pause // 1) Stop the movie // 2) Stop the movie timer bool wxQTMediaBackend::Pause() { m_bPlaying = false; m_lib.StopMovie(m_movie); return m_lib.GetMoviesError() == noErr; } // wxQTMediaBackend::Stop // 1) Stop the movie // 2) Stop the movie timer // 3) Seek to the beginning of the movie bool wxQTMediaBackend::Stop() { m_bPlaying = false; m_lib.StopMovie(m_movie); if (m_lib.GetMoviesError() == noErr) m_lib.<API key>(m_movie); return m_lib.GetMoviesError() == noErr; } // wxQTMediaBackend::GetPlaybackRate // Get the movie playback rate from ::GetMovieRate double wxQTMediaBackend::GetPlaybackRate() { return ( ((double)m_lib.GetMovieRate(m_movie)) / 0x10000); } // wxQTMediaBackend::SetPlaybackRate // Convert dRate to Fixed and Set the movie rate through SetMovieRate bool wxQTMediaBackend::SetPlaybackRate(double dRate) { m_lib.SetMovieRate(m_movie, (Fixed) (dRate * 0x10000)); return m_lib.GetMoviesError() == noErr; } // wxQTMediaBackend::SetPosition // 1) Create a time record struct (TimeRecord) with appropriate values // 2) Pass struct to SetMovieTime bool wxQTMediaBackend::SetPosition(wxLongLong where) { // NB: For some reason SetMovieTime does not work // correctly with the Quicktime Windows SDK (6) // From Muskelkatermann at the wxForum // RN - note that I have not verified this but there // is no harm in calling SetMovieTimeValue instead #if 0 TimeRecord theTimeRecord; memset(&theTimeRecord, 0, sizeof(TimeRecord)); theTimeRecord.value.lo = where.GetLo(); theTimeRecord.scale = m_lib.GetMovieTimeScale(m_movie); theTimeRecord.base = m_lib.GetMovieTimeBase(m_movie); m_lib.SetMovieTime(m_movie, &theTimeRecord); #else m_lib.SetMovieTimeValue(m_movie, where.GetLo()); #endif return (m_lib.GetMoviesError() == noErr); } // wxQTMediaBackend::GetPosition // 1) Calls GetMovieTime to get the position we are in in the movie // in milliseconds (we called wxLongLong wxQTMediaBackend::GetPosition() { return m_lib.GetMovieTime(m_movie, NULL); } // wxQTMediaBackend::GetVolume // Gets the volume through GetMovieVolume - which returns a 16 bit short - // + (1) + (2) + // (1) first 8 bits are value before decimal // (2) second 8 bits are value after decimal // Volume ranges from -1.0 (gain but no sound), 0 (no sound and no gain) to // 1 (full gain and sound) double wxQTMediaBackend::GetVolume() { short sVolume = m_lib.GetMovieVolume(m_movie); wxASSERT(m_lib.GetMoviesError() == noErr); if (sVolume & (128 << 8)) //negative - no sound return 0.0; return sVolume / 256.0; } // wxQTMediaBackend::SetVolume // Sets the volume through SetMovieVolume - which takes a 16 bit short - // + (1) + (2) + // (1) first 8 bits are value before decimal // (2) second 8 bits are value after decimal // Volume ranges from -1.0 (gain but no sound), 0 (no sound and no gain) to // 1 (full gain and sound) bool wxQTMediaBackend::SetVolume(double dVolume) { m_lib.SetMovieVolume(m_movie, (short) (dVolume * 256)); return m_lib.GetMoviesError() == noErr; } // wxQTMediaBackend::GetDuration // Calls GetMovieDuration wxLongLong wxQTMediaBackend::GetDuration() { return m_lib.GetMovieDuration(m_movie); } // wxQTMediaBackend::GetState // Determines the current state: // if we are at the beginning, then we are stopped wxMediaState wxQTMediaBackend::GetState() { if (m_bPlaying) return <API key>; else if ( !m_movie || wxQTMediaBackend::GetPosition() == 0 ) return <API key>; else return wxMEDIASTATE_PAUSED; } // wxQTMediaBackend::Cleanup // Diposes of the movie timer, Disassociates the Movie Controller with // movie and hides it if it exists, and stops and disposes // of the QT movie void wxQTMediaBackend::Cleanup() { m_bPlaying = false; if (m_timer) { delete m_timer; m_timer = NULL; } m_lib.StopMovie(m_movie); if (m_pMC) { Point thePoint; thePoint.h = thePoint.v = 0; m_lib.MCSetVisible(m_pMC, false); m_lib.MCSetMovie(m_pMC, NULL, NULL, thePoint); } m_lib.DisposeMovie(m_movie); m_movie = NULL; } // wxQTMediaBackend::ShowPlayerControls // Creates a movie controller for the Movie if the user wants it bool wxQTMediaBackend::ShowPlayerControls(<API key> flags) { if (m_pMC) { // restore old wndproc wxSetWindowProc((HWND)m_ctrl->GetHWND(), wxWndProc); m_lib.<API key>(m_pMC); m_pMC = NULL; // movie controller height m_bestSize.y -= 16; } if (flags && m_movie) { Rect rect; wxRect wxrect = m_ctrl->GetClientRect(); // make room for controller if (wxrect.width < 320) wxrect.width = 320; rect.top = (short)wxrect.y; rect.left = (short)wxrect.x; rect.right = (short)(rect.left + wxrect.width); rect.bottom = (short)(rect.top + wxrect.height); if (!m_pMC) { m_pMC = m_lib.NewMovieController(m_movie, &rect, mcTopLeftMovie | // mcScaleMovieToFit | // mcWithBadge | mcWithFrame); m_lib.MCDoAction(m_pMC, 32, (void*)true); // <API key> m_lib.<API key>(m_pMC, (WXFARPROC)wxQTMediaBackend::MCFilterProc, (void*)this); m_bestSize.y += 16; // movie controller height // By default the movie controller uses its own colour palette // for the movie which can be bad on some files, so turn it off. // Also turn off its frame / border for the movie // Also take care of a couple of the interface flags here long mcFlags = 0; m_lib.MCDoAction(m_pMC, 39/*mcActionGetFlags*/, (void*)&mcFlags); mcFlags |= // (1<< 0) /*<API key>*/ | (1<< 3) /*<API key>*/ | ((flags & <API key>) ? 0 : (1<< 1) /*<API key>*/) | ((flags & <API key>) ? 0 : (1<< 2) /*<API key>*/) // | (1<< 4) /*<API key>*/ // if we take care of repainting ourselves ; m_lib.MCDoAction(m_pMC, 38/*mcActionSetFlags*/, (void*)mcFlags); // intercept the wndproc of our control window wxSetWindowProc((HWND)m_ctrl->GetHWND(), wxQTMediaBackend::QTWndProc); // set the user data of our window wxSetWindowUserData((HWND)m_ctrl->GetHWND(), this); } } <API key>(); return m_lib.GetMoviesError() == noErr; } // wxQTMediaBackend::MCFilterProc (static) // Callback for when the movie controller recieves a message Boolean wxQTMediaBackend::MCFilterProc(MovieController WXUNUSED(theController), short action, void * WXUNUSED(params), LONG_PTR refCon) { // NB: potential optimisation // if (action == 1) // return 0; wxQTMediaBackend* pThis = (wxQTMediaBackend*)refCon; switch (action) { case 1: // don't process idle events break; case 8: // play button triggered - MC will set movie to opposite state // of current - playing ? paused : playing if (pThis) pThis->m_bPlaying = !(pThis->m_bPlaying); // NB: Sometimes it doesn't redraw properly - // if you click on the button but don't move the mouse // the button will not change its state until you move // mcActionDraw and Refresh/Update combo do nothing // to help this unfortunately break; default: break; } return 0; } // wxQTMediaBackend::GetVideoSize // Returns the actual size of the QT movie wxSize wxQTMediaBackend::GetVideoSize() const { return m_bestSize; } // wxQTMediaBackend::Move // Sets the bounds of either the Movie or Movie Controller void wxQTMediaBackend::Move(int WXUNUSED(x), int WXUNUSED(y), int w, int h) { if (m_movie) { // make room for controller if (m_pMC) { if (w < 320) w = 320; Rect theRect = {0, 0, (short)h, (short)w}; m_lib.<API key>(m_pMC, &theRect); } else { Rect theRect = {0, 0, (short)h, (short)w}; m_lib.SetMovieBox(m_movie, &theRect); } wxASSERT(m_lib.GetMoviesError() == noErr); } } // wxQTMediaBackend::OnEraseBackground // Suggestion from Greg Hazel to repaint the movie when idle // (on pause also) // TODO: We may be repainting too much here - under what exact circumstances // do we need this? I think Move also repaints correctly for the Movie // Controller, so in that instance we don't need this either void wxQTMediaEvtHandler::OnEraseBackground(wxEraseEvent& evt) { wxQuickTimeLibrary& m_pLib = m_qtb->m_lib; if ( m_qtb->m_pMC ) { // repaint movie controller m_pLib.MCDoAction(m_qtb->m_pMC, 2 /*mcActionDraw*/, m_pLib.GetNativeWindowPort(m_hwnd)); } else if ( m_qtb->m_movie ) { // no movie controller CGrafPtr port = (CGrafPtr)m_pLib.GetNativeWindowPort(m_hwnd); m_pLib.BeginUpdate(port); m_pLib.UpdateMovie(m_qtb->m_movie); wxASSERT(m_pLib.GetMoviesError() == noErr); m_pLib.EndUpdate(port); } else { // no movie // let the system repaint the window evt.Skip(); } } // End QT Backend // in source file that contains stuff you don't directly use #include "wx/html/forcelnk.h" FORCE_LINK_ME(wxmediabackend_qt) #endif // wxUSE_MEDIACTRL && wxUSE_ACTIVEX
// Name: src/msw/gdiobj.cpp // Purpose: wxGDIObject class // Created: 01/02/97 // RCS-ID: $Id: gdiobj.cpp 40626 2006-08-16 14:53:49Z VS $ // Licence: wxWindows licence // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "wx/gdiobj.h" #ifndef WX_PRECOMP #include <stdio.h> #include "wx/list.h" #include "wx/utils.h" #include "wx/app.h" #endif #include "wx/msw/private.h" #define M_GDIDATA wx_static_cast(wxGDIRefData*, m_refData) /* void wxGDIObject::<API key>(void) { if ( !M_GDIDATA ) return; // wxDebugMsg("Object %ld about to be incremented: %d\n", (long)this, m_usageCount); M_GDIDATA->m_usageCount ++; }; void wxGDIObject::<API key>(void) { if ( !M_GDIDATA ) return; M_GDIDATA->m_usageCount --; if (wxTheApp) wxTheApp->SetPendingCleanup(true); // wxDebugMsg("Object %ld decremented: %d\n", (long)this, M_GDIDATA->m_usageCount); if (M_GDIDATA->m_usageCount < 0) { char buf[80]; sprintf(buf, "Object %ld usage count is %d\n", (long)this, M_GDIDATA->m_usageCount); wxDebugMsg(buf); } // assert(M_GDIDATA->m_usageCount >= 0); }; */
module.exports = require("./mime-functions"); module.exports.contentTypes = require("./content-types");
// file at the top-level directory of this distribution and at // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: --cfg fooA --cfg fooB // fooA AND !bar #[cfg(fooA, not(bar))] fn foo1() -> int { 1 } // !fooA AND !bar #[cfg(not(fooA), not(bar))] fn foo2() -> int { 2 } // fooC OR (fooB AND !bar) #[cfg(fooC)] #[cfg(fooB, not(bar))] fn foo2() -> int { 3 } // fooA AND bar #[cfg(fooA, bar)] fn foo3() -> int { 2 } // !(fooA AND bar) #[cfg(not(fooA, bar))] fn foo3() -> int { 3 } pub fn main() { assert_eq!(1, foo1()); assert_eq!(3, foo2()); assert_eq!(3, foo3()); }
using NUnit.Framework; using Nest.Tests.MockData.Domain; namespace Nest.Tests.Unit.Search.Query.Singles { [TestFixture] public class <API key> { [Test] public void FallbackTerm() { var s = new SearchDescriptor<<API key>>().From(0).Size(10) .Query(q=>q .Conditionless(qs=>qs .Query(qcq=>qcq.Term("<API key>", "")) .Fallback(qcf=>qcf.Term("name", "do_me_instead") ) ) ); var json = TestElasticClient.Serialize(s); var expected = @"{ from: 0, size: 10, query : { term : { name : { value : ""do_me_instead"" } } } }"; Assert.True(json.JsonEquals(expected), json); } [Test] public void FallbackMatch() { var s = new SearchDescriptor<<API key>>().From(0).Size(10) .Query(q => q .Conditionless(qs => qs .Query(qcq => qcq .Match(m => m .OnField(p => p.Name) .Query("") ) ) .Fallback(qcf=>qcf .Match(m => m .OnField(p => p.Name) .Query("do_me_instead") ) ) ) ); var json = TestElasticClient.Serialize(s); var expected = @"{ from: 0, size: 10, query : { match : { name : { query: ""do_me_instead"" } } } }"; Assert.True(json.JsonEquals(expected), json); } [Test] public void UseQuery() { var s = new SearchDescriptor<<API key>>().From(0).Size(10) .Query(q => q .Conditionless(qs => qs .Query(qcq => qcq.Term("name", "NEST")) .Fallback(qcf => qcf.Term("name", "do_me_instead") ) ) ); var json = TestElasticClient.Serialize(s); var expected = @"{ from: 0, size: 10, query : { term : { name : { value : ""NEST"" } } } }"; Assert.True(json.JsonEquals(expected), json); } [Test] public void BothConditionless() { var s = new SearchDescriptor<<API key>>().From(0).Size(10) .Query(q => q .Conditionless(qs => qs .Query(qcq => qcq.Term("name", "")) .Fallback(qcf => qcf.Term("name", "") ) ) ); var json = TestElasticClient.Serialize(s); var expected = @"{ from: 0, size: 10 }"; Assert.True(json.JsonEquals(expected), json); } } }
require "formula" class Xplanetfx < Formula desc "Configure, run or daemonize xplanet for HQ Earth wallpapers" homepage "http://mein-neues-blog.de/xplanetFX/" url "http://repository.mein-neues-blog.de:9000/archive/xplanetfx-2.6.6_all.tar.gz" sha256 "<SHA256-like>" version "2.6.6" bottle do cellar :any sha256 "<SHA256-like>" => :yosemite sha256 "<SHA256-like>" => :mavericks sha256 "<SHA256-like>" => :mountain_lion end option "without-gui", "Build to run xplanetFX from the command-line only" option "with-gnu-sed", "Build to use GNU sed instead of OS X sed" depends_on "xplanet" depends_on "imagemagick" depends_on "wget" depends_on "coreutils" depends_on "gnu-sed" => :optional if build.with? "gui" depends_on "librsvg" depends_on "pygtk" => "with-libglade" end skip_clean "share/xplanetFX" def install inreplace "bin/xplanetFX", "WORKDIR=/usr/share/xplanetFX", "WORKDIR=#{HOMEBREW_PREFIX}/share/xplanetFX" prefix.install "bin", "share" path = "#{Formula["coreutils"].opt_libexec}/gnubin" path += ":#{Formula["gnu-sed"].opt_libexec}/gnubin" if build.with?("gnu-sed") if build.with?("gui") ENV.prepend_create_path "PYTHONPATH", "#{HOMEBREW_PREFIX}/lib/python2.7/site-packages/gtk-2.0" ENV.prepend_create_path "<API key>", "#{HOMEBREW_PREFIX}/lib/gdk-pixbuf-2.0/2.10.0/loaders" end bin.<API key>(libexec+'bin', :PATH => "#{path}:$PATH", :PYTHONPATH => ENV["PYTHONPATH"], :<API key> => ENV["<API key>"]) end def post_install if build.with?("gui") # Change the version directory below with any future update ENV["<API key>"]="#{HOMEBREW_PREFIX}/lib/gdk-pixbuf-2.0/2.10.0/loaders" system "#{HOMEBREW_PREFIX}/bin/<API key>", "--update-cache" end end end
# OpenSSL/crypto/rc4/Makefile DIR= rc4 TOP= ../.. CC= cc CPP= $(CC) -E INCLUDES= CFLAG=-g AR= ar r RC4_ENC=rc4_enc.o rc4_skey.o CFLAGS= $(INCLUDES) $(CFLAG) ASFLAGS= $(INCLUDES) $(ASFLAG) AFLAGS= $(ASFLAGS) GENERAL=Makefile TEST=rc4test.c APPS= LIB=$(TOP)/libcrypto.a LIBSRC=rc4_skey.c rc4_enc.c rc4_utl.c LIBOBJ=$(RC4_ENC) rc4_utl.o SRC= $(LIBSRC) EXHEADER= rc4.h HEADER= $(EXHEADER) rc4_locl.h ALL= $(GENERAL) $(SRC) $(HEADER) top: (cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all) all: lib lib: $(LIBOBJ) $(AR) $(LIB) $(LIBOBJ) $(RANLIB) $(LIB) || echo Never mind. @touch lib rc4-586.s: asm/rc4-586.pl ../perlasm/x86asm.pl $(PERL) asm/rc4-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@ rc4-x86_64.s: asm/rc4-x86_64.pl $(PERL) asm/rc4-x86_64.pl $(PERLASM_SCHEME) > $@ rc4-md5-x86_64.s: asm/rc4-md5-x86_64.pl $(PERL) asm/rc4-md5-x86_64.pl $(PERLASM_SCHEME) > $@ rc4-ia64.S: asm/rc4-ia64.pl $(PERL) asm/rc4-ia64.pl $(CFLAGS) > $@ rc4-parisc.s: asm/rc4-parisc.pl $(PERL) asm/rc4-parisc.pl $(PERLASM_SCHEME) $@ rc4-ia64.s: rc4-ia64.S @case `awk '/^#define RC4_INT/{print$$NF}' $(TOP)/include/openssl/opensslconf.h` in \ int) set -x; $(CC) $(CFLAGS) -DSZ=4 -E rc4-ia64.S > $@ ;; \ char) set -x; $(CC) $(CFLAGS) -DSZ=1 -E rc4-ia64.S > $@ ;; \ *) exit 1 ;; \ esac # GNU make "catch all" rc4-%.s: asm/rc4-%.pl; $(PERL) $< $(PERLASM_SCHEME) $@ files: $(PERL) $(TOP)/util/files.pl "RC4_ENC=$(RC4_ENC)" Makefile >> $(TOP)/MINFO links: @$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER) @$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST) @$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS) install: @[ -n "$(INSTALLTOP)" ] # should be set by top Makefile... @headerlist="$(EXHEADER)"; for i in $$headerlist ; \ do \ (cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \ chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \ done; tags: ctags $(SRC) tests: lint: lint -DLINT $(INCLUDES) $(SRC)>fluff update: depend depend: @[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile... $(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC) dclean: $(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new mv -f Makefile.new $(MAKEFILE) clean: rm -f *.s *.S *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff # DO NOT DELETE THIS LINE -- make depend depends on it. rc4_enc.o: ../../e_os.h ../../include/openssl/bio.h rc4_enc.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h rc4_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h rc4_enc.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h rc4_enc.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h rc4_enc.o: ../../include/openssl/rc4.h ../../include/openssl/safestack.h rc4_enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h rc4_enc.o: ../cryptlib.h rc4_enc.c rc4_locl.h rc4_skey.o: ../../e_os.h ../../include/openssl/bio.h rc4_skey.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h rc4_skey.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h rc4_skey.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h rc4_skey.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h rc4_skey.o: ../../include/openssl/rc4.h ../../include/openssl/safestack.h rc4_skey.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h rc4_skey.o: ../cryptlib.h rc4_locl.h rc4_skey.c rc4_utl.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h rc4_utl.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h rc4_utl.o: ../../include/openssl/ossl_typ.h ../../include/openssl/rc4.h rc4_utl.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h rc4_utl.o: ../../include/openssl/symhacks.h rc4_utl.c
@media screen and (max-width: 991px), screen and (min-device-width: 768px) and (max-device-width: 1024px) and (-<API key>: 2), screen and (min-device-width: 320px) and (max-device-width: 568px) and (-<API key>: 2) { .row-offcanvas { position: relative; -webkit-transition: all 0.25s ease-out; -moz-transition: all 0.25s ease-out; transition: all 0.25s ease-out; } .row-offcanvas-right .sidebar-offcanvas { right: -85%; } .row-offcanvas-right.active { right: 85%; } .sidebar-offcanvas { position: fixed; top: 0; width: 85%; } } #menu-btn { display: none; } @media screen and (max-width: 991px), only screen and (-<API key>: 1.3), only screen and (-<API key>: 13/10), only screen and (min-resolution: 120dpi) { #menu-btn { display: block; position: absolute; right: 15px; padding-bottom: 3px; } } #menu-btn .btn-back { display: none; } #menu-btn .btn-text { display: none; font-size: 1.2em; } #menu-btn .active { display: inline !important; } #sidebar { overflow-y: scroll; height: 85%; max-width: 400px; } #sidebar .list-group { background-color: transparent; border: 0; } #sidebar .list-group .list-group-item { border: 0; margin-left: 20px; color: #666; } @media screen and (max-width: 991px), only screen and (-<API key>: 1.3), only screen and (-<API key>: 13/10), only screen and (min-resolution: 120dpi) { #sidebar { position: absolute; margin-left: 185%; top: 20px; } } .btn-blue { background-color: #7eb5d3; color: #fff; } .btn-blue:hover, .btn-blue:focus { background-color: #a4cbe0; color: #000; outline: none !important; }