answer
stringlengths 15
1.25M
|
|---|
require('ember-runtime/core');
require('ember-runtime/system/core_object');
require('ember-runtime/mixins/mutable_enumerable');
require('ember-runtime/mixins/copyable');
require('ember-runtime/mixins/freezable');
/**
@module ember
@submodule ember-runtime
*/
var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, isNone = Ember.isNone, fmt = Ember.String.fmt;
/**
An unordered collection of objects.
A Set works a bit like an array except that its items are not ordered. You
can create a set to efficiently test for membership for an object. You can
also iterate through a set just like an array, even accessing objects by
index, however there is no guarantee as to their order.
All Sets are observable via the Enumerable Observer API - which works
on any enumerable object including both Sets and Arrays.
## Creating a Set
You can create a set like you would most objects using
`new Ember.Set()`. Most new sets you create will be empty, but you can
also initialize the set with some content by passing an array or other
enumerable of objects to the constructor.
Finally, you can pass in an existing set and the set will be copied. You
can also create a copy of a set by calling `Ember.Set#copy()`.
javascript
// creates a new empty set
var foundNames = new Ember.Set();
// creates a set with four names in it.
var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P
// creates a copy of the names set.
var namesCopy = new Ember.Set(names);
// same as above.
var anotherNamesCopy = names.copy();
## Adding/Removing Objects
You generally add or remove objects from a set using `add()` or
`remove()`. You can add any type of object including primitives such as
numbers, strings, and booleans.
Unlike arrays, objects can only exist one time in a set. If you call `add()`
on a set with the same object multiple times, the object will only be added
once. Likewise, calling `remove()` with the same object multiple times will
remove the object the first time and have no effect on future calls until
you add the object to the set again.
NOTE: You cannot add/remove `null` or `undefined` to a set. Any attempt to do
so will be ignored.
In addition to add/remove you can also call `push()`/`pop()`. Push behaves
just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary
object, remove it and return it. This is a good way to use a set as a job
queue when you don't care which order the jobs are executed in.
## Testing for an Object
To test for an object's presence in a set you simply call
`Ember.Set#contains()`.
## Observing changes
When using `Ember.Set`, you can observe the `"[]"` property to be
alerted whenever the content changes. You can also add an enumerable
observer to the set to be notified of specific objects that are added and
removed from the set. See `Ember.Enumerable` for more information on
enumerables.
This is often unhelpful. If you are filtering sets of objects, for instance,
it is very inefficient to re-filter all of the items each time the set
changes. It would be better if you could just adjust the filtered set based
on what was changed on the original set. The same issue applies to merging
sets, as well.
## Other Methods
`Ember.Set` primary implements other mixin APIs. For a complete reference
on the methods you will use with `Ember.Set`, please consult these mixins.
The most useful ones will be `Ember.Enumerable` and
`Ember.MutableEnumerable` which implement most of the common iterator
methods you are used to on Array.
Note that you can also use the `Ember.Copyable` and `Ember.Freezable`
APIs on `Ember.Set` as well. Once a set is frozen it can no longer be
modified. The benefit of this is that when you call `frozenCopy()` on it,
Ember will avoid making copies of the set. This allows you to write
code that can know with certainty when the underlying set data will or
will not be modified.
@class Set
@namespace Ember
@extends Ember.CoreObject
@uses Ember.MutableEnumerable
@uses Ember.Copyable
@uses Ember.Freezable
@since Ember 0.9
*/
Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable,
/** @scope Ember.Set.prototype */ {
// IMPLEMENT ENUMERABLE APIS
/**
This property will change as the number of objects in the set changes.
@property length
@type number
@default 0
*/
length: 0,
/**
Clears the set. This is useful if you want to reuse an existing set
without having to recreate it.
javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.length; // 3
colors.clear();
colors.length; // 0
@method clear
@return {Ember.Set} An empty Set
*/
clear: function() {
if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); }
var len = get(this, 'length');
if (len === 0) { return this; }
var guid;
this.<API key>(len, 0);
Ember.propertyWillChange(this, 'firstObject');
Ember.propertyWillChange(this, 'lastObject');
for (var i=0; i < len; i++){
guid = guidFor(this[i]);
delete this[guid];
delete this[i];
}
set(this, 'length', 0);
Ember.propertyDidChange(this, 'firstObject');
Ember.propertyDidChange(this, 'lastObject');
this.<API key>(len, 0);
return this;
},
/**
Returns true if the passed object is also an enumerable that contains the
same objects as the receiver.
javascript
var colors = ["red", "green", "blue"],
same_colors = new Ember.Set(colors);
same_colors.isEqual(colors); // true
same_colors.isEqual(["purple", "brown"]); // false
@method isEqual
@param {Ember.Set} obj the other object.
@return {Boolean}
*/
isEqual: function(obj) {
// fail fast
if (!Ember.Enumerable.detect(obj)) return false;
var loc = get(this, 'length');
if (get(obj, 'length') !== loc) return false;
while(--loc >= 0) {
if (!obj.contains(this[loc])) return false;
}
return true;
},
/**
Adds an object to the set. Only non-`null` objects can be added to a set
and those can only be added once. If the object is already in the set or
the passed value is null this method will have no effect.
This is an alias for `Ember.MutableEnumerable.addObject()`.
javascript
var colors = new Ember.Set();
colors.add("blue"); // ["blue"]
colors.add("blue"); // ["blue"]
colors.add("red"); // ["blue", "red"]
colors.add(null); // ["blue", "red"]
colors.add(undefined); // ["blue", "red"]
@method add
@param {Object} obj The object to add.
@return {Ember.Set} The set itself.
*/
add: Ember.aliasMethod('addObject'),
/**
Removes the object from the set if it is found. If you pass a `null` value
or an object that is already not in the set, this method will have no
effect. This is an alias for `Ember.MutableEnumerable.removeObject()`.
javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.remove("red"); // ["blue", "green"]
colors.remove("purple"); // ["blue", "green"]
colors.remove(null); // ["blue", "green"]
@method remove
@param {Object} obj The object to remove
@return {Ember.Set} The set itself.
*/
remove: Ember.aliasMethod('removeObject'),
/**
Removes the last element from the set and returns it, or `null` if it's empty.
javascript
var colors = new Ember.Set(["green", "blue"]);
colors.pop(); // "blue"
colors.pop(); // "green"
colors.pop(); // null
@method pop
@return {Object} The removed object from the set or null.
*/
pop: function() {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
var obj = this.length > 0 ? this[this.length-1] : null;
this.remove(obj);
return obj;
},
/**
Inserts the given object on to the end of the set. It returns
the set itself.
This is an alias for `Ember.MutableEnumerable.addObject()`.
javascript
var colors = new Ember.Set();
colors.push("red"); // ["red"]
colors.push("green"); // ["red", "green"]
colors.push("blue"); // ["red", "green", "blue"]
@method push
@return {Ember.Set} The set itself.
*/
push: Ember.aliasMethod('addObject'),
/**
Removes the last element from the set and returns it, or `null` if it's empty.
This is an alias for `Ember.Set.pop()`.
javascript
var colors = new Ember.Set(["green", "blue"]);
colors.shift(); // "blue"
colors.shift(); // "green"
colors.shift(); // null
@method shift
@return {Object} The removed object from the set or null.
*/
shift: Ember.aliasMethod('pop'),
/**
Inserts the given object on to the end of the set. It returns
the set itself.
This is an alias of `Ember.Set.push()`
javascript
var colors = new Ember.Set();
colors.unshift("red"); // ["red"]
colors.unshift("green"); // ["red", "green"]
colors.unshift("blue"); // ["red", "green", "blue"]
@method unshift
@return {Ember.Set} The set itself.
*/
unshift: Ember.aliasMethod('push'),
/**
Adds each object in the passed enumerable to the set.
This is an alias of `Ember.MutableEnumerable.addObjects()`
javascript
var colors = new Ember.Set();
colors.addEach(["red", "green", "blue"]); // ["red", "green", "blue"]
@method addEach
@param {Ember.Enumerable} objects the objects to add.
@return {Ember.Set} The set itself.
*/
addEach: Ember.aliasMethod('addObjects'),
/**
Removes each object in the passed enumerable to the set.
This is an alias of `Ember.MutableEnumerable.removeObjects()`
javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.removeEach(["red", "blue"]); // ["green"]
@method removeEach
@param {Ember.Enumerable} objects the objects to remove.
@return {Ember.Set} The set itself.
*/
removeEach: Ember.aliasMethod('removeObjects'),
// PRIVATE ENUMERABLE SUPPORT
init: function(items) {
this._super();
if (items) this.addObjects(items);
},
// implement Ember.Enumerable
nextObject: function(idx) {
return this[idx];
},
// more optimized version
firstObject: Ember.computed(function() {
return this.length > 0 ? this[0] : undefined;
}),
// more optimized version
lastObject: Ember.computed(function() {
return this.length > 0 ? this[this.length-1] : undefined;
}),
// implements Ember.MutableEnumerable
addObject: function(obj) {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
if (isNone(obj)) return this; // nothing to do
var guid = guidFor(obj),
idx = this[guid],
len = get(this, 'length'),
added ;
if (idx>=0 && idx<len && (this[idx] === obj)) return this; // added
added = [obj];
this.<API key>(null, added);
Ember.propertyWillChange(this, 'lastObject');
len = get(this, 'length');
this[guid] = len;
this[len] = obj;
set(this, 'length', len+1);
Ember.propertyDidChange(this, 'lastObject');
this.<API key>(null, added);
return this;
},
// implements Ember.MutableEnumerable
removeObject: function(obj) {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
if (isNone(obj)) return this; // nothing to do
var guid = guidFor(obj),
idx = this[guid],
len = get(this, 'length'),
isFirst = idx === 0,
isLast = idx === len-1,
last, removed;
if (idx>=0 && idx<len && (this[idx] === obj)) {
removed = [obj];
this.<API key>(removed, null);
if (isFirst) { Ember.propertyWillChange(this, 'firstObject'); }
if (isLast) { Ember.propertyWillChange(this, 'lastObject'); }
// swap items - basically move the item to the end so it can be removed
if (idx < len-1) {
last = this[len-1];
this[idx] = last;
this[guidFor(last)] = idx;
}
delete this[guid];
delete this[len-1];
set(this, 'length', len-1);
if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); }
if (isLast) { Ember.propertyDidChange(this, 'lastObject'); }
this.<API key>(removed, null);
}
return this;
},
// optimized version
contains: function(obj) {
return this[guidFor(obj)]>=0;
},
copy: function() {
var C = this.constructor, ret = new C(), loc = get(this, 'length');
set(ret, 'length', loc);
while(--loc>=0) {
ret[loc] = this[loc];
ret[guidFor(this[loc])] = loc;
}
return ret;
},
toString: function() {
var len = this.length, idx, array = [];
for(idx = 0; idx < len; idx++) {
array[idx] = this[idx];
}
return fmt("Ember.Set<%@>", [array.join(',')]);
}
});
|
// <summary>
// A visual element that shows a wireframe for the specified bounding box.
// </summary>
namespace HelixToolkit.Wpf
{
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media.Media3D;
<summary>
A visual element that shows a wireframe for the specified bounding box.
</summary>
public class <API key> : LinesVisual3D
{
<summary>
Identifies the <see cref="BoundingBox"/> dependency property.
</summary>
public static readonly DependencyProperty BoundingBoxProperty = DependencyProperty.Register(
"BoundingBox", typeof(Rect3D), typeof(<API key>), new UIPropertyMetadata(new Rect3D(), BoxChanged));
<summary>
Gets or sets the bounding box.
</summary>
<value> The bounding box. </value>
public Rect3D BoundingBox
{
get
{
return (Rect3D)this.GetValue(BoundingBoxProperty);
}
set
{
this.SetValue(BoundingBoxProperty, value);
}
}
<summary>
Updates the box.
</summary>
protected virtual void OnBoxChanged()
{
if (this.BoundingBox.IsEmpty)
{
this.Points = null;
return;
}
var points = new List<Point3D>();
var bb = this.BoundingBox;
var p0 = new Point3D(bb.X, bb.Y, bb.Z);
var p1 = new Point3D(bb.X, bb.Y + bb.SizeY, bb.Z);
var p2 = new Point3D(bb.X + bb.SizeX, bb.Y + bb.SizeY, bb.Z);
var p3 = new Point3D(bb.X + bb.SizeX, bb.Y, bb.Z);
var p4 = new Point3D(bb.X, bb.Y, bb.Z + bb.SizeZ);
var p5 = new Point3D(bb.X, bb.Y + bb.SizeY, bb.Z + bb.SizeZ);
var p6 = new Point3D(bb.X + bb.SizeX, bb.Y + bb.SizeY, bb.Z + bb.SizeZ);
var p7 = new Point3D(bb.X + bb.SizeX, bb.Y, bb.Z + bb.SizeZ);
Action<Point3D, Point3D> addEdge = (p, q) =>
{
points.Add(p);
points.Add(q);
};
addEdge(p0, p1);
addEdge(p1, p2);
addEdge(p2, p3);
addEdge(p3, p0);
addEdge(p4, p5);
addEdge(p5, p6);
addEdge(p6, p7);
addEdge(p7, p4);
addEdge(p0, p4);
addEdge(p1, p5);
addEdge(p2, p6);
addEdge(p3, p7);
this.Points = points;
}
<summary>
Called when the box dimensions changed.
</summary>
<param name="d">
The sender.
</param>
<param name="e">
The event arguments.
</param>
private static void BoxChanged(DependencyObject d, <API key> e)
{
((<API key>)d).OnBoxChanged();
}
}
}
|
using UnityEngine;
using System;
using System.Collections.Generic;
namespace HUX.Utility
{
public class AABBTree<T> where T : class
{
#region Private Classes
<summary>
Node class for the tree. CAn be either a branch or a leaf.
</summary>
private class AABBNode
{
#region Public Static Functions
<summary>
Creates a node containing both bounds.
</summary>
<param name="rightBounds"></param>
<param name="leftBounds"></param>
<returns></returns>
public static AABBNode CreateNode(Bounds rightBounds, Bounds leftBounds)
{
AABBNode newNode = new AABBNode();
newNode.Bounds = rightBounds.ExpandToContian(leftBounds);
return newNode;
}
<summary>
Creates a node with the bounds and data.
</summary>
<param name="bounds"></param>
<param name="data"></param>
<returns></returns>
public static AABBNode CreateNode(Bounds bounds, T data)
{
AABBNode newNode = new AABBNode();
newNode.Bounds = bounds;
newNode.UserData = data;
// Determine if we want a margin bounds;
return newNode;
}
#endregion
#region Public Variables
<summary>
Children of this node.
</summary>
public AABBNode[] Children = new AABBNode[2];
<summary>
The Axis Aligned Bounding Box for this node.
</summary>
public Bounds Bounds;
<summary>
User Data for this node.
</summary>
public T UserData;
#endregion
#region Private Variables
<summary>
A weak reference to the parent so the tree will get cleaned up if the root node is no longer referenced.
</summary>
private WeakReference m_ParentRef;
#endregion
#region Accessors
<summary>
True if this is a branch node with no children assigned.
</summary>
public bool IsLeaf
{
get
{
return Children[0] == null && Children[1] == null;
}
}
<summary>
Accessor for setting/getting the parent.
</summary>
public AABBNode Parent
{
get
{
return m_ParentRef != null && m_ParentRef.IsAlive ? m_ParentRef.Target as AABBNode : null;
}
set
{
if (value == null)
{
m_ParentRef = null;
}
else
{
m_ParentRef = new WeakReference(value);
}
}
}
#endregion
#region Public Functions
<summary>
Sets the children for this node.
</summary>
<param name="child1"></param>
<param name="child2"></param>
public void SetChildren(AABBNode child1, AABBNode child2)
{
child1.Parent = this;
child2.Parent = this;
Children[0] = child1;
Children[1] = child2;
}
<summary>
Sets the bounds to the size of both children.
</summary>
public void RebuildBounds()
{
Bounds = Children[0].Bounds.ExpandToContian(Children[1].Bounds);
}
#endregion
}
#endregion
#region Private Variables
<summary>
The root node of the tree.
</summary>
private AABBNode m_RootNode;
#endregion
#region Public Functions
<summary>
Creates a new node with the provided bounds.
</summary>
<param name="bounds"></param>
<param name="data"></param>
public void Insert(Bounds bounds, T data)
{
AABBNode newNode = AABBNode.CreateNode(bounds, data);
if (m_RootNode == null)
{
m_RootNode = newNode;
}
else
{
RecursiveInsert(m_RootNode, newNode);
}
}
<summary>
Removes the node containing data.
</summary>
<param name="data"></param>
public void Remove(T data)
{
AABBNode node = FindNode(data);
RemoveNode(node);
}
<summary>
Removes the node with the bounds. If two nodes have the exact same bounds only the first one found will be removed.
</summary>
<param name="bounds"></param>
public void Remove(Bounds bounds)
{
AABBNode node = FindNode(bounds);
RemoveNode(node);
}
<summary>
Destroys all nodes in the tree.
</summary>
public void Clear()
{
// All we need to do is remove the root node reference. The garbage collector will do the rest.
m_RootNode = null;
}
#endregion
#region Private Functions
<summary>
Recursively Insert the new Node until we hit a leaf node. Then branch and insert both nodes.
</summary>
<param name="currentNode"></param>
<param name="newNode"></param>
private void RecursiveInsert(AABBNode currentNode, AABBNode newNode)
{
AABBNode branch = currentNode;
if (currentNode.IsLeaf)
{
branch = AABBNode.CreateNode(currentNode.Bounds, newNode.Bounds);
branch.Parent = currentNode.Parent;
if (currentNode == m_RootNode)
{
m_RootNode = branch;
}
else
{
branch.Parent.Children[branch.Parent.Children[0] == currentNode ? 0 : 1] = branch;
}
branch.SetChildren(currentNode, newNode);
}
else
{
Bounds withChild1 = branch.Children[0].Bounds.ExpandToContian(newNode.Bounds);
Bounds withChild2 = branch.Children[1].Bounds.ExpandToContian(newNode.Bounds);
float volume1 = withChild1.Volume();
float volume2 = withChild2.Volume();
RecursiveInsert((volume1 <= volume2) ? branch.Children[0] : branch.Children[1], newNode);
}
branch.RebuildBounds();
}
<summary>
Finds the node that has the assigned user data.
</summary>
<param name="userData"></param>
<returns></returns>
private AABBNode FindNode(T userData)
{
AABBNode foundNode = null;
List<AABBNode> nodesToSearch = new List<AABBNode>();
nodesToSearch.Add(m_RootNode);
while (nodesToSearch.Count > 0)
{
AABBNode currentNode = nodesToSearch[0];
nodesToSearch.RemoveAt(0);
if (currentNode.UserData == userData)
{
foundNode = currentNode;
break;
}
else if (!currentNode.IsLeaf)
{
nodesToSearch.AddRange(currentNode.Children);
}
}
return foundNode;
}
<summary>
Finds the leaf node that matches bounds.
</summary>
<param name="bounds"></param>
<returns></returns>
private AABBNode FindNode(Bounds bounds)
{
AABBNode foundNode = null;
AABBNode currentNode = m_RootNode;
while (currentNode != null)
{
if (currentNode.IsLeaf)
{
foundNode = currentNode.Bounds == bounds ? currentNode : null;
break;
}
else
{
//Which child node if any would the bounds be in?
if (currentNode.Children[0].Bounds.ContainsBounds(bounds))
{
currentNode = currentNode.Children[0];
}
else if (currentNode.Children[1].Bounds.ContainsBounds(bounds))
{
currentNode = currentNode.Children[1];
}
else
{
currentNode = null;
}
}
}
return foundNode;
}
<summary>
Removes a node from the tree
</summary>
<param name="node"></param>
private void RemoveNode(AABBNode node)
{
AABBNode nodeParent = node.Parent;
if (node == m_RootNode)
{
m_RootNode = null;
}
else
{
AABBNode otherChild = nodeParent.Children[0] == node ? nodeParent.Children[1] : nodeParent.Children[0];
if (nodeParent.Parent == null)
{
m_RootNode = otherChild;
otherChild.Parent = null;
}
else
{
int childIndex = nodeParent.Parent.Children[0] == nodeParent ? 0 : 1;
nodeParent.Parent.Children[childIndex] = otherChild;
otherChild.Parent = nodeParent.Parent;
}
UpdateNodeBoundUp(otherChild.Parent);
}
}
<summary>
Updates the bounds nonleaf node object moving up the Parent tree to Root.
</summary>
<param name="node"></param>
private void UpdateNodeBoundUp(AABBNode node)
{
if (node != null)
{
if (!node.IsLeaf)
{
node.RebuildBounds();
}
UpdateNodeBoundUp(node.Parent);
}
}
#endregion
}
}
|
(function (root, factory) {
if (root === undefined && window !== undefined) root = window;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(root["jQuery"]);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Нищо избрано',
noneResultsText: 'Няма резултат за {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? "{0} избран елемент" : "{0} избрани елемента";
},
maxOptionsText: function (numAll, numGroup) {
return [
(numAll == 1) ? 'Лимита е достигнат ({n} елемент максимум)' : 'Лимита е достигнат ({n} елемента максимум)',
(numGroup == 1) ? 'Груповия лимит е достигнат ({n} елемент максимум)' : 'Груповия лимит е достигнат ({n} елемента максимум)'
];
},
selectAllText: 'Избери всички',
deselectAllText: 'Размаркирай всички',
multipleSeparator: ', '
};
})(jQuery);
}));
|
<?php
declare(strict_types=1);
namespace Sylius\Component\Core\Promotion\Checker\Rule;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\OrderItemInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Promotion\Checker\Rule\<API key>;
use Sylius\Component\Promotion\Exception\<API key>;
use Sylius\Component\Promotion\Model\<API key>;
final class HasTaxonRuleChecker implements <API key>
{
public const TYPE = 'has_taxon';
/**
* {@inheritdoc}
*
* @throws <API key>
*/
public function isEligible(<API key> $subject, array $configuration): bool
{
if (!isset($configuration['taxons'])) {
return false;
}
if (!$subject instanceof OrderInterface) {
throw new <API key>($subject, OrderInterface::class);
}
/** @var OrderItemInterface $item */
foreach ($subject->getItems() as $item) {
if ($this-><API key>($item->getProduct(), $configuration)) {
return true;
}
}
return false;
}
/**
* @param ProductInterface $product
* @param array $configuration
*
* @return bool
*/
private function <API key>(ProductInterface $product, array $configuration): bool
{
foreach ($product->getTaxons() as $taxon) {
if (in_array($taxon->getCode(), $configuration['taxons'], true)) {
return true;
}
}
return false;
}
}
|
require 'faraday'
require 'json'
module Twitter
module REST
module Response
class ParseJson < Faraday::Response::Middleware
WHITESPACE_REGEX = /\A^\s*$\z/
def parse(body)
case body
when WHITESPACE_REGEX, nil
nil
else
JSON.parse(body, :symbolize_names => true)
end
end
def on_complete(response)
response.body = parse(response.body) if respond_to?(:parse) && !<API key>.include?(response.status)
end
def <API key>
[204, 301, 302, 304]
end
end
end
end
end
Faraday::Response.register_middleware :<TwitterConsumerkey> => Twitter::REST::Response::ParseJson
|
package org.spongepowered.api.event.item.inventory;
import org.spongepowered.api.entity.living.Living;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.item.inventory.ItemStack;
public interface <API key> extends <API key>, AffectSlotEvent, Cancellable {
/**
* Fired when a {@link Living} changes it's equipment.
*/
interface Equipment extends <API key> {}
/**
* Fired when a {@link Living} changes it's held {@link ItemStack}.
*/
interface Held extends <API key> {}
interface Transfer extends <API key> {}
interface Pickup extends <API key> {}
}
|
<h2></h2>
<p>
() <span class="filename">include/config_default.inc.php</span></p>
<p></p>
<h3></h3>
<ul>
<li><strong></strong>: RSS</li>
<li><strong></strong>: </li>
<li><strong>URI</strong>: RSS</li>
<li><strong></strong>:
</li>
<li><strong></strong>: </li>
<li><strong></strong>: </li>
<li><strong></strong>: </li>
<li><strong></strong>: </li>
<li><strong></strong>: </li>
</ul>
<h3></h3>
<p><span
class="pwgScreen">category.php</span><span
class="pwgScreen">picture.php</span><code>history</code></p>
<p><span class="pwgScreen"> > > </span></p>
<ul>
<li><strong></strong>: </li>
<li><strong></strong>: </li>
<li><strong></strong>: </li>
</ul>
<h3></h3>
<ul>
<li><strong></strong>: </li>
<li><strong>1</strong>.</li>
<li><strong></strong>:
<span class="pwgScreen"> > > </span></li>
<li><strong></strong>:
</li>
<li><strong></strong>:
<span class="pwgScreen"> > > </span></li>
</ul>
<!--TODO --><h3></h3>
<ul>
<!--TODO --> <li><strong></strong>: </li>
<!--TODO --> <li><strong></strong>: </li>
<li><strong></strong>: </li>
</ul>
<h3></h3>
<p>
(<span class="pwgScreen"></span>) </p>
<p><span class="pwgScreen"> > > </span>
</p>
<ul>
<li><strong></strong>: Piwigo</li>
<li><strong>1</strong></li>
<li><strong>1</strong></li>
<li><strong></strong></li>
<li><strong></strong>: 1</li>
<li><strong></strong>: ?
<em></em>: </li>
<li><strong></strong>: </li>
<li><strong></strong>:
: <br />
$conf['show_nb_hits'] = true; <br />
: false</li>
<li><strong></strong>:
</li>
<li><strong></strong>: </li>
</ul>
|
table.tablesaw {
empty-cells: show;
max-width: 100%;
width: 100%;
}
.tablesaw {
border-collapse: collapse;
width: 100%;
}
/* Structure */
.tablesaw {
border: 0;
padding: 0;
}
.tablesaw th,
.tablesaw td {
box-sizing: border-box;
padding: .5em .7em;
}
.tablesaw thead tr:first-child th {
padding-top: .9em;
padding-bottom: .7em;
}
.tablesaw-enhanced .tablesaw-bar .btn {
border: 1px solid #ccc;
background: none;
background-color: #fafafa;
box-shadow: 0 1px 0 rgba(255,255,255,1);
color: #4a4a4a;
clear: both;
cursor: pointer;
display: block;
font: bold 20px/1 sans-serif;
margin: 0;
padding: .5em .85em .4em .85em;
position: relative;
text-align: center;
text-decoration: none;
text-transform: capitalize;
text-shadow: 0 1px 0 #fff;
width: 100%;
/* Theming */
background-image: -<API key>(top, rgba( 255,255,255,.1 ) 0%, rgba( 255,255,255,.1 ) 50%, rgba( 170,170,170,.1 ) 55%, rgba( 120,120,120,.15 ) 100%);
background-image: linear-gradient( top, rgba( 255,255,255,.1 ) 0%, rgba( 255,255,255,.1 ) 50%, rgba( 170,170,170,.1 ) 55%, rgba( 120,120,120,.15 ) 100% );
-webkit-appearance: none !important;
-moz-appearance: none !important;
box-sizing: border-box;
-<API key>: antialiased;
border-radius: .25em;
}
.tablesaw-enhanced .tablesaw-bar a.btn {
color: #1c95d4;
}
.tablesaw-enhanced .tablesaw-bar .btn:hover {
text-decoration: none;
}
/* Default radio/checkbox styling horizonal controlgroups. */
.tablesaw-enhanced .tablesaw-bar .btn:active {
background-color: #ddd;
background-image: -<API key>(top, rgba( 100,100,100,.35 ) 0%, rgba( 255,255,255,0 ) 70%);
background-image: linear-gradient( top, rgba( 100,100,100,.35 ) 0%, rgba( 255,255,255,0 ) 70% );
}
.tablesaw-enhanced .tablesaw-bar .btn:hover,
.tablesaw-enhanced .tablesaw-bar .btn:focus {
color: #208de3;
background-color: #fff;
outline: none;
}
.tablesaw-bar .btn:focus {
box-shadow: 0 0 .35em #4faeef !important;
}
.tablesaw-bar .btn-select select {
background: none;
border: none;
display: block;
position: absolute;
font-weight: inherit;
left: 0;
top: 0;
margin: 0;
width: 100%;
height: 100%;
z-index: 2;
min-height: 1em;
}
.tablesaw-bar .btn-select select {
opacity: 0;
filter: alpha(opacity=0);
display: inline-block;
color: transparent;
}
.tablesaw-bar .btn select option {
background: #fff;
color: #000;
font-family: sans-serif;
}
.tablesaw-enhanced .tablesaw-bar .btn.btn-select {
color: #4d4d4d;
padding-right: 2.5em;
min-width: 7.25em;
text-align: left;
text-indent: 0;
}
.tablesaw-bar .btn.btn-small,
.tablesaw-bar .btn.btn-micro {
display: inline-block;
width: auto;
height: auto;
position: relative;
top: 0;
}
.tablesaw-bar .btn.btn-small {
font-size: 1.0625em;
line-height: 19px;
padding: .3em 1em .3em 1em;
}
.tablesaw-bar .btn.btn-micro {
font-size: .8125em;
padding: .4em .7em .25em .7em;
}
.tablesaw-enhanced .tablesaw-bar .btn-select {
text-align: left;
}
.tablesaw-bar .btn-select:after {
background: #e5e5e5;
background: rgba(0,0,0,.1);
box-shadow: 0 2px 2px rgba(255,255,255,.25);
content: " ";
display: block;
position: absolute;
}
.tablesaw-bar .btn-select.btn-small,
.tablesaw-bar .btn-select.btn-micro {
padding-right: 1.5em;
}
.tablesaw-bar .btn-select:after {
background: none;
background-repeat: no-repeat;
background-position: .25em .45em;
content: "\25bc";
font-size: .55em;
padding-top: 1.2em;
padding-left: 1em;
left: auto;
right: 0;
margin: 0;
top: 0;
bottom: 0;
width: 1.8em;
}
.tablesaw-bar .btn-select.btn-small:after,
.tablesaw-bar .btn-select.btn-micro:after {
width: 1.2em;
font-size: .5em;
padding-top: 1em;
padding-right: .5em;
line-height: 1.65;
background: none;
box-shadow: none;
border-left-width: 0;
}
/* Column navigation buttons for swipe and columntoggle tables */
.tablesaw-advance .btn {
-webkit-appearance: none;
-moz-appearance: none;
box-sizing: border-box;
text-shadow: 0 1px 0 #fff;
border-radius: .25em;
}
.tablesaw-advance .btn.btn-micro {
font-size: .8125em;
padding: .3em .7em .25em .7em;
}
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn {
display: inline-block;
overflow: hidden;
width: 1.8em;
height: 1.8em;
background-position: 50% 50%;
margin-left: .5em;
position: relative;
}
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.left:before,
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.right:before,
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.down:before,
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.up:before {
content: "\0020";
overflow: hidden;
width: 0;
height: 0;
position: absolute;
}
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.down:before {
left: .5em;
top: .65em;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #808080;
}
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.up:before {
left: .5em;
top: .65em;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid #808080;
}
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.left:before,
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.right:before {
top: .45em;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
}
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.left:before {
left: .6em;
border-right: 5px solid #808080;
}
.tablesaw-bar .tablesaw-advance a.tablesaw-nav-btn.right:before {
left: .7em;
border-left: 5px solid #808080;
}
.tablesaw-advance a.tablesaw-nav-btn.disabled {
opacity: .25;
filter: alpha(opacity=25);
cursor: default;
pointer-events: none;
}
/* Table Toolbar */
.tablesaw-bar {
clear: both;
font-family: sans-serif;
}
.tablesaw-toolbar {
font-size: .875em;
float: left;
}
.tablesaw-toolbar label {
padding: .5em 0;
clear: both;
display: block;
color: #888;
margin-right: .5em;
text-transform: uppercase;
}
.tablesaw-bar .btn,
.tablesaw-enhanced .tablesaw-bar .btn {
margin-top: .5em;
margin-bottom: .5em;
}
.tablesaw-bar .btn-select,
.tablesaw-enhanced .tablesaw-bar .btn-select {
margin-bottom: 0;
}
.tablesaw-bar .tablesaw-toolbar .btn {
margin-left: .4em;
margin-top: 0;
text-transform: uppercase;
border: none;
box-shadow: none;
background: transparent;
font-family: sans-serif;
font-size: 1em;
padding-left: .3em;
}
.tablesaw-bar .tablesaw-toolbar .btn-select {
min-width: 0;
}
.tablesaw-bar .tablesaw-toolbar .btn-select:after {
padding-top: .9em;
}
.tablesaw-bar .tablesaw-toolbar select {
color: #888;
text-transform: none;
background: transparent;
}
.tablesaw-toolbar ~ table {
clear: both;
}
.tablesaw-toolbar .a11y-sm {
clip: rect(0 0 0 0);
height: 1px;
overflow: hidden;
position: absolute;
width: 1px;
}
@media (min-width: 24em) {
.tablesaw-toolbar .a11y-sm {
clip: none;
height: auto;
width: auto;
position: static;
overflow: visible;
}
}
table.tablesaw tbody th {
font-weight: bold;
}
table.tablesaw thead th,
table.tablesaw thead td {
color: #444;
font-size: .9em;
}
.tablesaw th,
.tablesaw td {
line-height: 1em;
text-align: left;
vertical-align: middle;
}
.tablesaw td,
.tablesaw tbody th {
vertical-align: middle;
font-size: 1.17em;
/* 19px */
}
.tablesaw td .btn,
.tablesaw tbody th .btn {
margin: 0;
}
.tablesaw thead {
border: 1px solid #e5e5e4;
background: #e2dfdc;
background-image: -<API key>(top, #fff, #e2dfdc);
background-image: linear-gradient(to bottom, #fff, #e2dfdc);
}
.tablesaw thead th {
font-weight: 100;
color: #777;
text-transform: uppercase;
text-shadow: 0 1px 0 #fff;
text-align: left;
}
.tablesaw thead tr:first-child th {
font-weight: normal;
font-family: sans-serif;
border-right: 1px solid #e4e1de;
}
/* Table rows have a gray bottom stroke by default */
.tablesaw tbody tr {
border-bottom: 1px solid #dfdfdf;
}
.tablesaw caption {
text-align: left;
margin-bottom: 0;
opacity: .5;
filter: alpha(opacity=50);
line-height: 2.4;
}
@media (min-width: 25em) {
.tablesaw caption {
margin-bottom: .6em;
line-height: 1.2;
}
}
/* Stack */
.<API key> {
text-transform: uppercase;
font-size: .9em;
font-weight: normal;
}
.tablesaw-cell-label {
font-size: .65em;
text-transform: uppercase;
color: #888;
font-family: sans-serif;
}
@media (min-width: 40em) {
.tablesaw td {
line-height: 2em;
}
}
@media only all {
.tablesaw-swipe .<API key> {
border-right: 1px solid #e4e1de;
}
.tablesaw-swipe .<API key> {
box-shadow: 3px 0 4px -1px #e4e1de;
}
}
/* Table rows have a gray bottom stroke by default */
.tablesaw-stack tbody tr {
border-bottom: 1px solid #dfdfdf;
}
.tablesaw-stack td .tablesaw-cell-label,
.tablesaw-stack th .tablesaw-cell-label {
display: none;
}
/* Mobile first styles: Begin with the stacked presentation at narrow widths */
@media only all {
/* Show the table cells as a block level element */
.tablesaw-stack td,
.tablesaw-stack th {
text-align: left;
display: block;
}
.tablesaw-stack tr {
clear: both;
display: table-row;
}
/* Make the label elements a percentage width */
.tablesaw-stack td .tablesaw-cell-label,
.tablesaw-stack th .tablesaw-cell-label {
display: block;
padding: 0 .6em 0 0;
width: 30%;
display: inline-block;
}
/* For grouped headers, have a different style to visually separate the levels by classing the first label in each col group */
.tablesaw-stack th .<API key>,
.tablesaw-stack td .<API key> {
display: block;
padding: .4em 0;
margin: .4em 0;
}
.tablesaw-cell-label {
display: block;
}
/* Avoid double strokes when stacked */
.tablesaw-stack tbody th.group {
margin-top: -1px;
}
/* Avoid double strokes when stacked */
.tablesaw-stack th.group b.tablesaw-cell-label {
display: none !important;
}
}
@media (max-width: 39.9375em) {
.tablesaw-stack thead td,
.tablesaw-stack thead th {
display: none;
}
.tablesaw-stack tbody td,
.tablesaw-stack tbody th {
clear: left;
float: left;
width: 100%;
}
.tablesaw-cell-label {
vertical-align: top;
}
.<API key> {
max-width: 67%;
display: inline-block;
}
.tablesaw-stack td:empty,
.tablesaw-stack th:empty {
display: none;
}
}
/* Media query to show as a standard table at 560px (35em x 16px) or wider */
@media (min-width: 40em) {
.tablesaw-stack tr {
display: table-row;
}
/* Show the table header rows */
.tablesaw-stack td,
.tablesaw-stack th,
.tablesaw-stack thead td,
.tablesaw-stack thead th {
display: table-cell;
margin: 0;
}
/* Hide the labels in each cell */
.tablesaw-stack td .tablesaw-cell-label,
.tablesaw-stack th .tablesaw-cell-label {
display: none !important;
}
}
.<API key> {
table-layout: fixed;
}
@media only all {
/* Unchecked manually: Always hide */
.tablesaw-swipe th.<API key>,
.tablesaw-swipe td.<API key> {
display: none;
}
}
.btn.<API key> span {
text-indent: -9999px;
display: inline-block;
}
.<API key> {
position: relative;
/* for dialog positioning */
}
.<API key> .dialog-content {
padding: .5em;
}
.<API key> tbody td {
line-height: 1.5;
}
/* Remove top/bottom margins around the fieldcontain on check list */
.<API key> {
display: none;
}
.<API key>.visible .<API key> {
display: block;
position: absolute;
top: 2em;
right: 0;
background-color: #fff;
padding: .5em .8em;
border: 1px solid #ccc;
box-shadow: 0 1px 2px #ccc;
border-radius: .2em;
z-index: 1;
}
.<API key> fieldset {
margin: 0;
}
/* Hide all prioritized columns by default */
@media only all {
.<API key> th.tablesaw-priority-6,
.<API key> td.tablesaw-priority-6,
.<API key> th.tablesaw-priority-5,
.<API key> td.tablesaw-priority-5,
.<API key> th.tablesaw-priority-4,
.<API key> td.tablesaw-priority-4,
.<API key> th.tablesaw-priority-3,
.<API key> td.tablesaw-priority-3,
.<API key> th.tablesaw-priority-2,
.<API key> td.tablesaw-priority-2,
.<API key> th.tablesaw-priority-1,
.<API key> td.tablesaw-priority-1 {
display: none;
}
}
.<API key> .dialog-content {
top: 0 !important;
right: 1em;
left: auto !important;
width: 12em;
max-width: 18em;
margin: -.5em auto 0;
}
.<API key> .dialog-content:focus {
outline-style: none;
}
/* Preset breakpoints if "" class added to table */
/* Show priority 1 at 320px (20em x 16px) */
@media (min-width: 20em) {
.<API key> th.tablesaw-priority-1,
.<API key> td.tablesaw-priority-1 {
display: table-cell;
}
}
/* Show priority 2 at 480px (30em x 16px) */
@media (min-width: 30em) {
.<API key> th.tablesaw-priority-2,
.<API key> td.tablesaw-priority-2 {
display: table-cell;
}
}
/* Show priority 3 at 640px (40em x 16px) */
@media (min-width: 40em) {
.<API key> th.tablesaw-priority-3,
.<API key> td.tablesaw-priority-3 {
display: table-cell;
}
.<API key> tbody td {
line-height: 2;
}
}
/* Show priority 4 at 800px (50em x 16px) */
@media (min-width: 50em) {
.<API key> th.tablesaw-priority-4,
.<API key> td.tablesaw-priority-4 {
display: table-cell;
}
}
/* Show priority 5 at 960px (60em x 16px) */
@media (min-width: 60em) {
.<API key> th.tablesaw-priority-5,
.<API key> td.tablesaw-priority-5 {
display: table-cell;
}
}
/* Show priority 6 at 1,120px (70em x 16px) */
@media (min-width: 70em) {
.<API key> th.tablesaw-priority-6,
.<API key> td.tablesaw-priority-6 {
display: table-cell;
}
}
@media only all {
/* Unchecked manually: Always hide */
.<API key> th.<API key>,
.<API key> td.<API key> {
display: none;
}
/* Checked manually: Always show */
.<API key> th.<API key>,
.<API key> td.<API key> {
display: table-cell;
}
}
.<API key> .btn-group > label {
display: block;
padding: .2em 0;
white-space: nowrap;
}
.<API key> .btn-group > label input {
margin-right: .8em;
}
.tablesaw-sortable,
.tablesaw-sortable thead,
.tablesaw-sortable thead tr,
.tablesaw-sortable thead tr th {
position: relative;
}
.tablesaw-sortable thead tr th {
padding-right: 1.6em;
vertical-align: top;
}
.tablesaw-sortable th.<API key>,
.tablesaw-sortable tr:first-child th.<API key> {
padding: 0;
}
.tablesaw-sortable th.<API key> button {
padding-top: .9em;
padding-bottom: .7em;
padding-left: .6em;
padding-right: 1.6em;
}
.tablesaw-sortable .<API key> button {
min-width: 100%;
color: inherit;
background: transparent;
border: 0;
padding: 0;
text-align: left;
font: inherit;
text-transform: inherit;
position: relative;
}
.tablesaw-sortable .<API key>.<API key> button:after,
.tablesaw-sortable .<API key>.<API key> button:after {
width: 7px;
height: 10px;
content: "\0020";
position: absolute;
right: .5em;
}
.tablesaw-sortable .<API key>.<API key> button:after {
content: "\2191";
}
.tablesaw-sortable .<API key>.<API key> button:after {
content: "\2193";
}
.tablesaw-sortable .not-applicable:after {
content: "
display: block;
}
.tablesaw-sortable .not-applicable span {
display: none;
}
.tablesaw-advance {
float: right;
}
.tablesaw-advance.minimap {
margin-right: .4em;
}
.<API key> {
float: left;
margin: 0;
padding: 0;
list-style: none;
}
.<API key> li {
display: table-cell;
margin: 0;
padding: .4em .2em;
}
.<API key> li i {
width: .25em;
height: .25em;
background: #555;
border-radius: 100%;
display: inline-block;
}
.<API key> {
opacity: .25;
filter: alpha(opacity=25);
cursor: default;
pointer-events: none;
}
|
package org.eclipse.persistence.tools.workbench.framework.context;
import org.eclipse.persistence.tools.workbench.framework.resources.<API key>;
import org.eclipse.persistence.tools.workbench.framework.resources.ResourceRepository;
import org.eclipse.persistence.tools.workbench.framework.resources.<API key>;
/**
* Wrap another context and expand its resource
* repository with a resource repository wrapper.
*/
public class <API key> extends <API key> {
private ResourceRepository <API key>;
/**
* Construct a context with an expanded resource repository
* that adds the resources in the specified resource bundle and icon map
* to the original resource repository.
*/
public <API key>(ApplicationContext delegate, Class resourceBundleClass, <API key> <API key>) {
super(delegate);
this.<API key> = new <API key>(this.<API key>(), resourceBundleClass, <API key>);
}
/**
* @see <API key>#<API key>()
*/
public ResourceRepository <API key>() {
return this.<API key>;
}
/**
* Return the original, unwrapped resource repository.
*/
public ResourceRepository <API key>() {
return this.getDelegate().<API key>();
}
}
|
package org.eclipse.persistence.mappings.transformers;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.core.mappings.transformers.<API key>;
import org.eclipse.persistence.mappings.foundation.<API key>;
/**
* PUBLIC:
* This interface is used by the Transformation Mapping to build the value for a
* specific field. The user must provide implementations of this interface to the
* Transformation Mapping.
* @author mmacivor
* @since 10.1.3
*/
public interface FieldTransformer extends <API key><Session> {
/**
* Initialize this transformer. Only required if the user needs some special
* information from the mapping in order to do the transformation
* @param mapping - the mapping this transformer is associated with.
*/
public void initialize(<API key> mapping);
/**
* @param instance - an instance of the domain class which contains the attribute
* @param session - the current session
* @param fieldName - the name of the field being transformed. Used if the user wants to use this transformer for multiple fields.
* @return - The value to be written for the field associated with this transformer
*/
@Override
public Object buildFieldValue(Object instance, String fieldName, Session session);
}
|
package org.eclipse.persistence.testing.tests.writing;
import org.eclipse.persistence.testing.framework.*;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.sessions.server.ClientSession;
import org.eclipse.persistence.testing.framework.WriteObjectTest;
/**
* Test changing private parts of an object.
*/
public class ComplexUpdateTest extends WriteObjectTest {
/** The object which is actually changed */
public Object workingCopy;
public boolean usesUnitOfWork = false;
public boolean <API key> = false;
public boolean shouldCommitParent = false;
/** TODO: Set this to true, and fix issues from tests that fail. */
public boolean shouldCompareClone = true;
public ComplexUpdateTest() {
super();
}
public ComplexUpdateTest(Object originalObject) {
super(originalObject);
}
protected void changeObject() {
// By default do nothing
}
public void <API key>() {
useNestedUnitOfWork();
this.shouldCommitParent = true;
}
public String getName() {
return super.getName() + new Boolean(usesUnitOfWork) + new Boolean(<API key>);
}
public void reset() {
if (getExecutor().getSession().isUnitOfWork()) {
getExecutor().setSession(((UnitOfWork)getSession()).getParent());
// Do the same for nested units of work.
if (getExecutor().getSession().isUnitOfWork()) {
getExecutor().setSession(((UnitOfWork)getSession()).getParent());
}
}
super.reset();
}
protected void setup() {
super.setup();
if (this.usesUnitOfWork) {
getExecutor().setSession(getSession().acquireUnitOfWork());
if (this.<API key>) {
getExecutor().setSession(getSession().acquireUnitOfWork());
}
this.workingCopy = ((UnitOfWork)getSession()).registerObject(this.objectToBeWritten);
} else {
this.workingCopy = this.objectToBeWritten;
}
}
protected void test() {
changeObject();
if (this.usesUnitOfWork) {
// Ensure that the original has not been changed.
if (!((UnitOfWork)getSession()).getParent().compareObjects(this.originalObject, this.objectToBeWritten)) {
throw new TestErrorException("The original object was changed through changing the clone.");
}
((UnitOfWork)getSession()).commit();
getExecutor().setSession(((UnitOfWork)getSession()).getParent());
if (this.<API key>) {
if (this.shouldCommitParent) {
((UnitOfWork)getSession()).commit();
}
getExecutor().setSession(((UnitOfWork)getSession()).getParent());
}
// Ensure that the clone matches the cache.
if (this.shouldCompareClone) {
ClassDescriptor descriptor = getSession().getClassDescriptor(this.objectToBeWritten);
if(descriptor.<API key>()) {
getSession().logMessage("ComplexUpdateTest: descriptor.<API key>() == null. In this case object's changes are not merged back into parent's cache");
} else if (descriptor.<API key>() && getSession().isClientSession()){
if (!getAbstractSession().compareObjects(this.workingCopy, ((ClientSession)getSession()).getParent().<API key>().getFromIdentityMap(this.workingCopy))) {
throw new TestErrorException("The clone does not match the cached object.");
}
}
else {
if (!getAbstractSession().compareObjects(this.workingCopy, this.objectToBeWritten)) {
throw new TestErrorException("The clone does not match the cached object.");
}
}
}
} else {
super.test();
}
}
public void useNestedUnitOfWork() {
this.<API key> = true;
this.usesUnitOfWork = true;
}
}
|
package org.eclipse.persistence.testing.tests.jpa.advanced;
import org.eclipse.persistence.testing.models.jpa.advanced.Project;
/**
* Tests the @PostUpdate events from an Entity.
*
* @author Guy Pelletier
*/
public class <API key> extends CallbackEventTest {
public void test() throws Exception {
m_beforeEvent = 0; // Loading a new object to update, count starts at 0.
Project project = updateProject();
m_afterEvent = project.post_update_count;
}
}
|
<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Main plugin class
*
* @package <API key>
* @since 2.0.0
*/
if ( ! class_exists( '<API key>' ) ) {
final class <API key> {
/**
* Plugin version
*
* @var string
* @since 2.0.0
*/
public static $version = '2.2.10';
/**
* The single instance of the plugin class
*
* @var object
* @since 2.0.0
*/
protected static $_instance = null;
/**
* Instance of admin class
*
* @var object
* @since 2.0.0
*/
protected static $admin = null;
/**
* Instance of admin pointer class
*
* @var object
* @since 2.1.0
*/
protected static $admin_pointer = null;
/**
* Instance of compatibility class
*
* @var object
* @since 2.0.0
*/
protected static $compatibility = null;
/**
* Instance of the text filters class
*
* @var object
* @since 2.0.0
*/
protected static $text_filters = null;
/**
* Return the main plugin instance
*
* @return object
* @since 2.0.0
*/
public static function instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Return the instance of the admin class
*
* @return object
* @since 2.0.0
*/
public static function admin() {
return self::$admin;
}
/**
* Return the instance of the admin pointer class
*
* @return object
* @since 2.1.0
*/
public static function admin_pointer() {
return self::$admin_pointer;
}
/**
* Return the instance of the compatibility class
*
* @return object
* @since 2.0.0
*/
public static function compatibility() {
return self::$compatibility;
}
/**
* Return the instance of the text filters class
*
* @return object
* @since 2.0.0
*/
public static function text_filters() {
return self::$text_filters;
}
/**
* Get plugin version
*
* @return string
* @since 2.0.0
*/
public static function get_version() {
return self::$version;
}
/**
* Get plugin basename
*
* @uses plugin_basename()
*
* @return string
* @since 2.0.0
*/
public static function get_basename() {
return plugin_basename( __FILE__ );
}
/**
* Class constructor
*
* @uses add_action()
* @uses add_filter()
* @uses get_option()
* @uses get_bloginfo()
*
* @global object $wp_embed
* @since 2.0.0
*/
protected function __construct() {
// Include required files
include_once( plugin_dir_path( __FILE__ ) . 'includes/class-widget.php' );
// Include and instantiate admin class on admin pages
if ( is_admin() ) {
include_once( plugin_dir_path( __FILE__ ) . 'includes/class-admin.php' );
self::$admin = <API key>::instance();
include_once( plugin_dir_path( __FILE__ ) . 'includes/class-admin-pointer.php' );
self::$admin_pointer = <API key>::instance();
}
// Include and instantiate text filter class on frontend pages
else {
include_once( plugin_dir_path( __FILE__ ) . 'includes/class-text-filters.php' );
self::$text_filters = <API key>::instance();
}
// Register action and filter hooks
add_action( 'plugins_loaded', array( $this, 'load_compatibility' ), 50 );
add_action( 'widgets_init', array( $this, 'widgets_init' ) );
}
/**
* Prevent the class from being cloned
*
* @return void
* @since 2.0.0
*/
protected function __clone() {
_doing_it_wrong( __FUNCTION__, __( 'Cheatin’ uh?' ), '2.0' );
}
/**
* Load compatibility class
*
* @uses apply_filters()
* @uses get_bloginfo()
* @uses plugin_dir_path()
*
* @return void
* @since 2.0.0
*/
public function load_compatibility() {
// Compatibility load flag (for both deprecated functions and code for compatibility with other plugins)
$load_compatibility = apply_filters( '<API key>', true );
if ( $load_compatibility ) {
include_once( plugin_dir_path( __FILE__ ) . 'includes/class-compatibility.php' );
self::$compatibility = <API key>::instance();
}
}
/**
* Widget initialization
*
* @uses is_blog_installed()
* @uses register_widget()
*
* @return null|void
* @since 2.0.0
*/
public function widgets_init() {
if ( ! is_blog_installed() ) {
return;
}
register_widget( '<API key>' );
}
/**
* Check if a widget is a Black Studio Tinyme Widget instance
*
* @param object $widget
* @return boolean
* @since 2.0.0
*/
public function check_widget( $widget ) {
return 'object' == gettype( $widget ) && ( '<API key>' == get_class( $widget ) || is_subclass_of( $widget , '<API key>' ) );
}
} // END class <API key>
} // END class_exists check
if ( ! function_exists( 'bstw' ) ) {
/**
* Return the main instance to prevent the need to use globals
*
* @return object
* @since 2.0.0
*/
function bstw() {
return <API key>::instance();
}
/* Create the main instance */
bstw();
} // END function_exists bstw check
else {
/* Check for multiple plugin instances */
if ( ! function_exists( '<API key>' ) ) {
/**
* Show admin notice when multiple instances of the plugin are detected
*
* @return void
* @since 2.1.0
*/
function <API key>() {
global $pagenow;
if ( 'widgets.php' == $pagenow ) {
echo '<div class="error">';
/* translators: error message shown when multiple instance of the plugin are detected */
echo '<p>' . esc_html( __( 'ERROR: Multiple instances of the Black Studio TinyMCE Widget plugin were detected. Please activate only one instance at a time.', '<API key>' ) ) . '</p>';
echo '</div>';
}
}
add_action( 'admin_notices', '<API key>' );
} // END function_exists <API key> check
} // END else function_exists bstw check
|
/*global window:false */
/*global document:false */
/*global wp:false */
/*global wpmUi:false */
/*global ace:false */
/**
* Admin Javascript functions for PopUp
*/
jQuery(function init_admin() {
// Disables dragging of metaboxes: Users cannot change the metabox order.
function <API key>() {
var boxes = jQuery( '.meta-box-sortables' ),
handles = jQuery( '.postbox .hndle' );
if ( ! boxes.length ) { return; }
boxes.sortable({
disabled: true
});
handles.css( 'cursor', 'pointer' );
}
// Keeps the submitdiv always visible, even when scrolling.
function scrolling_submitdiv() {
var scroll_top,
top_offset,
submitdiv = jQuery( '#submitdiv' ),
postbody = jQuery( '#post-body' ),
body = jQuery( 'body' ),
padding = 20;
if ( ! submitdiv.length ) { return; }
top_offset = submitdiv.position().top;
var small_make_sticky = function() {
if ( ! body.hasClass( 'sticky-submit' ) ) {
body.addClass( 'sticky-submit' );
submitdiv.css({ 'marginTop': 0 } );
submitdiv.find( '.sticky-actions' ).show();
submitdiv.find( '.non-sticky' ).hide();
}
};
var small_remove_sticky = function() {
if ( body.hasClass( 'sticky-submit' ) ) {
body.removeClass( 'sticky-submit' );
submitdiv.find( '.sticky-actions' ).hide();
submitdiv.find( '.non-sticky' ).show();
}
};
jQuery( window ).resize(function() {
var is_small = jQuery( window ).width() <= 850;
if ( is_small ) {
if ( ! body.hasClass( 'po-small' ) ) {
body.addClass( 'po-small' );
}
} else {
if ( body.hasClass( 'po-small' ) ) {
body.removeClass( 'po-small' );
small_remove_sticky();
}
}
}).scroll(function(){
if ( postbody.hasClass( 'columns-1' ) || body.hasClass( 'po-small' ) ) {
// 1-column view:
// The div stays as sticky toolbar when scrolling down.
scroll_top = jQuery( window ).scrollTop() - top_offset;
if ( scroll_top > 0 ) {
small_make_sticky();
} else {
small_remove_sticky();
}
} else {
// 2-column view:
// The div scrolls with the page to stay visible.
scroll_top = jQuery( window ).scrollTop() - top_offset + padding;
if ( scroll_top > 0 ) {
submitdiv.css({ 'marginTop': scroll_top } );
} else {
submitdiv.css({ 'marginTop': 0 } );
}
}
});
window.setTimeout( function() {
jQuery( window ).trigger( 'scroll' );
}, 100 );
}
// Change the text-fields to colorpicker fields.
function init_colorpicker() {
var inp = jQuery( '.colorpicker' );
if ( ! inp.length || 'function' !== typeof inp.wpColorPicker ) { return; }
var maybe_hide_picker = function maybe_hide_picker( ev ) {
var el = jQuery( ev.target ),
cp = el.closest( '.wp-picker-container' ),
me = cp.find( '.colorpicker' ),
do_hide = jQuery( '.colorpicker' );
if ( cp.length ) {
do_hide = do_hide.not( me );
}
do_hide.each( function() {
var picker = jQuery( this ),
wrap = picker.closest( '.wp-picker-container' );
picker.iris( 'hide' );
// As mentioned: Color picker does not like to hide properly...
picker.hide();
wrap.find( '.wp-picker-clear').addClass( 'hidden' );
wrap.find( '.wp-picker-open').removeClass( 'wp-picker-open' );
});
};
inp.wpColorPicker();
// Don't ask why the handler is hooked three times ;-)
// The Color picker is a bit bitchy when it comes to hiding it...
jQuery( document ).on( 'mousedown', maybe_hide_picker );
jQuery( document ).on( 'click', maybe_hide_picker );
jQuery( document ).on( 'mouseup', maybe_hide_picker );
}
// Add event handlers for editor UI controls (i.e. to checkboxes)
function init_edit_controls() {
var chk_colors = jQuery( '#po-custom-colors' ),
chk_size = jQuery( '#po-custom-size' ),
opt_display = jQuery( '[name=po_display]' ),
chk_can_hide = jQuery( '#po-can-hide' ),
chk_close_hides = jQuery( '#po-close-hides' );
if ( ! chk_colors.length ) { return; }
var toggle_section = function toggle_section() {
var group,
me = jQuery( this ),
sel = me.data( 'toggle' ),
sect = jQuery( sel ),
group_or = me.data( 'or' ),
group_and = me.data( 'and' ),
is_active = false;
if ( group_or ) {
group = jQuery( group_or );
is_active = ( group.filter( ':checked' ).length > 0);
} else if ( group_and ) {
group = jQuery( group_and );
is_active = ( group.length === group.filter( ':checked' ).length );
} else {
is_active = me.prop( 'checked' );
}
if ( is_active ) {
sect.removeClass( 'inactive' );
sect.find( 'input,select,textarea,a' )
.prop( 'readonly', false )
.removeClass( 'disabled' );
} else {
sect.addClass( 'inactive' );
// Do NOT set .prop('disabled', true)!
sect.find( 'input,select,textarea,a' )
.prop( 'readonly', true )
.addClass( 'disabled' );
}
sect.addClass( 'inactive-anim' );
};
var <API key> = function <API key>() {
var me = jQuery( this ),
name = me.attr( 'name' ),
group = jQuery( '[name="' + name + '"]' );
group.each(function() {
toggle_section.call( this );
});
};
var create_sliders = function create_sliders() {
jQuery( '.slider' ).each(function() {
var me = jQuery( this ),
wrap = me.closest( '.slider-wrap' ),
inp_base = me.data( 'input' ),
inp_min = wrap.find( inp_base + 'min' ),
inp_max = wrap.find( inp_base + 'max' ),
min_input = wrap.find( '.slider-min-input' ),
min_ignore = wrap.find( '.slider-min-ignore' ),
max_input = wrap.find( '.slider-max-input' ),
max_ignore = wrap.find( '.slider-max-ignore' ),
min = me.data( 'min' ),
max = me.data( 'max' );
if ( isNaN( min ) ) { min = 0; }
if ( isNaN( max ) ) { max = 9999; }
inp_min.prop( 'readonly', true );
inp_max.prop( 'readonly', true );
var update_fields = function update_fields( val1, val2 ) {
inp_min.val( val1 );
inp_max.val( val2 );
if ( val1 === min ) {
min_input.hide();
min_ignore.show();
} else {
min_input.show();
min_ignore.hide();
}
if ( val2 === max ) {
max_input.hide();
max_ignore.show();
} else {
max_input.show();
max_ignore.hide();
}
};
me.slider({
range: true,
min: min,
max: max,
values: [ inp_min.val(), inp_max.val() ],
slide: function( event, ui ) {
update_fields( ui.values[0], ui.values[1] );
}
});
update_fields( inp_min.val(), inp_max.val() );
});
};
chk_colors.click( toggle_section );
chk_size.click( toggle_section );
chk_can_hide.click( toggle_section );
chk_close_hides.click( toggle_section );
opt_display.click( <API key> );
toggle_section.call( chk_colors );
toggle_section.call( chk_size );
toggle_section.call( chk_can_hide );
toggle_section.call( chk_close_hides );
opt_display.each(function() {
toggle_section.call( jQuery( this ) );
});
create_sliders();
}
// Toggle rules on/off
function init_rules() {
var all_rules = jQuery( '#meta-rules .all-rules' ),
active_rules = jQuery( '#meta-rules .active-rules' );
if ( ! all_rules.length ) { return; }
var toggle_checkbox = function toggle_checkbox( ev ) {
var me = jQuery( ev.target ),
chk = me.find( 'input.<API key>' );
if ( me.closest( '.wpmui-toggle' ).length ) { return; }
if ( me.hasClass( 'inactive' ) ) { return false; }
chk.trigger( 'click' );
};
var toggle_rule = function toggle_rule() {
var me = jQuery( this ),
rule = me.closest( '.rule' ),
sel = me.data( 'form' ),
form = active_rules.find( sel ),
active = me.prop( 'checked' );
if ( active ) {
rule.removeClass( 'off' ).addClass( 'on' );
form.removeClass( 'off' ).addClass( 'on open' );
} else {
rule.removeClass( 'on' ).addClass( 'off' );
form.removeClass( 'on' ).addClass( 'off' );
}
exclude_rules( me, active );
};
var exclude_rules = function exclude_rules( checkbox, active ) {
var ind, excl1, excl2,
excl = checkbox.data( 'exclude' ),
keys = (excl ? excl.split( ',' ) : []);
// Exclude other rules.
for ( ind = keys.length - 1; ind >= 0; ind -= 1 ) {
excl1 = all_rules.find( '.rule-' + keys[ ind ] );
excl2 = active_rules.find( '#po-rule-' + keys[ ind ] );
if ( excl1.hasClass( 'on' ) ) {
// Rule is active; possibly migrated from old PopUp editor
// so we cannot disable the rule now...
continue;
}
excl1.prop( 'disabled', active );
if ( active ) {
excl1.addClass( 'inactive off' ).removeClass( 'on' );
excl2.addClass( 'off' ).removeClass( 'on' );
} else {
excl1.removeClass( 'inactive off' );
}
}
};
var toggle_form = function toggle_form() {
var me = jQuery( this ),
form = me.closest( '.rule' );
form.toggleClass( 'open' );
};
all_rules.find( 'input.<API key>' ).click( toggle_rule );
all_rules.find( '.rule' ).click( toggle_checkbox );
active_rules.on( 'click', '.rule-title,.rule-toggle', toggle_form );
// Exclude rules.
all_rules.find( '.rule.on input.<API key>' ).each(function() {
exclude_rules( jQuery( this ), true );
});
jQuery( '.init-loading' ).removeClass( 'wpmui-loading' );
}
// Hook up the "Featured image" button.
function init_image() {
// Uploading files
var box = jQuery( '.content-image' ),
btn = box.find( '.add_image' ),
dropzone = box.find( '.featured-img' ),
reset = box.find( '.reset' ),
inp = box.find( '.po-image' ),
img_preview = box.find( '.img-preview' ),
img_label = box.find( '.lbl-empty' ),
img_pos = box.find( '.img-pos' ),
file_frame;
// User selected an image (via drag-drop or file_frame)
var use_image = function use_image( url ) {
inp.val( url );
img_preview.attr( 'src', url ).show();
img_label.hide();
img_pos.show();
dropzone.addClass( 'has-image' );
};
// User selected an image (via drag-drop or file_frame)
var reset_image = function reset_image( url ) {
inp.val( '' );
img_preview.attr( 'src', '' ).hide();
img_label.show();
img_pos.hide();
dropzone.removeClass( 'has-image' );
};
// User clicks on the "Add image" button.
var select_clicked = function select_clicked( ev ) {
ev.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
file_frame.open();
return;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: btn.attr( 'data-title' ),
button: {
text: btn.attr( 'data-button' )
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
// We set multiple to false so only get one image from the uploader
var attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
use_image( attachment.url );
});
// Finally, open the modal
file_frame.open();
};
var select_pos = function select_pos( ev ) {
var me = jQuery( this );
img_pos.find( '.option' ).removeClass( 'selected' );
me.addClass( 'selected' );
};
btn.on( 'click', select_clicked );
reset.on( 'click', reset_image );
img_pos.on( 'click', '.option', select_pos );
}
// Adds custom bulk actions to the popup list.
function bulk_actions() {
var key,
ba1 = jQuery( 'select[name="action"] '),
ba2 = jQuery( 'select[name="action2"] ');
if ( ! ba1.length || 'object' !== typeof window.po_bulk ) { return; }
for ( key in window.po_bulk ) {
jQuery( '<option>' )
.val( key )
.text( window.po_bulk[key] )
.appendTo( ba1 )
.clone()
.appendTo( ba2 );
}
}
// Makes the post-list sortable (to change popup-order)
function sortable_list() {
var table = jQuery( 'table.posts' ),
tbody = table.find( '#the-list' );
if ( ! tbody.length ) { return; }
var ajax_done = function ajax_done( resp, okay ) {
table.removeClass( 'wpmui-loading' );
if ( okay ) {
for ( var id in resp ) {
if ( ! resp.hasOwnProperty( id ) ) { continue; }
tbody.find( '#post-' + id + ' .the-pos' ).text( resp[id] );
}
}
};
var save_order = function save_order( event, ui ) {
var i,
rows = tbody.find('tr'),
order = [];
for ( i = 0; i < rows.length; i+= 1 ) {
order.push( jQuery( rows[i] ).attr( 'id' ) );
}
table.addClass( 'wpmui-loading' );
wpmUi.ajax( null, 'po-ajax' )
.data({
'do': 'order',
'order': order
})
.ondone( ajax_done )
.load_json();
};
tbody.sortable({
placeholder: '<API key>',
axis: 'y',
handle: '.column-po_order',
helper: 'clone',
opacity: 0.75,
update: save_order
});
tbody.disableSelection();
}
// Shows a preview of the current PopUp.
function init_preview() {
var doc = jQuery( document ),
body = jQuery( '#wpcontent' );
var handle_list_click = function handle_list_click( ev ) {
var me = jQuery( this ),
po_id = me.data( 'id' );
ev.preventDefault();
if ( undefined === window.inc_popup ) { return false; }
body.addClass( 'wpmui-loading' );
window.inc_popup.load( po_id );
return false;
};
var handle_editor_click = function handle_editor_click( ev ) {
var data,
me = jQuery( this ),
form = jQuery( '#post' ),
ajax = wpmUi.ajax();
ev.preventDefault();
if ( undefined === window.inc_popup ) { return false; }
data = ajax.extract_data( form );
body.addClass( 'wpmui-loading' );
window.inc_popup.load( 0, data );
return false;
};
var show_popup = function show_popup( ev, popup ) {
body.removeClass( 'wpmui-loading' );
popup.init();
};
doc.on( 'click', '.posts .po-preview', handle_list_click );
doc.on( 'click', '#post .preview', handle_editor_click );
doc.on( 'popup-initialized', show_popup );
}
// Initialize the CSS editor
function init_css_editor() {
jQuery('.po_css_editor').each(function(){
var editor = ace.edit(this.id);
jQuery(this).data('editor', editor);
editor.setTheme('ace/theme/chrome');
editor.getSession().setMode('ace/mode/css');
editor.getSession().setUseWrapMode(true);
editor.getSession().setUseWrapMode(false);
});
jQuery('.po_css_editor').each(function(){
var self = this,
input = jQuery( jQuery(this).data('input') );
jQuery(this).data('editor').getSession().on('change', function () {
input.val( jQuery(self).data('editor').getSession().getValue() );
});
});
}
if ( ! jQuery( 'body.post-type-inc_popup' ).length ) {
return;
}
// EDITOR
if ( jQuery( 'body.post-php' ).length || jQuery( 'body.post-new-php' ).length ) {
<API key>();
scrolling_submitdiv();
init_colorpicker();
init_edit_controls();
init_rules();
init_preview();
init_image();
init_css_editor();
wpmUi.upgrade_multiselect();
}
// POPUP LIST
else if ( jQuery( 'body.edit-php' ).length ) {
sortable_list();
bulk_actions();
init_preview();
}
});
|
goog.provide('ol.source.ImageVector');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.vec.Mat4');
goog.require('ol.dom');
goog.require('ol.extent');
goog.require('ol.render.canvas.ReplayGroup');
goog.require('ol.renderer.vector');
goog.require('ol.source.ImageCanvas');
goog.require('ol.source.Vector');
goog.require('ol.style.Style');
goog.require('ol.vec.Mat4');
/**
* @classdesc
* An image source whose images are canvas elements into which vector features
* read from a vector source (`ol.source.Vector`) are drawn. An
* `ol.source.ImageVector` object is to be used as the `source` of an image
* layer (`ol.layer.Image`). Image layers are rotated, scaled, and translated,
* as opposed to being re-rendered, during animations and interactions. So, like
* any other image layer, an image layer configured with an
* `ol.source.ImageVector` will exhibit this behaviour. This is in contrast to a
* vector layer, where vector features are re-drawn during animations and
* interactions.
*
* @constructor
* @extends {ol.source.ImageCanvas}
* @param {olx.source.ImageVectorOptions} options Options.
* @api
*/
ol.source.ImageVector = function(options) {
/**
* @private
* @type {ol.source.Vector}
*/
this.source_ = options.source;
/**
* @private
* @type {!goog.vec.Mat4.Number}
*/
this.transform_ = goog.vec.Mat4.createNumber();
/**
* @private
* @type {<API key>}
*/
this.canvasContext_ = ol.dom.<API key>();
/**
* @private
* @type {ol.Size}
*/
this.canvasSize_ = [0, 0];
/**
* @private
* @type {ol.render.canvas.ReplayGroup}
*/
this.replayGroup_ = null;
goog.base(this, {
attributions: options.attributions,
canvasFunction: goog.bind(this.<API key>, this),
logo: options.logo,
projection: options.projection,
ratio: options.ratio,
resolutions: options.resolutions,
state: this.source_.getState()
});
/**
* User provided style.
* @type {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction}
* @private
*/
this.style_ = null;
/**
* Style function for use within the library.
* @type {ol.style.StyleFunction|undefined}
* @private
*/
this.styleFunction_ = undefined;
this.setStyle(options.style);
goog.events.listen(this.source_, goog.events.EventType.CHANGE,
this.handleSourceChange_, undefined, this);
};
goog.inherits(ol.source.ImageVector, ol.source.ImageCanvas);
/**
* @param {ol.Extent} extent Extent.
* @param {number} resolution Resolution.
* @param {number} pixelRatio Pixel ratio.
* @param {ol.Size} size Size.
* @param {ol.proj.Projection} projection Projection;
* @return {HTMLCanvasElement} Canvas element.
* @private
*/
ol.source.ImageVector.prototype.<API key> =
function(extent, resolution, pixelRatio, size, projection) {
var replayGroup = new ol.render.canvas.ReplayGroup(
ol.renderer.vector.getTolerance(resolution, pixelRatio), extent,
resolution);
this.source_.loadFeatures(extent, resolution, projection);
var loading = false;
this.source_.<API key>(extent, resolution,
/**
* @param {ol.Feature} feature Feature.
*/
function(feature) {
loading = loading ||
this.renderFeature_(feature, resolution, pixelRatio, replayGroup);
}, this);
replayGroup.finish();
if (loading) {
return null;
}
if (this.canvasSize_[0] != size[0] || this.canvasSize_[1] != size[1]) {
this.canvasContext_.canvas.width = size[0];
this.canvasContext_.canvas.height = size[1];
this.canvasSize_[0] = size[0];
this.canvasSize_[1] = size[1];
} else {
this.canvasContext_.clearRect(0, 0, size[0], size[1]);
}
var transform = this.getTransform_(ol.extent.getCenter(extent),
resolution, pixelRatio, size);
replayGroup.replay(this.canvasContext_, pixelRatio, transform, 0, {});
this.replayGroup_ = replayGroup;
return this.canvasContext_.canvas;
};
/**
* @inheritDoc
*/
ol.source.ImageVector.prototype.<API key> = function(
coordinate, resolution, rotation, skippedFeatureUids, callback) {
if (goog.isNull(this.replayGroup_)) {
return undefined;
} else {
/** @type {Object.<string, boolean>} */
var features = {};
return this.replayGroup_.<API key>(
coordinate, resolution, 0, skippedFeatureUids,
/**
* @param {ol.Feature} feature Feature.
* @return {?} Callback result.
*/
function(feature) {
goog.asserts.assert(goog.isDef(feature));
var key = goog.getUid(feature).toString();
if (!(key in features)) {
features[key] = true;
return callback(feature);
}
});
}
};
/**
* Get a reference to the wrapped source.
* @return {ol.source.Vector} Source.
* @api
*/
ol.source.ImageVector.prototype.getSource = function() {
return this.source_;
};
/**
* Get the style for features. This returns whatever was passed to the `style`
* option at construction or to the `setStyle` method.
* @return {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction}
* Layer style.
* @api stable
*/
ol.source.ImageVector.prototype.getStyle = function() {
return this.style_;
};
/**
* Get the style function.
* @return {ol.style.StyleFunction|undefined} Layer style function.
* @api stable
*/
ol.source.ImageVector.prototype.getStyleFunction = function() {
return this.styleFunction_;
};
/**
* @param {ol.Coordinate} center Center.
* @param {number} resolution Resolution.
* @param {number} pixelRatio Pixel ratio.
* @param {ol.Size} size Size.
* @return {!goog.vec.Mat4.Number} Transform.
* @private
*/
ol.source.ImageVector.prototype.getTransform_ =
function(center, resolution, pixelRatio, size) {
return ol.vec.Mat4.makeTransform2D(this.transform_,
size[0] / 2, size[1] / 2,
pixelRatio / resolution, -pixelRatio / resolution,
0,
-center[0], -center[1]);
};
/**
* Handle changes in image style state.
* @param {goog.events.Event} event Image style change event.
* @private
*/
ol.source.ImageVector.prototype.handleImageChange_ =
function(event) {
this.changed();
};
/**
* @private
*/
ol.source.ImageVector.prototype.handleSourceChange_ = function() {
// setState will trigger a CHANGE event, so we always rely
// change events by calling setState.
this.setState(this.source_.getState());
};
/**
* @param {ol.Feature} feature Feature.
* @param {number} resolution Resolution.
* @param {number} pixelRatio Pixel ratio.
* @param {ol.render.canvas.ReplayGroup} replayGroup Replay group.
* @return {boolean} `true` if an image is loading.
* @private
*/
ol.source.ImageVector.prototype.renderFeature_ =
function(feature, resolution, pixelRatio, replayGroup) {
var styles;
if (goog.isDef(feature.getStyleFunction())) {
styles = feature.getStyleFunction().call(feature, resolution);
} else if (goog.isDef(this.styleFunction_)) {
styles = this.styleFunction_(feature, resolution);
}
if (!goog.isDefAndNotNull(styles)) {
return false;
}
var i, ii, loading = false;
for (i = 0, ii = styles.length; i < ii; ++i) {
loading = ol.renderer.vector.renderFeature(
replayGroup, feature, styles[i],
ol.renderer.vector.getSquaredTolerance(resolution, pixelRatio),
this.handleImageChange_, this) || loading;
}
return loading;
};
/**
* Set the style for features. This can be a single style object, an array
* of styles, or a function that takes a feature and resolution and returns
* an array of styles. If it is `undefined` the default style is used. If
* it is `null` the layer has no style (a `null` style), so only features
* that have their own styles will be rendered in the layer. See
* {@link ol.style} for information on the default style.
* @param {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction|undefined}
* style Layer style.
* @api stable
*/
ol.source.ImageVector.prototype.setStyle = function(style) {
this.style_ = goog.isDef(style) ? style : ol.style.<API key>;
this.styleFunction_ = goog.isNull(style) ?
undefined : ol.style.createStyleFunction(this.style_);
this.changed();
};
|
package manuylov.maxim.ocaml.lang.parser.psi.element.impl;
import com.intellij.lang.ASTNode;
import manuylov.maxim.ocaml.lang.parser.psi.OCamlElementVisitor;
import manuylov.maxim.ocaml.lang.parser.psi.element.<API key>;
import org.jetbrains.annotations.NotNull;
public class <API key> extends <API key> implements <API key> {
public <API key>(@NotNull final ASTNode node) {
super(node);
}
public void visit(@NotNull final OCamlElementVisitor visitor) {
visitor.<API key>(this);
}
}
|
#define FTDI_VID 0x0403 /* Vendor Id */
/*** "original" FTDI device PIDs ***/
#define FTDI_8U232AM_PID 0x6001 /* Similar device to SIO above */
#define <API key> 0x6006 /* FTDI's alternate PID for above */
#define FTDI_8U2232C_PID 0x6010 /* Dual channel device */
#define FTDI_4232H_PID 0x6011 /* Quad channel hi-speed device */
#define FTDI_SIO_PID 0x8372 /* Product Id SIO application of 8U100AX */
#define FTDI_232RL_PID 0xFBFA /* Product ID for FT232RL */
/*** third-party PIDs (using FTDI_VID) ***/
#define MARVELL_OPENRD_PID 0x9e90
#define FTDI_CANDAPTER_PID 0x9F80 /* Product Id */
#define FTDI_NXTCAM_PID 0xABB8 /* NXTCam for Mindstorms NXT */
#define FTDI_USINT_CAT_PID 0xb810 /* Navigator CAT and 2nd PTT lines */
#define FTDI_USINT_WKEY_PID 0xb811 /* Navigator WKEY and FSK lines */
#define <API key> 0xb812 /* Navigator RS232 and CONFIG lines */
#define FTDI_OOCDLINK_PID 0xbaf8 /* Amontec JTAGkey */
/* Luminary Micro Stellaris Boards, VID = FTDI_VID */
/* FTDI 2332C Dual channel device, side A=245 FIFO (JTAG), Side B=RS232 UART */
#define <API key> 0xbcd8
#define <API key> 0xbcd9
#define FTDI_TURTELIZER_PID 0xBDC8 /* JTAG/RS-232 adapter by egnite GmbH */
#define FTDI_OPENDCC_PID 0xBFD8
#define <API key> 0xBFD9
#define <API key> 0xBFDA
#define <API key> 0xBFDB
#define <API key> 0xc7d0 /* LocoBuffer USB */
/* DMX4ALL DMX Interfaces */
#define FTDI_DMX4ALL 0xC850
/*
* ASK.fr devices
*/
#define FTDI_ASK_RDR400_PID 0xC991 /* ASK RDR 400 series card reader */
#define <API key> 0xCAA0 /* Product Id */
/*
* Tactrix OpenPort (ECU) devices.
* OpenPort 1.3M submitted by Donour Sizemore.
* OpenPort 1.3S and 1.3U submitted by Ian Abbott.
*/
#define <API key> 0xCC48 /* OpenPort 1.3 Mitsubishi */
#define <API key> 0xCC49 /* OpenPort 1.3 Subaru */
#define <API key> 0xCC4A /* OpenPort 1.3 Universal */
/* the VID is the standard ftdi vid (FTDI_VID) */
#define <API key> 0xD010 /* SCS PTC-IIusb */
#define <API key> 0xD011 /* SCS Tracker / DSP TNC */
#define <API key> 0xD012
#define <API key> 0xD013
#define <API key> 0xD014
#define <API key> 0xD015
#define <API key> 0xD016
#define <API key> 0xD017
/* iPlus device */
#define FTDI_IPLUS_PID 0xD070 /* Product Id */
#define FTDI_IPLUS2_PID 0xD071 /* Product Id */
#define <API key> 0xD678 /* Gamma Scout online */
/* Propox devices */
#define <API key> 0xD738
/* Lenz LI-USB Computer Interface. */
#define FTDI_LENZ_LIUSB_PID 0xD780
#define <API key> 0xD388
#define <API key> 0xD389
#define <API key> 0xD38A
#define <API key> 0xD38B
#define <API key> 0xD38C
#define <API key> 0xD38D
#define <API key> 0xD38E
#define <API key> 0xD38F
#define FTDI_NDI_HUC_PID 0xDA70 /* NDI Host USB Converter */
#define <API key> 0xDA71 /* NDI Spectra SCU */
#define <API key> 0xDA72 /* NDI future device #2 */
#define <API key> 0xDA73 /* NDI future device #3 */
#define <API key> 0xDA74 /* NDI Aurora SCU */
#define <API key> 0xDAF8
#define <API key> 0xDAF9
#define <API key> 0xDAFA
#define <API key> 0xDAFB
#define <API key> 0xDAFC
#define <API key> 0xDAFD
#define <API key> 0xDAFE
#define <API key> 0xDAFF
/*
* Westrex International devices submitted by Cory Lee
*/
#define <API key> 0xDC00 /* Model 777 */
#define <API key> 0xDC01 /* Model 8900F */
#define FTDI_ACG_HFDUAL_PID 0xDD20 /* HF Dual ISO Reader (RFID) */
#define FTDI_ARTEMIS_PID 0xDF28 /* All Artemis Cameras */
#define FTDI_ATIK_ATK16_PID 0xDF30 /* ATIK ATK-16 Grayscale Camera */
#define <API key> 0xDF32 /* ATIK ATK-16C Colour Camera */
#define <API key> 0xDF31 /* ATIK ATK-16HR Grayscale Camera */
#define <API key> 0xDF33 /* ATIK ATK-16HRC Colour Camera */
#define <API key> 0xDF35 /* ATIK ATK-16IC Grayscale Camera */
#define <API key> 0xE050 /* YEI ServoCenter3.1 USB */
#define FTDI_ELV_USR_PID 0xE000 /* ELV <API key> */
#define FTDI_ELV_MSM1_PID 0xE001 /* ELV Mini-Sound-Modul */
#define FTDI_ELV_KL100_PID 0xE002 /* ELV Kfz-Leistungsmesser KL 100 */
#define FTDI_ELV_WS550_PID 0xE004 /* WS 550 */
#define FTDI_ELV_EC3000_PID 0xE006 /* ENERGY CONTROL 3000 USB */
#define FTDI_ELV_WS888_PID 0xE008 /* WS 888 */
#define FTDI_ELV_TWS550_PID 0xE009 /* Technoline WS 550 */
#define FTDI_ELV_FEM_PID 0xE00A /* Funk Energie Monitor */
#define <API key> 0xE0E8 /* FHZ 1300 PC */
#define FTDI_ELV_WS500_PID 0xE0E9 /* PC-Wetterstation (WS 500) */
#define FTDI_ELV_HS485_PID 0xE0EA /* USB to RS-485 adapter */
#define FTDI_ELV_UMS100_PID 0xE0EB /* ELV USB Master-Slave Schaltsteckdose UMS 100 */
#define FTDI_ELV_TFD128_PID 0xE0EC /* ELV <API key> TFD 128 */
#define FTDI_ELV_FM3RX_PID 0xE0ED /* ELV <API key> FM3 RX */
#define FTDI_ELV_WS777_PID 0xE0EE /* Conrad WS 777 */
#define <API key> 0xE0EF /* Energy monitor EM 1010 PC */
#define FTDI_ELV_CSI8_PID 0xE0F0 /* <API key> (CSI 8) */
#define <API key> 0xE0F1 /* PC-Datenlogger fuer Energiemonitor (EM 1000 DL) */
#define FTDI_ELV_PCK100_PID 0xE0F2 /* PC-Kabeltester (PCK 100) */
#define FTDI_ELV_RFP500_PID 0xE0F3 /* HF-Leistungsmesser (RFP 500) */
#define <API key> 0xE0F4 /* Signalgeber (FS 20 SIG) */
#define FTDI_ELV_UTP8_PID 0xE0F5 /* ELV UTP 8 */
#define <API key> 0xE0F6 /* PC-Wetterstation (WS 300 PC) */
#define <API key> 0xE0F7 /* Conrad WS 444 PC */
#define FTDI_PHI_FISCO_PID 0xE40B /* PHI Fisco USB to Serial cable */
#define FTDI_ELV_UAD8_PID 0xF068 /* USB-AD-Wandler (UAD 8) */
#define FTDI_ELV_UDA7_PID 0xF069 /* USB-DA-Wandler (UDA 7) */
#define FTDI_ELV_USI2_PID 0xF06A /* <API key> (USI 2) */
#define FTDI_ELV_T1100_PID 0xF06B /* Thermometer (T 1100) */
#define FTDI_ELV_PCD200_PID 0xF06C /* PC-Datenlogger (PCD 200) */
#define FTDI_ELV_ULA200_PID 0xF06D /* USB-LCD-Ansteuerung (ULA 200) */
#define <API key> 0xF06E /* ALC 8500 Expert */
#define <API key> 0xF06F /* FHZ 1000 PC */
#define FTDI_ELV_UR100_PID 0xFB58 /* USB-RS232-Umsetzer (UR 100) */
#define FTDI_ELV_UM100_PID 0xFB5A /* USB-Modul UM 100 */
#define FTDI_ELV_UO100_PID 0xFB5B /* USB-Modul UO 100 */
/* Additional ELV PIDs that default to using the FTDI D2XX drivers on
* MS Windows, rather than the FTDI Virtual Com Port drivers.
* Maybe these will be easier to use with the libftdi/libusb user-space
* drivers, or possibly the Comedi drivers in some cases. */
#define <API key> 0xFB59 /* <API key> (CLI 7000) */
#define <API key> 0xFB5C /* <API key> (PPS 7330) */
#define FTDI_ELV_TFM100_PID 0xFB5D /* <API key> (TFM 100) */
#define FTDI_ELV_UDF77_PID 0xFB5E /* USB DCF Funkuhr (UDF 77) */
#define FTDI_ELV_UIO88_PID 0xFB5F /* USB-I/O Interface (UIO 88) */
#define EVER_ECO_PRO_CDS 0xe520 /* RS-232 converter */
/*
* Active Robots product ids.
*/
#define <API key> 0xE548 /* USB comms board */
/* Pyramid Computer GmbH */
#define FTDI_PYRAMID_PID 0xE6C8 /* Pyramid Appliance Display */
#define <API key> 0xE700 /* Product Id */
/*
* Gude Analog- und Digitalsysteme GmbH
*/
#define <API key> 0xE808
#define <API key> 0xE809
#define <API key> 0xE80A
#define <API key> 0xE80B
#define <API key> 0xE80C
#define <API key> 0xE80D
#define <API key> 0xE80E
#define <API key> 0xE80F
#define <API key> 0xE888 /* Expert ISDN Control USB */
#define <API key> 0xE889 /* USB RS-232 OptoBridge */
#define <API key> 0xE88A
#define <API key> 0xE88B
#define <API key> 0xE88C
#define <API key> 0xE88D
#define <API key> 0xE88E
#define <API key> 0xE88F
#define <API key> 0xEA90 /* COM to 1-Wire USB adaptor */
/* TNC-X USB-to-packet-radio adapter, versions prior to 3.0 (DLP module) */
#define FTDI_TNC_X_PID 0xEBE0
#define <API key> 0xEC88 /* Teratronik device (preferring VCP driver on windows) */
#define <API key> 0xEC89 /* Teratronik device (preferring D2XX driver on windows) */
/* Rig Expert Ukraine devices */
#define FTDI_REU_TINY_PID 0xED22 /* RigExpert Tiny */
/*
* Hameg HO820 and HO870 interface (using VID 0x0403)
*/
#define HAMEG_HO820_PID 0xed74
#define HAMEG_HO730_PID 0xed73
#define HAMEG_HO720_PID 0xed72
#define HAMEG_HO870_PID 0xed71
#define FTDI_MAXSTREAM_PID 0xEE18 /* Xbee PKG-U Module */
#define FTDI_MHAM_KW_PID 0xEEE8 /* USB-KW interface */
#define FTDI_MHAM_YS_PID 0xEEE9 /* USB-YS interface */
#define FTDI_MHAM_Y6_PID 0xEEEA /* USB-Y6 interface */
#define FTDI_MHAM_Y8_PID 0xEEEB /* USB-Y8 interface */
#define FTDI_MHAM_IC_PID 0xEEEC /* USB-IC interface */
#define FTDI_MHAM_DB9_PID 0xEEED /* USB-DB9 interface */
#define FTDI_MHAM_RS232_PID 0xEEEE /* USB-RS232 interface */
#define FTDI_MHAM_Y9_PID 0xEEEF /* USB-Y9 interface */
#define <API key> 0xEF50 /* Master */
#define <API key> 0xEF51 /* DUSB01 module */
/*
* The following are the values for the Perle Systems
* UltraPort USB serial converters
*/
#define <API key> 0xF0C0 /* Perle UltraPort Product Id */
/* Sprog II (Andrew Crosland's SprogII DCC interface) */
#define FTDI_SPROG_II 0xF0C8
/* an infrared receiver for user access control with IR tags */
#define FTDI_PIEGROUP_PID 0xF208 /* Product Id */
#define FTDI_ACTZWAVE_PID 0xF2D0
/*
* 4N-GALAXY.DE PIDs for CAN-USB, USB-RS232, USB-RS422, USB-RS485,
* USB-TTY aktiv, USB-TTY passiv. Some PIDs are used by several devices
* and I'm not entirely sure which are used by which.
*/
#define <API key> 0xF3C0
#define <API key> 0xF3C1
/*
* Linx Technologies product ids
*/
#define LINX_SDMUSBQSS_PID 0xF448 /* Linx SDM-USB-QS-S */
#define <API key> 0xF449 /* Linx Master Development 2.0 */
#define LINX_FUTURE_0_PID 0xF44A /* Linx future device */
#define LINX_FUTURE_1_PID 0xF44B /* Linx future device */
#define LINX_FUTURE_2_PID 0xF44C /* Linx future device */
/*
* Oceanic product ids
*/
#define FTDI_OCEANIC_PID 0xF460 /* Oceanic dive instrument */
/*
* SUUNTO product ids
*/
#define <API key> 0xF680 /* Suunto Sports instrument */
/* USB-UIRT - An infrared receiver and transmitter using the 8U232AM chip */
#define FTDI_USB_UIRT_PID 0xF850 /* Product Id */
/* CCS Inc. ICDU/ICDU40 product ID -
* the FT232BM is used in an in-circuit-debugger unit for PIC16's/PIC18's */
#define <API key> 0xF9D0
#define <API key> 0xF9D1
#define FTDI_CCSMACHX_2_PID 0xF9D2
#define <API key> 0xF9D3
#define <API key> 0xF9D4
#define <API key> 0xF9D5
/*
* The following are the values for the Matrix Orbital LCD displays,
* which are the FT232BM ( similar to the 8U232AM )
*/
#define FTDI_MTXORB_0_PID 0xFA00 /* Matrix Orbital Product Id */
#define FTDI_MTXORB_1_PID 0xFA01 /* Matrix Orbital Product Id */
#define FTDI_MTXORB_2_PID 0xFA02 /* Matrix Orbital Product Id */
#define FTDI_MTXORB_3_PID 0xFA03 /* Matrix Orbital Product Id */
#define FTDI_MTXORB_4_PID 0xFA04 /* Matrix Orbital Product Id */
#define FTDI_MTXORB_5_PID 0xFA05 /* Matrix Orbital Product Id */
#define FTDI_MTXORB_6_PID 0xFA06 /* Matrix Orbital Product Id */
#define FTDI_HE_TIRA1_PID 0xFA78 /* Tira-1 IR transceiver */
#define INSIDE_ACCESSO 0xFAD0
/*
* ThorLabs USB motor drivers
*/
#define FTDI_THORLABS_PID 0xfaf0 /* ThorLabs USB motor drivers */
/*
* Protego product ids
*/
#define PROTEGO_SPECIAL_1 0xFC70 /* special/unknown device */
#define PROTEGO_R2X0 0xFC71 /* R200-USB TRNG unit (R210, R220, and R230) */
#define PROTEGO_SPECIAL_3 0xFC72 /* special/unknown device */
#define PROTEGO_SPECIAL_4 0xFC73 /* special/unknown device */
/*
* DSS-20 Sync Station for Sony Ericsson P800
*/
#define FTDI_DSS20_PID 0xFC82
#define FTDI_IRTRANS_PID 0xFC60 /* Product Id */
#define FTDI_RM_CANVIEW_PID 0xfd60 /* Product Id */
#define FTDI_TTUSB_PID 0xFF20 /* Product Id */
#define FTDI_USBX_707_PID 0xF857 /* ADSTech IR Blaster USBX-707 (FTDI_VID) */
#define FTDI_RELAIS_PID 0xFA10 /* Relais device from Rudolf Gugler */
#define FTDI_PCDJ_DAC2_PID 0xFA88
#define <API key> 0xFB80 /* R2000KU TRUE RNG (FTDI_VID) */
/*
* DIEBOLD BCS SE923 (FTDI_VID)
*/
#define <API key> 0xfb99
#define FTDI_XF_632_PID 0xFC08 /* 632: 16x2 Character Display */
#define FTDI_XF_634_PID 0xFC09 /* 634: 20x4 Character Display */
#define FTDI_XF_547_PID 0xFC0A /* 547: Two line Display */
#define FTDI_XF_633_PID 0xFC0B /* 633: 16x2 Character Display with Keys */
#define FTDI_XF_631_PID 0xFC0C /* 631: 20x2 Character Display */
#define FTDI_XF_635_PID 0xFC0D /* 635: 20x4 Character Display */
#define FTDI_XF_640_PID 0xFC0E /* 640: Two line Display */
#define FTDI_XF_642_PID 0xFC0F /* 642: Two line Display */
/*
* Video Networks Limited / Homechoice in the UK use an ftdi-based device
* for their 1Mb broadband internet service. The following PID is exhibited
* by the usb device supplied (the VID is the standard ftdi vid (FTDI_VID)
*/
#define <API key> 0xfe38 /* Product Id */
/* AlphaMicro Components AMC-232USB01 device (FTDI_VID) */
#define FTDI_AMC232_PID 0xFF00 /* Product Id */
/*
* IBS elektronik product ids (FTDI_VID)
* Submitted by Thomas Schleusener
*/
#define FTDI_IBS_US485_PID 0xff38 /* IBS US485 (USB<-->RS422/485 interface) */
#define FTDI_IBS_PICPRO_PID 0xff39 /* IBS PIC-Programmer */
#define FTDI_IBS_PCMCIA_PID 0xff3a /* IBS Card reader for PCMCIA SRAM-cards */
#define FTDI_IBS_PK1_PID 0xff3b /* IBS PK1 - Particel counter */
#define <API key> 0xff3c /* IBS RS232 - Monitor */
#define FTDI_IBS_APP70_PID 0xff3d /* APP 70 (dust monitoring system) */
#define FTDI_IBS_PEDO_PID 0xff3e /* IBS PEDO-Modem (RF modem 868.35 MHz) */
#define FTDI_IBS_PROD_PID 0xff3f /* future device */
#define FTDI_CANUSB_PID 0xFFA8 /* Product Id */
/** third-party VID/PID combos **/
/*
* Atmel STK541
*/
#define ATMEL_VID 0x03eb /* Vendor ID */
#define STK541_PID 0x2109 /* Zigbee Controller */
#define ADI_VID 0x0456
#define ADI_GNICE_PID 0xF000
#define ADI_GNICEPLUS_PID 0xF001
/*
* RATOC REX-USB60F
*/
#define RATOC_VENDOR_ID 0x0584
#define <API key> 0xb020
/*
* Acton Research Corp.
*/
#define ACTON_VID 0x0647 /* Vendor ID */
#define <API key> 0x0100
#define CONTEC_VID 0x06CE /* Vendor ID */
#define CONTEC_COM1USBH_PID 0x8311 /* COM-1(USB)H */
/*
* Definitions for B&B Electronics products.
*/
#define BANDB_VID 0x0856 /* B&B Electronics Vendor ID */
#define BANDB_USOTL4_PID 0xAC01 /* USOTL4 Isolated RS-485 Converter */
#define BANDB_USTL4_PID 0xAC02 /* USTL4 RS-485 Converter */
#define BANDB_USO9ML2_PID 0xAC03 /* USO9ML2 Isolated RS-232 Converter */
#define BANDB_USOPTL4_PID 0xAC11
#define BANDB_USPTL4_PID 0xAC12
#define <API key> 0xAC16
#define BANDB_USO9ML2DR_PID 0xAC17
#define <API key> 0xAC18 /* USOPTL4R-2 2-port Isolated RS-232 Converter */
#define BANDB_USOPTL4DR_PID 0xAC19
#define <API key> 0xAC25
#define <API key> 0xAC26
#define BANDB_232USB9M_PID 0xAC27
#define <API key> 0xAC33
#define <API key> 0xAC34
#define BANDB_TTL5USB9M_PID 0xAC49
#define BANDB_TTL3USB9M_PID 0xAC50
#define <API key> 0xBA02
#define INTREPID_VID 0x093C
#define <API key> 0x0601
#define INTREPID_NEOVI_PID 0x0701
#define IDTECH_VID 0x0ACD /* ID TECH Vendor ID */
#define IDTECH_IDT1221U_PID 0x0300 /* IDT1221U USB to RS-232 adapter */
/*
* Definitions for Omnidirectional Control Technology, Inc. devices
*/
#define OCT_VID 0x0B39 /* OCT vendor ID */
/* Note: OCT US101 is also rebadged as Dick Smith Electronics (NZ) XH6381 */
/* Also rebadged as Dick Smith Electronics (Aus) XH6451 */
/* Also rebadged as SIIG Inc. model US2308 hardware version 1 */
#define OCT_DK201_PID 0x0103 /* OCT DK201 USB docking station */
#define OCT_US101_PID 0x0421 /* OCT US101 USB to RS-232 */
/*
* Definitions for Icom Inc. devices
*/
#define ICOM_VID 0x0C26 /* Icom vendor ID */
/* Note: ID-1 is a communications tranceiver for HAM-radio operators */
#define ICOM_ID_1_PID 0x0004 /* ID-1 USB to RS-232 */
/* Note: OPC is an Optional cable to connect an Icom Tranceiver */
#define ICOM_OPC_U_UC_PID 0x0018 /* OPC-478UC, OPC-1122U cloning cable */
/* Note: ID-RP* devices are Icom Repeater Devices for HAM-radio */
#define ICOM_ID_RP2C1_PID 0x0009 /* ID-RP2C Asset 1 to RS-232 */
#define ICOM_ID_RP2C2_PID 0x000A /* ID-RP2C Asset 2 to RS-232 */
#define ICOM_ID_RP2D_PID 0x000B /* ID-RP2D configuration port*/
#define ICOM_ID_RP2VT_PID 0x000C /* ID-RP2V Transmit config port */
#define ICOM_ID_RP2VR_PID 0x000D /* ID-RP2V Receive config port */
#define ICOM_ID_RP4KVT_PID 0x0010 /* ID-RP4000V Transmit config port */
#define ICOM_ID_RP4KVR_PID 0x0011 /* ID-RP4000V Receive config port */
#define ICOM_ID_RP2KVT_PID 0x0012 /* ID-RP2000V Transmit config port */
#define ICOM_ID_RP2KVR_PID 0x0013 /* ID-RP2000V Receive config port */
#define GN_OTOMETRICS_VID 0x0c33 /* Vendor ID */
#define AURICAL_USB_PID 0x0010 /* Aurical USB Audiometer */
/*
* The following are the values for the Sealevel SeaLINK+ adapters.
* (Original list sent by Tuan Hoang. Ian Abbott renamed the macros and
* removed some PIDs that don't seem to match any existing products.)
*/
#define SEALEVEL_VID 0x0c52 /* Sealevel Vendor ID */
#define SEALEVEL_2101_PID 0x2101 /* SeaLINK+232 (2101/2105) */
#define SEALEVEL_2102_PID 0x2102 /* SeaLINK+485 (2102) */
#define SEALEVEL_2103_PID 0x2103 /* SeaLINK+232I (2103) */
#define SEALEVEL_2104_PID 0x2104 /* SeaLINK+485I (2104) */
#define SEALEVEL_2106_PID 0x9020 /* SeaLINK+422 (2106) */
#define SEALEVEL_2201_1_PID 0x2211 /* SeaPORT+2/232 (2201) Port 1 */
#define SEALEVEL_2201_2_PID 0x2221 /* SeaPORT+2/232 (2201) Port 2 */
#define SEALEVEL_2202_1_PID 0x2212 /* SeaPORT+2/485 (2202) Port 1 */
#define SEALEVEL_2202_2_PID 0x2222 /* SeaPORT+2/485 (2202) Port 2 */
#define SEALEVEL_2203_1_PID 0x2213 /* SeaPORT+2 (2203) Port 1 */
#define SEALEVEL_2203_2_PID 0x2223 /* SeaPORT+2 (2203) Port 2 */
#define SEALEVEL_2401_1_PID 0x2411 /* SeaPORT+4/232 (2401) Port 1 */
#define SEALEVEL_2401_2_PID 0x2421 /* SeaPORT+4/232 (2401) Port 2 */
#define SEALEVEL_2401_3_PID 0x2431 /* SeaPORT+4/232 (2401) Port 3 */
#define SEALEVEL_2401_4_PID 0x2441 /* SeaPORT+4/232 (2401) Port 4 */
#define SEALEVEL_2402_1_PID 0x2412 /* SeaPORT+4/485 (2402) Port 1 */
#define SEALEVEL_2402_2_PID 0x2422 /* SeaPORT+4/485 (2402) Port 2 */
#define SEALEVEL_2402_3_PID 0x2432 /* SeaPORT+4/485 (2402) Port 3 */
#define SEALEVEL_2402_4_PID 0x2442 /* SeaPORT+4/485 (2402) Port 4 */
#define SEALEVEL_2403_1_PID 0x2413 /* SeaPORT+4 (2403) Port 1 */
#define SEALEVEL_2403_2_PID 0x2423 /* SeaPORT+4 (2403) Port 2 */
#define SEALEVEL_2403_3_PID 0x2433 /* SeaPORT+4 (2403) Port 3 */
#define SEALEVEL_2403_4_PID 0x2443 /* SeaPORT+4 (2403) Port 4 */
#define SEALEVEL_2801_1_PID 0X2811 /* SeaLINK+8/232 (2801) Port 1 */
#define SEALEVEL_2801_2_PID 0X2821 /* SeaLINK+8/232 (2801) Port 2 */
#define SEALEVEL_2801_3_PID 0X2831 /* SeaLINK+8/232 (2801) Port 3 */
#define SEALEVEL_2801_4_PID 0X2841 /* SeaLINK+8/232 (2801) Port 4 */
#define SEALEVEL_2801_5_PID 0X2851 /* SeaLINK+8/232 (2801) Port 5 */
#define SEALEVEL_2801_6_PID 0X2861 /* SeaLINK+8/232 (2801) Port 6 */
#define SEALEVEL_2801_7_PID 0X2871 /* SeaLINK+8/232 (2801) Port 7 */
#define SEALEVEL_2801_8_PID 0X2881 /* SeaLINK+8/232 (2801) Port 8 */
#define SEALEVEL_2802_1_PID 0X2812 /* SeaLINK+8/485 (2802) Port 1 */
#define SEALEVEL_2802_2_PID 0X2822 /* SeaLINK+8/485 (2802) Port 2 */
#define SEALEVEL_2802_3_PID 0X2832 /* SeaLINK+8/485 (2802) Port 3 */
#define SEALEVEL_2802_4_PID 0X2842 /* SeaLINK+8/485 (2802) Port 4 */
#define SEALEVEL_2802_5_PID 0X2852 /* SeaLINK+8/485 (2802) Port 5 */
#define SEALEVEL_2802_6_PID 0X2862 /* SeaLINK+8/485 (2802) Port 6 */
#define SEALEVEL_2802_7_PID 0X2872 /* SeaLINK+8/485 (2802) Port 7 */
#define SEALEVEL_2802_8_PID 0X2882 /* SeaLINK+8/485 (2802) Port 8 */
#define SEALEVEL_2803_1_PID 0X2813 /* SeaLINK+8 (2803) Port 1 */
#define SEALEVEL_2803_2_PID 0X2823 /* SeaLINK+8 (2803) Port 2 */
#define SEALEVEL_2803_3_PID 0X2833 /* SeaLINK+8 (2803) Port 3 */
#define SEALEVEL_2803_4_PID 0X2843 /* SeaLINK+8 (2803) Port 4 */
#define SEALEVEL_2803_5_PID 0X2853 /* SeaLINK+8 (2803) Port 5 */
#define SEALEVEL_2803_6_PID 0X2863 /* SeaLINK+8 (2803) Port 6 */
#define SEALEVEL_2803_7_PID 0X2873 /* SeaLINK+8 (2803) Port 7 */
#define SEALEVEL_2803_8_PID 0X2883 /* SeaLINK+8 (2803) Port 8 */
#define JETI_VID 0x0c6c
#define JETI_SPC1201_PID 0x04b2
#define ELEKTOR_VID 0x0C7D
#define ELEKTOR_FT323R_PID 0x0005 /* RFID-Reader, issue 09-2006 */
#define POSIFLEX_VID 0x0d3a /* Vendor ID */
#define POSIFLEX_PP7000_PID 0x0300 /* PP-7000II thermal printer */
/*
* The following are the values for two KOBIL chipcard terminals.
*/
#define KOBIL_VID 0x0d46 /* KOBIL Vendor ID */
#define KOBIL_CONV_B1_PID 0x2020 /* KOBIL Konverter for B1 */
#define KOBIL_CONV_KAAN_PID 0x2021 /* KOBIL_Konverter for KAAN */
#define FTDI_NF_RIC_VID 0x0DCD /* Vendor Id */
#define FTDI_NF_RIC_PID 0x0001 /* Product Id */
/*
* Falcom Wireless Communications GmbH
*/
#define FALCOM_VID 0x0F94 /* Vendor Id */
#define FALCOM_TWIST_PID 0x0001 /* Falcom Twist USB GPRS modem */
#define FALCOM_SAMBA_PID 0x0005 /* Falcom Samba USB GPRS modem */
/* Larsen and Brusgaard AltiTrack/USBtrack */
#define LARSENBRUSGAARD_VID 0x0FD8
#define LB_ALTITRACK_PID 0x0001
/*
* TTi (Thurlby Thandar Instruments)
*/
#define TTI_VID 0x103E /* Vendor Id */
#define TTI_QL355P_PID 0x03E8 /* TTi QL355P power supply */
/* Interbiometrics USB I/O Board */
/* Developed for Interbiometrics by Rudolf Gugler */
#define INTERBIOMETRICS_VID 0x1209
#define <API key> 0x1002
#define <API key> 0x1006
#define TESTO_VID 0x128D
#define <API key> 0x0001
/*
* Mobility Electronics products.
*/
#define MOBILITY_VID 0x1342
#define <API key> 0x0202 /* EasiDock USB 200 serial */
#define FIC_VID 0x1457
#define <API key> 0x5118
/* Olimex */
#define OLIMEX_VID 0x15BA
#define <API key> 0x0003
/*
* Telldus Technologies
*/
#define TELLDUS_VID 0x1781 /* Vendor ID */
#define <API key> 0x0C30 /* RF control dongle 433 MHz using FT232RL */
/*
* RT Systems programming cables for various ham radios
*/
#define RTSYSTEMS_VID 0x2100 /* Vendor ID */
#define <API key> 0x9e52 /* Serial converter for VX-7 Radios using FT232RL */
#define BAYER_VID 0x1A79
#define <API key> 0x6001
/*
* The following are the values for the Matrix Orbital FTDI Range
* Anything in this range will use an FT232RL.
*/
#define MTXORB_VID 0x1B3D
#define <API key> 0x0100
#define <API key> 0x0101
#define <API key> 0x0102
#define <API key> 0x0103
#define <API key> 0x0104
#define <API key> 0x0105
#define <API key> 0x0106
#define <API key> 0x0107
#define <API key> 0x0108
#define <API key> 0x0109
#define <API key> 0x010A
#define <API key> 0x010B
#define <API key> 0x010C
#define <API key> 0x010D
#define <API key> 0x010E
#define <API key> 0x010F
#define <API key> 0x0110
#define <API key> 0x0111
#define <API key> 0x0112
#define <API key> 0x0113
#define <API key> 0x0114
#define <API key> 0x0115
#define <API key> 0x0116
#define <API key> 0x0117
#define <API key> 0x0118
#define <API key> 0x0119
#define <API key> 0x011A
#define <API key> 0x011B
#define <API key> 0x011C
#define <API key> 0x011D
#define <API key> 0x011E
#define <API key> 0x011F
#define <API key> 0x0120
#define <API key> 0x0121
#define <API key> 0x0122
#define <API key> 0x0123
#define <API key> 0x0124
#define <API key> 0x0125
#define <API key> 0x0126
#define <API key> 0x0127
#define <API key> 0x0128
#define <API key> 0x0129
#define <API key> 0x012A
#define <API key> 0x012B
#define <API key> 0x012C
#define <API key> 0x012D
#define <API key> 0x012E
#define <API key> 0x012F
#define <API key> 0x0130
#define <API key> 0x0131
#define <API key> 0x0132
#define <API key> 0x0133
#define <API key> 0x0134
#define <API key> 0x0135
#define <API key> 0x0136
#define <API key> 0x0137
#define <API key> 0x0138
#define <API key> 0x0139
#define <API key> 0x013A
#define <API key> 0x013B
#define <API key> 0x013C
#define <API key> 0x013D
#define <API key> 0x013E
#define <API key> 0x013F
#define <API key> 0x0140
#define <API key> 0x0141
#define <API key> 0x0142
#define <API key> 0x0143
#define <API key> 0x0144
#define <API key> 0x0145
#define <API key> 0x0146
#define <API key> 0x0147
#define <API key> 0x0148
#define <API key> 0x0149
#define <API key> 0x014A
#define <API key> 0x014B
#define <API key> 0x014C
#define <API key> 0x014D
#define <API key> 0x014E
#define <API key> 0x014F
#define <API key> 0x0150
#define <API key> 0x0151
#define <API key> 0x0152
#define <API key> 0x0153
#define <API key> 0x0154
#define <API key> 0x0155
#define <API key> 0x0156
#define <API key> 0x0157
#define <API key> 0x0158
#define <API key> 0x0159
#define <API key> 0x015A
#define <API key> 0x015B
#define <API key> 0x015C
#define <API key> 0x015D
#define <API key> 0x015E
#define <API key> 0x015F
#define <API key> 0x0160
#define <API key> 0x0161
#define <API key> 0x0162
#define <API key> 0x0163
#define <API key> 0x0164
#define <API key> 0x0165
#define <API key> 0x0166
#define <API key> 0x0167
#define <API key> 0x0168
#define <API key> 0x0169
#define <API key> 0x016A
#define <API key> 0x016B
#define <API key> 0x016C
#define <API key> 0x016D
#define <API key> 0x016E
#define <API key> 0x016F
#define <API key> 0x0170
#define <API key> 0x0171
#define <API key> 0x0172
#define <API key> 0x0173
#define <API key> 0x0174
#define <API key> 0x0175
#define <API key> 0x0176
#define <API key> 0x0177
#define <API key> 0x0178
#define <API key> 0x0179
#define <API key> 0x017A
#define <API key> 0x017B
#define <API key> 0x017C
#define <API key> 0x017D
#define <API key> 0x017E
#define <API key> 0x017F
#define <API key> 0x0180
#define <API key> 0x0181
#define <API key> 0x0182
#define <API key> 0x0183
#define <API key> 0x0184
#define <API key> 0x0185
#define <API key> 0x0186
#define <API key> 0x0187
#define <API key> 0x0188
#define <API key> 0x0189
#define <API key> 0x018A
#define <API key> 0x018B
#define <API key> 0x018C
#define <API key> 0x018D
#define <API key> 0x018E
#define <API key> 0x018F
#define <API key> 0x0190
#define <API key> 0x0191
#define <API key> 0x0192
#define <API key> 0x0193
#define <API key> 0x0194
#define <API key> 0x0195
#define <API key> 0x0196
#define <API key> 0x0197
#define <API key> 0x0198
#define <API key> 0x0199
#define <API key> 0x019A
#define <API key> 0x019B
#define <API key> 0x019C
#define <API key> 0x019D
#define <API key> 0x019E
#define <API key> 0x019F
#define <API key> 0x01A0
#define <API key> 0x01A1
#define <API key> 0x01A2
#define <API key> 0x01A3
#define <API key> 0x01A4
#define <API key> 0x01A5
#define <API key> 0x01A6
#define <API key> 0x01A7
#define <API key> 0x01A8
#define <API key> 0x01A9
#define <API key> 0x01AA
#define <API key> 0x01AB
#define <API key> 0x01AC
#define <API key> 0x01AD
#define <API key> 0x01AE
#define <API key> 0x01AF
#define <API key> 0x01B0
#define <API key> 0x01B1
#define <API key> 0x01B2
#define <API key> 0x01B3
#define <API key> 0x01B4
#define <API key> 0x01B5
#define <API key> 0x01B6
#define <API key> 0x01B7
#define <API key> 0x01B8
#define <API key> 0x01B9
#define <API key> 0x01BA
#define <API key> 0x01BB
#define <API key> 0x01BC
#define <API key> 0x01BD
#define <API key> 0x01BE
#define <API key> 0x01BF
#define <API key> 0x01C0
#define <API key> 0x01C1
#define <API key> 0x01C2
#define <API key> 0x01C3
#define <API key> 0x01C4
#define <API key> 0x01C5
#define <API key> 0x01C6
#define <API key> 0x01C7
#define <API key> 0x01C8
#define <API key> 0x01C9
#define <API key> 0x01CA
#define <API key> 0x01CB
#define <API key> 0x01CC
#define <API key> 0x01CD
#define <API key> 0x01CE
#define <API key> 0x01CF
#define <API key> 0x01D0
#define <API key> 0x01D1
#define <API key> 0x01D2
#define <API key> 0x01D3
#define <API key> 0x01D4
#define <API key> 0x01D5
#define <API key> 0x01D6
#define <API key> 0x01D7
#define <API key> 0x01D8
#define <API key> 0x01D9
#define <API key> 0x01DA
#define <API key> 0x01DB
#define <API key> 0x01DC
#define <API key> 0x01DD
#define <API key> 0x01DE
#define <API key> 0x01DF
#define <API key> 0x01E0
#define <API key> 0x01E1
#define <API key> 0x01E2
#define <API key> 0x01E3
#define <API key> 0x01E4
#define <API key> 0x01E5
#define <API key> 0x01E6
#define <API key> 0x01E7
#define <API key> 0x01E8
#define <API key> 0x01E9
#define <API key> 0x01EA
#define <API key> 0x01EB
#define <API key> 0x01EC
#define <API key> 0x01ED
#define <API key> 0x01EE
#define <API key> 0x01EF
#define <API key> 0x01F0
#define <API key> 0x01F1
#define <API key> 0x01F2
#define <API key> 0x01F3
#define <API key> 0x01F4
#define <API key> 0x01F5
#define <API key> 0x01F6
#define <API key> 0x01F7
#define <API key> 0x01F8
#define <API key> 0x01F9
#define <API key> 0x01FA
#define <API key> 0x01FB
#define <API key> 0x01FC
#define <API key> 0x01FD
#define <API key> 0x01FE
#define <API key> 0x01FF
/*
* The Mobility Lab (TML)
* Submitted by Pierre Castella
*/
#define TML_VID 0x1B91 /* Vendor ID */
#define TML_USB_SERIAL_PID 0x0064 /* USB - Serial Converter */
#define ALTI2_VID 0x1BC9
#define ALTI2_N3_PID 0x6001 /* Neptune 3 */
/*
* Ionics PlugComputer
*/
#define IONICS_VID 0x1c0c
#define <API key> 0x0102
/*
* Dresden Elektronik Sensor Terminal Board
*/
#define DE_VID 0x1cf1 /* Vendor ID */
#define STB_PID 0x0001 /* Sensor Terminal Board */
#define WHT_PID 0x0004 /* Wireless Handheld Terminal */
/*
* STMicroelectonics
*/
#define ST_VID 0x0483
#define ST_STMCLT1030_PID 0x3747 /* ST Micro Connect Lite STMCLT1030 */
#define PAPOUCH_VID 0x5050 /* Vendor ID */
#define PAPOUCH_TMU_PID 0x0400 /* TMU USB Thermometer */
#define <API key> 0x0900 /* Quido 4/4 Module */
#define PAPOUCH_AD4USB_PID 0x8003 /* AD4USB Measurement Module */
/*
* Marvell SheevaPlug
*/
#define MARVELL_VID 0x9e88
#define <API key> 0x9e8f
#define EVOLUTION_VID 0xDEEE /* Vendor ID */
#define EVOLUTION_ER1_PID 0x0300 /* ER1 Control Module */
#define EVO_8U232AM_PID 0x02FF /* Evolution robotics RCM2 (FT232AM)*/
#define EVO_HYBRID_PID 0x0302 /* Evolution robotics RCM4 PID (FT232BM)*/
#define EVO_RCM4_PID 0x0303 /* Evolution robotics RCM4 PID */
/*
* MJS Gadgets HD Radio / XM Radio / Sirius Radio interfaces (using VID 0x0403)
*/
#define MJSG_GENERIC_PID 0x9378
#define MJSG_SR_RADIO_PID 0x9379
#define MJSG_XM_RADIO_PID 0x937A
#define MJSG_HD_RADIO_PID 0x937C
#define FTDI_DOTEC_PID 0x9868
#define <API key> 0xBCA0
#define <API key> 0xBCA1
#define <API key> 0xBCA2
#define <API key> 0xBCA4
/*
* Segway Robotic Mobility Platform USB interface (using VID 0x0403)
* Submitted by John G. Rogers
*/
#define SEGWAY_RMP200_PID 0xe729
|
// modification, are permitted provided that the following conditions
// are met:
// and/or other materials provided with the distribution.
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using NLog.Internal;
using NLog.Config;
using NLog.Conditions;
using System.Collections.Generic;
namespace NLog.Targets.Wrappers
{
<summary>
A target wrapper that filters buffered log entries based on a set of conditions
that are evaluated on all events.
</summary>
<remarks>
<API key> must be used with some type of buffering target or wrapper, such as
AsyncTargetWrapper, BufferingWrapper or <API key>.
</remarks>
<example>
<p>
This example works like this. If there are no Warn,Error or Fatal messages in the buffer
only Info messages are written to the file, but if there are any warnings or errors,
the output includes detailed trace (levels >= Debug). You can plug in a different type
of buffering wrapper (such as <API key>) to achieve different
functionality.
</p>
<p>
To set up the target in the <a href="config.html">configuration file</a>,
use the following syntax:
</p>
<code lang="XML" src="examples/targets/Configuration File/<API key>/NLog.config" />
<p>
The above examples assume just one target and a single rule. See below for
a programmatic configuration that's equivalent to the above config file:
</p>
<code lang="C#" src="examples/targets/Configuration API/<API key>/Simple/Example.cs" />
</example>
[Target("<API key>", IgnoresLayout = true, IsWrapper = true)]
public class <API key>: WrapperTargetBase
{
private ConditionExpression _defaultFilter;
private <API key> _rules = new <API key>();
<summary>
Creates a new instance of <see cref="<API key>"/>.
</summary>
public <API key>()
{
}
<summary>
Default filter to be applied when no specific rule matches.
</summary>
public string DefaultFilter
{
get { return _defaultFilter.ToString(); }
set { _defaultFilter = ConditionParser.ParseExpression(value); }
}
<summary>
Collection of filtering rules. The rules are processed top-down
and the first rule that matches determines the filtering condition to
be applied to log events.
</summary>
[ArrayParameter(typeof(FilteringRule), "when")]
public <API key> Rules
{
get { return _rules; }
}
<summary>
Evaluates all filtering rules to find the first one that matches.
The matching rule determines the filtering condition to be applied
to all items in a buffer. If no condition matches, default filter
is applied to the array of log events.
</summary>
<param name="logEvents">Array of log events to be post-filtered.</param>
public override void Write(LogEventInfo[] logEvents)
{
ConditionExpression resultFilter = null;
if (InternalLogger.IsTraceEnabled)
{
InternalLogger.Trace("Input: {0} events", logEvents.Length);
}
// evaluate all the rules to get the filtering condition
for (int i = 0; i < logEvents.Length; ++i)
{
for (int j = 0; j < _rules.Count; ++j)
{
object v = _rules[j].ExistsCondition.Evaluate(logEvents[i]);
if (v is bool && (bool)v)
{
if (InternalLogger.IsTraceEnabled)
InternalLogger.Trace("Rule matched: {0}", _rules[j].ExistsCondition);
resultFilter = _rules[j].FilterCondition;
break;
}
}
if (resultFilter != null)
break;
}
if (resultFilter == null)
resultFilter = _defaultFilter;
if (InternalLogger.IsTraceEnabled)
InternalLogger.Trace("Filter to apply: {0}", resultFilter);
// apply the condition to the buffer
List<LogEventInfo> resultBuffer = new List<LogEventInfo>();
for (int i = 0; i < logEvents.Length; ++i)
{
object v = resultFilter.Evaluate(logEvents[i]);
if (v is bool && (bool)v)
resultBuffer.Add(logEvents[i]);
}
if (InternalLogger.IsTraceEnabled)
InternalLogger.Trace("After filtering: {0} events", resultBuffer.Count);
if (resultBuffer.Count > 0)
{
WrappedTarget.Write(resultBuffer.ToArray());
}
}
<summary>
Processes a single log event. Not very useful for this post-filtering
wrapper.
</summary>
<param name="logEvent">Log event.</param>
public override void Write(LogEventInfo logEvent)
{
Write(new LogEventInfo[] { logEvent });
}
<summary>
Adds all layouts used by this target to the specified collection.
</summary>
<param name="layouts">The collection to add layouts to.</param>
public override void PopulateLayouts(LayoutCollection layouts)
{
base.PopulateLayouts(layouts);
foreach (FilteringRule fr in Rules)
{
fr.FilterCondition.PopulateLayouts(layouts);
fr.ExistsCondition.PopulateLayouts(layouts);
}
_defaultFilter.PopulateLayouts(layouts);
}
}
}
|
include $(TOPDIR)/rules.mk
include $(INCLUDE_DIR)/kernel.mk
PKG_NAME:=mac80211
PKG_VERSION:=2014-11-04
PKG_RELEASE:=1
PKG_SOURCE_URL:=http://mirror2.openwrt.org/sources
<API key>:=
PKG_MD5SUM:=<API key>
PKG_SOURCE:=compat-wireless-$(PKG_VERSION)$(<API key>).tar.bz2
PKG_BUILD_DIR:=$(KERNEL_BUILD_DIR)/compat-wireless-$(PKG_VERSION)
PKG_BUILD_PARALLEL:=1
PKG_MAINTAINER:=Felix Fietkau <nbd@openwrt.org>
PKG_DRIVERS = \
adm8211 ath5k libertas-usb libertas-sd p54-common p54-pci p54-usb p54-spi \
rt2x00-lib rt2x00-pci rt2x00-usb rt2800-lib rt2400-pci rt2500-pci \
rt2500-usb rt61-pci rt73-usb rt2800-mmio rt2800-pci rt2800-usb rt2800-soc \
rtl8180 rtl8187 zd1211rw mac80211-hwsim carl9170 b43 b43legacy \
ath9k-common ath9k ath9k-htc ath10k ath net-libipw net-ipw2100 net-ipw2200 \
mwl8k mwifiex-pcie net-hermes net-hermes-pci net-hermes-plx net-hermes-pcmcia \
iwl-legacy iwl3945 iwl4965 iwlagn wlcore wl12xx wl18xx lib80211 \
rtlwifi rtlwifi-pci rtlwifi-usb rtl8192c-common rtl8192ce rtl8192se \
rtl8192de rtl8192cu
PKG_CONFIG_DEPENDS:= \
<API key> \
$(patsubst %,CONFIG_PACKAGE_kmod-%,$(PKG_DRIVERS)) \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
include $(INCLUDE_DIR)/package.mk
WMENU:=Wireless Drivers
define KernelPackage/mac80211/Default
SUBMENU:=$(WMENU)
URL:=http://linuxwireless.org/
MAINTAINER:=Felix Fietkau <nbd@openwrt.org>
DEPENDS:=@(!TARGET_avr32||BROKEN)
endef
define KernelPackage/cfg80211
$(call KernelPackage/mac80211/Default)
TITLE:=cfg80211 - wireless configuration API
DEPENDS+= +iw
FILES:= \
$(PKG_BUILD_DIR)/compat/compat.ko \
$(PKG_BUILD_DIR)/net/wireless/cfg80211.ko
endef
define KernelPackage/cfg80211/description
cfg80211 is the Linux wireless LAN (802.11) configuration API.
endef
define KernelPackage/mac80211
$(call KernelPackage/mac80211/Default)
TITLE:=Linux 802.11 Wireless Networking Stack
DEPENDS+= +kmod-crypto-core +kmod-crypto-arc4 +kmod-crypto-aes +kmod-cfg80211 +hostapd-common
KCONFIG:=\
CONFIG_AVERAGE=y
FILES:= $(PKG_BUILD_DIR)/net/mac80211/mac80211.ko
MENU:=1
endef
define KernelPackage/mac80211/config
if <API key>
config <API key>
bool "Export mac80211 internals in DebugFS"
select KERNEL_DEBUG_FS
select KERNEL_RELAY if <API key>
default y
help
Select this to see extensive information about
the internal state of mac80211 in debugfs.
config <API key>
bool "Enable 802.11s mesh support"
default y
endif
endef
define KernelPackage/mac80211/description
Generic IEEE 802.11 Networking Stack (mac80211)
endef
<API key>:=linux-firmware
<API key>:=<SHA1-like>
<API key>:=$(<API key>)-2014-06-04-$(<API key>).tar.bz2
<API key>:=git
<API key>:=https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git
<API key>:=$(<API key>)-$(<API key>)
#<API key>:=<API key>
define Download/linux-firmware
FILE:=$(<API key>)
URL:=$(<API key>)
MD5SUM:=$(<API key>)
PROTO:=$(<API key>)
VERSION:=$(<API key>)
SUBDIR:=$(<API key>)
MIRROR_MD5SUM:=$(<API key>)
endef
$(eval $(call Download,linux-firmware))
<API key>:=ath10k-firmware
<API key>:=<SHA1-like>
<API key>:=$(<API key>)-$(<API key>).tar.bz2
<API key>:=git
<API key>:=https://github.com/kvalo/ath10k-firmware.git
<API key>:=$(<API key>)-$(<API key>)
#<API key>:=?
define Download/ath10k-firmware
FILE:=$(<API key>)
URL:=$(<API key>)
PROTO:=$(<API key>)
VERSION:=$(<API key>)
SUBDIR:=$(<API key>)
#MIRROR_MD5SUM:=$(<API key>)
endef
$(eval $(call Download,ath10k-firmware))
# Prism54 drivers
P54PCIFW:=2.13.12.0.arm
P54USBFW:=2.13.24.0.lm87.arm
P54SPIFW:=2.13.0.0.a.13.14.arm
define Download/p54usb
FILE:=$(P54USBFW)
URL:=http://daemonizer.de/prism54/prism54-fw/fw-usb
MD5SUM:=<API key>
endef
$(eval $(call Download,p54usb))
define Download/p54pci
FILE:=$(P54PCIFW)
URL:=http://daemonizer.de/prism54/prism54-fw/fw-softmac
MD5SUM:=<API key>
endef
$(eval $(call Download,p54pci))
define Download/p54spi
FILE:=$(P54SPIFW)
URL:=http://daemonizer.de/prism54/prism54-fw/stlc4560
MD5SUM:=<API key>
endef
$(eval $(call Download,p54spi))
define KernelPackage/p54/Default
$(call KernelPackage/mac80211/Default)
TITLE:=Prism54 Drivers
endef
define KernelPackage/p54/description
Kernel module for Prism54 chipsets (mac80211)
endef
define KernelPackage/p54-common
$(call KernelPackage/p54/Default)
DEPENDS+= @PCI_SUPPORT||@USB_SUPPORT||@TARGET_omap24xx +kmod-mac80211 +kmod-lib-crc-ccitt
TITLE+= (COMMON)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/p54/p54common.ko
endef
define KernelPackage/p54-pci
$(call KernelPackage/p54/Default)
TITLE+= (PCI)
DEPENDS+= @PCI_SUPPORT +kmod-p54-common
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/p54/p54pci.ko
AUTOLOAD:=$(call AutoProbe,p54pci)
endef
define KernelPackage/p54-usb
$(call KernelPackage/p54/Default)
TITLE+= (USB)
DEPENDS+= @USB_SUPPORT +kmod-usb-core +kmod-p54-common
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/p54/p54usb.ko
AUTOLOAD:=$(call AutoProbe,p54usb)
endef
define KernelPackage/p54-spi
$(call KernelPackage/p54/Default)
TITLE+= (SPI)
DEPENDS+= @TARGET_omap24xx +kmod-p54-common
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/p54/p54spi.ko
AUTOLOAD:=$(call AutoProbe,p54spi)
endef
define KernelPackage/rt2x00/Default
$(call KernelPackage/mac80211/Default)
TITLE:=Ralink Drivers for RT2x00 cards
endef
define KernelPackage/rt2x00-lib
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @(PCI_SUPPORT||USB_SUPPORT||TARGET_ramips) +kmod-mac80211 +kmod-lib-crc-itu-t
TITLE+= (LIB)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2x00lib.ko
MENU:=1
endef
define KernelPackage/rt2x00-lib/config
if <API key>
config <API key>
bool "Enable rt2x00 debugfs support"
depends on <API key>
help
Enable creation of debugfs files for the rt2x00 drivers.
These debugfs files support both reading and writing of the
most important register types of the rt2x00 hardware.
config <API key>
bool "Enable rt2x00 debug output"
help
Enable debugging output for all rt2x00 modules
endif
endef
define KernelPackage/rt2x00-mmio
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @(PCI_SUPPORT||TARGET_ramips) +kmod-rt2x00-lib +kmod-eeprom-93cx6
HIDDEN:=1
TITLE+= (MMIO)
FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2x00mmio.ko
endef
define KernelPackage/rt2x00-pci
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @PCI_SUPPORT +kmod-rt2x00-mmio +kmod-rt2x00-lib
HIDDEN:=1
TITLE+= (PCI)
FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2x00pci.ko
AUTOLOAD:=$(call AutoProbe,rt2x00pci)
endef
define KernelPackage/rt2x00-usb
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @USB_SUPPORT +kmod-rt2x00-lib +kmod-usb-core
HIDDEN:=1
TITLE+= (USB)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2x00usb.ko
AUTOLOAD:=$(call AutoProbe,rt2x00usb)
endef
define KernelPackage/rt2800-lib
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @(PCI_SUPPORT||USB_SUPPORT||TARGET_ramips) +kmod-rt2x00-lib +kmod-lib-crc-ccitt +@DRIVER_11N_SUPPORT
HIDDEN:=1
TITLE+= (rt2800 LIB)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2800lib.ko
endef
define KernelPackage/rt2400-pci
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @PCI_SUPPORT +kmod-rt2x00-pci
TITLE+= (RT2400 PCI)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2400pci.ko
AUTOLOAD:=$(call AutoProbe,rt2400pci)
endef
define KernelPackage/rt2500-pci
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @PCI_SUPPORT +kmod-rt2x00-pci
TITLE+= (RT2500 PCI)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2500pci.ko
AUTOLOAD:=$(call AutoProbe,rt2500pci)
endef
define KernelPackage/rt2500-usb
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @USB_SUPPORT +kmod-rt2x00-usb
TITLE+= (RT2500 USB)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2500usb.ko
AUTOLOAD:=$(call AutoProbe,rt2500usb)
endef
define KernelPackage/rt61-pci
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @PCI_SUPPORT +kmod-rt2x00-pci
TITLE+= (RT2x61 PCI)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt61pci.ko
AUTOLOAD:=$(call AutoProbe,rt61pci)
endef
define KernelPackage/rt73-usb
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @USB_SUPPORT +kmod-rt2x00-usb
TITLE+= (RT73 USB)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt73usb.ko
AUTOLOAD:=$(call AutoProbe,rt73usb)
endef
define KernelPackage/rt2800-mmio
$(call KernelPackage/rt2x00/Default)
TITLE += (RT28xx/RT3xxx MMIO)
DEPENDS += +kmod-rt2800-lib +kmod-rt2x00-mmio
HIDDEN:=1
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2800mmio.ko
endef
define KernelPackage/rt2800-soc
$(call KernelPackage/rt2x00/Default)
DEPENDS += @(<API key>||<API key>||<API key>||<API key>) +kmod-rt2800-mmio +kmod-rt2800-lib
TITLE += (RT28xx/RT3xxx SoC)
FILES := \
$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2x00soc.ko \
$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2800soc.ko
AUTOLOAD:=$(call AutoProbe,rt2800soc)
endef
define KernelPackage/rt2800-pci
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @PCI_SUPPORT +kmod-rt2x00-pci +kmod-rt2800-lib +kmod-rt2800-mmio
TITLE+= (RT2860 PCI)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2800pci.ko
AUTOLOAD:=$(call AutoProbe,rt2800pci)
endef
define KernelPackage/rt2800-usb
$(call KernelPackage/rt2x00/Default)
DEPENDS+= @USB_SUPPORT +kmod-rt2x00-usb +kmod-rt2800-lib +kmod-lib-crc-ccitt
TITLE+= (RT2870 USB)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rt2x00/rt2800usb.ko
AUTOLOAD:=$(call AutoProbe,rt2800usb)
endef
define KernelPackage/rtl818x/Default
$(call KernelPackage/mac80211/Default)
TITLE:=Realtek Drivers for RTL818x devices
URL:=http://wireless.kernel.org/en/users/Drivers/rtl8187
DEPENDS+= +kmod-eeprom-93cx6 +kmod-mac80211
endef
define KernelPackage/rtl8180
$(call KernelPackage/rtl818x/Default)
DEPENDS+= @PCI_SUPPORT
TITLE+= (RTL8180 PCI)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtl818x/rtl8180/rtl818x_pci.ko
AUTOLOAD:=$(call AutoProbe,rtl818x_pci)
endef
define KernelPackage/rtl8187
$(call KernelPackage/rtl818x/Default)
DEPENDS+= @USB_SUPPORT +kmod-usb-core
TITLE+= (RTL8187 USB)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtl818x/rtl8187/rtl8187.ko
AUTOLOAD:=$(call AutoProbe,rtl8187)
endef
define KernelPackage/rtlwifi/config
config <API key>
bool "Realtek wireless debugging"
depends on <API key>
help
Say Y, if you want to debug realtek wireless drivers.
endef
define KernelPackage/rtlwifi
$(call KernelPackage/mac80211/Default)
TITLE:=Realtek common driver part
DEPENDS+= @(PCI_SUPPORT||USB_SUPPORT) +kmod-mac80211 +@DRIVER_11N_SUPPORT
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtlwifi.ko
HIDDEN:=1
endef
define KernelPackage/rtlwifi-pci
$(call KernelPackage/mac80211/Default)
TITLE:=Realtek common driver part (PCI support)
DEPENDS+= @PCI_SUPPORT +kmod-rtlwifi
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl_pci.ko
AUTOLOAD:=$(call AutoProbe,rtl_pci)
HIDDEN:=1
endef
define KernelPackage/rtlwifi-usb
$(call KernelPackage/mac80211/Default)
TITLE:=Realtek common driver part (USB support)
DEPENDS+= @USB_SUPPORT +kmod-usb-core +kmod-rtlwifi
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl_usb.ko
AUTOLOAD:=$(call AutoProbe,rtl_usb)
HIDDEN:=1
endef
define KernelPackage/rtl8192c-common
$(call KernelPackage/mac80211/Default)
TITLE:=Realtek RTL8192CE/RTL8192CU common support module
DEPENDS+= +kmod-rtlwifi
FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl8192c/rtl8192c-common.ko
HIDDEN:=1
endef
define KernelPackage/rtl8192ce
$(call KernelPackage/mac80211/Default)
TITLE:=Realtek RTL8192CE/RTL8188CE support
DEPENDS+= +kmod-rtlwifi-pci +<API key>
FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl8192ce/rtl8192ce.ko
AUTOLOAD:=$(call AutoProbe,rtl8192ce)
endef
define KernelPackage/rtl8192ce/install
$(INSTALL_DIR) $(1)/lib/firmware/rtlwifi
$(INSTALL_DATA) $(PKG_BUILD_DIR)/$(<API key>)/rtlwifi/rtl8192cfw.bin $(1)/lib/firmware/rtlwifi
$(INSTALL_DATA) $(PKG_BUILD_DIR)/$(<API key>)/rtlwifi/rtl8192cfwU.bin $(1)/lib/firmware/rtlwifi
$(INSTALL_DATA) $(PKG_BUILD_DIR)/$(<API key>)/rtlwifi/rtl8192cfwU_B.bin $(1)/lib/firmware/rtlwifi
endef
define KernelPackage/rtl8192se
$(call KernelPackage/mac80211/Default)
TITLE:=Realtek RTL8192SE/RTL8191SE support
DEPENDS+= +kmod-rtlwifi-pci
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl8192se/rtl8192se.ko
AUTOLOAD:=$(call AutoProbe,rtl8192se)
endef
define KernelPackage/rtl8192se/install
$(INSTALL_DIR) $(1)/lib/firmware/rtlwifi
$(INSTALL_DATA) $(PKG_BUILD_DIR)/$(<API key>)/rtlwifi/rtl8192sefw.bin $(1)/lib/firmware/rtlwifi
endef
define KernelPackage/rtl8192de
$(call KernelPackage/mac80211/Default)
TITLE:=Realtek RTL8192DE/RTL8188DE support
DEPENDS+= +kmod-rtlwifi-pci
FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl8192de/rtl8192de.ko
AUTOLOAD:=$(call AutoProbe,rtl8192de)
endef
define KernelPackage/rtl8192de/install
$(INSTALL_DIR) $(1)/lib/firmware/rtlwifi
$(INSTALL_DATA) $(PKG_BUILD_DIR)/$(<API key>)/rtlwifi/rtl8192defw.bin $(1)/lib/firmware/rtlwifi
endef
define KernelPackage/rtl8192cu
$(call KernelPackage/mac80211/Default)
TITLE:=Realtek RTL8192CU/RTL8188CU support
DEPENDS+= +kmod-rtlwifi-usb +<API key>
FILES:= $(PKG_BUILD_DIR)/drivers/net/wireless/rtlwifi/rtl8192cu/rtl8192cu.ko
AUTOLOAD:=$(call AutoProbe,rtl8192cu)
endef
define KernelPackage/rtl8192cu/install
$(INSTALL_DIR) $(1)/lib/firmware/rtlwifi
$(INSTALL_DATA) $(PKG_BUILD_DIR)/$(<API key>)/rtlwifi/rtl8192cufw.bin $(1)/lib/firmware/rtlwifi
$(INSTALL_DATA) $(PKG_BUILD_DIR)/$(<API key>)/rtlwifi/rtl8192cufw_A.bin $(1)/lib/firmware/rtlwifi
$(INSTALL_DATA) $(PKG_BUILD_DIR)/$(<API key>)/rtlwifi/rtl8192cufw_B.bin $(1)/lib/firmware/rtlwifi
$(INSTALL_DATA) $(PKG_BUILD_DIR)/$(<API key>)/rtlwifi/rtl8192cufw_TMSC.bin $(1)/lib/firmware/rtlwifi
endef
ZD1211FW_NAME:=zd1211-firmware
ZD1211FW_VERSION:=1.4
define Download/zd1211rw
FILE:=$(ZD1211FW_NAME)-$(ZD1211FW_VERSION).tar.bz2
URL:=@SF/zd1211/
MD5SUM:=<API key>
endef
$(eval $(call Download,zd1211rw))
define KernelPackage/zd1211rw
$(call KernelPackage/mac80211/Default)
TITLE:=Zydas ZD1211 support
DEPENDS+= @USB_SUPPORT +kmod-usb-core +kmod-mac80211
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/zd1211rw/zd1211rw.ko
AUTOLOAD:=$(call AutoProbe,zd1211rw)
endef
define KernelPackage/adm8211
$(call KernelPackage/mac80211/Default)
TITLE:=ADMTek 8211 support
DEPENDS+=@PCI_SUPPORT +kmod-mac80211 +kmod-eeprom-93cx6
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/adm8211.ko
AUTOLOAD:=$(call AutoProbe,adm8211)
endef
define KernelPackage/ath/config
if PACKAGE_kmod-ath
config ATH_USER_REGD
bool "Force Atheros drivers to respect the user's regdomain settings"
help
Atheros' idea of regulatory handling is that the EEPROM of the card defines
the regulatory limits and the user is only allowed to restrict the settings
even further, even if the country allows frequencies or power levels that
are forbidden by the EEPROM settings.
Select this option if you want the driver to respect the user's decision about
regulatory settings.
config PACKAGE_ATH_DEBUG
bool "Atheros wireless debugging"
help
Say Y, if you want to debug atheros wireless drivers.
Right now only ath9k makes use of this.
config PACKAGE_ATH_DFS
bool "Enable DFS support"
default y
help
Dynamic frequency selection (DFS) is required for most of the 5 GHz band
channels in Europe, US, and Japan.
Select this option if you want to use such channels.
endif
endef
define KernelPackage/ath
$(call KernelPackage/mac80211/Default)
TITLE:=Atheros common driver part
DEPENDS+= @PCI_SUPPORT||USB_SUPPORT||TARGET_ar71xx||TARGET_atheros +kmod-mac80211
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath.ko
MENU:=1
endef
define KernelPackage/ath/description
This module contains some common parts needed by Atheros Wireless drivers.
endef
define KernelPackage/ath5k
$(call KernelPackage/mac80211/Default)
TITLE:=Atheros 5xxx wireless cards support
URL:=http://linuxwireless.org/en/users/Drivers/ath5k
DEPENDS+= @PCI_SUPPORT||@TARGET_atheros +kmod-ath
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath5k/ath5k.ko
AUTOLOAD:=$(call AutoProbe,ath5k)
endef
define KernelPackage/ath5k/description
This module adds support for wireless adapters based on
Atheros 5xxx chipset.
endef
define KernelPackage/ath9k-common
$(call KernelPackage/mac80211/Default)
TITLE:=Atheros 802.11n wireless devices (common code for ath9k and ath9k_htc)
URL:=http://linuxwireless.org/en/users/Drivers/ath9k
DEPENDS+= @PCI_SUPPORT||USB_SUPPORT||TARGET_ar71xx +kmod-ath +@DRIVER_11N_SUPPORT
FILES:= \
$(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath9k/ath9k_common.ko \
$(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath9k/ath9k_hw.ko
endef
define KernelPackage/ath9k
$(call KernelPackage/mac80211/Default)
TITLE:=Atheros 802.11n PCI wireless cards support
URL:=http://linuxwireless.org/en/users/Drivers/ath9k
DEPENDS+= @PCI_SUPPORT||TARGET_ar71xx +kmod-ath9k-common
FILES:= \
$(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath9k/ath9k.ko
AUTOLOAD:=$(call AutoProbe,ath9k)
endef
define KernelPackage/ath9k/description
This module adds support for wireless adapters based on
Atheros IEEE 802.11n AR5008 and AR9001 family of chipsets.
endef
define KernelPackage/ath9k/config
config ATH9K_SUPPORT_PCOEM
bool "Support chips used in PC OEM cards"
depends on PACKAGE_kmod-ath9k
endef
define KernelPackage/ath9k-htc
$(call KernelPackage/mac80211/Default)
TITLE:=Atheros 802.11n USB device support
URL:=http://linuxwireless.org/en/users/Drivers/ath9k
DEPENDS+= @USB_SUPPORT +kmod-ath9k-common +kmod-usb-core
FILES:= \
$(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath9k/ath9k_htc.ko
AUTOLOAD:=$(call AutoProbe,ath9k_htc)
endef
define KernelPackage/ath9k-htc/description
This module adds support for wireless adapters based on
Atheros USB AR9271 and AR7010 family of chipsets.
endef
define KernelPackage/ath10k
$(call KernelPackage/mac80211/Default)
TITLE:=Atheros 802.11ac wireless cards support
URL:=http://wireless.kernel.org/en/users/Drivers/ath10k
DEPENDS+= @PCI_SUPPORT +kmod-ath +@DRIVER_11N_SUPPORT
FILES:= \
$(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath10k/ath10k_core.ko \
$(PKG_BUILD_DIR)/drivers/net/wireless/ath/ath10k/ath10k_pci.ko
AUTOLOAD:=$(call AutoLoad,55,ath10k_core ath10k_pci)
endef
define KernelPackage/ath10k/description
This module adds support for wireless adapters based on
Atheros IEEE 802.11ac family of chipsets. For now only
PCI is supported.
endef
define KernelPackage/ath10k/config
if PACKAGE_kmod-ath10k
config ATH10K_STA_FW
bool "Firmware optimized for STA operation"
default n
help
Use the ath10k firmware optimized for wireless client instead
of access point operation.
endif
endef
define KernelPackage/carl9170
$(call KernelPackage/mac80211/Default)
TITLE:=Driver for Atheros AR9170 USB sticks
DEPENDS:=@USB_SUPPORT +kmod-mac80211 +kmod-ath +kmod-usb-core +kmod-input-core +@DRIVER_11N_SUPPORT
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ath/carl9170/carl9170.ko
AUTOLOAD:=$(call AutoProbe,carl9170)
endef
define KernelPackage/lib80211
$(call KernelPackage/mac80211/Default)
TITLE:=802.11 Networking stack
DEPENDS:=+kmod-cfg80211
FILES:= \
$(PKG_BUILD_DIR)/net/wireless/lib80211.ko \
$(PKG_BUILD_DIR)/net/wireless/lib80211_crypt_wep.ko \
$(PKG_BUILD_DIR)/net/wireless/lib80211_crypt_ccmp.ko \
$(PKG_BUILD_DIR)/net/wireless/lib80211_crypt_tkip.ko
AUTOLOAD:=$(call AutoProbe, \
lib80211 \
lib80211_crypt_wep \
lib80211_crypt_ccmp \
lib80211_crypt_tkip \
)
endef
define KernelPackage/lib80211/description
Kernel modules for 802.11 Networking stack
Includes:
- lib80211
- lib80211_crypt_wep
- lib80211_crypt_tkip
- lib80211_crytp_ccmp
endef
define KernelPackage/libertas-usb
$(call KernelPackage/mac80211/Default)
DEPENDS+= @USB_SUPPORT +kmod-cfg80211 +kmod-usb-core +kmod-lib80211 +@DRIVER_WEXT_SUPPORT
TITLE:=Marvell 88W8015 Wireless Driver
FILES:= \
$(PKG_BUILD_DIR)/drivers/net/wireless/libertas/libertas.ko \
$(PKG_BUILD_DIR)/drivers/net/wireless/libertas/usb8xxx.ko
AUTOLOAD:=$(call AutoProbe,libertas usb8xxx)
endef
define KernelPackage/libertas-sd
$(call KernelPackage/mac80211/Default)
DEPENDS+= +kmod-cfg80211 +kmod-lib80211 +kmod-mmc +@DRIVER_WEXT_SUPPORT @!TARGET_uml
TITLE:=Marvell 88W8686 Wireless Driver
FILES:= \
$(PKG_BUILD_DIR)/drivers/net/wireless/libertas/libertas.ko \
$(PKG_BUILD_DIR)/drivers/net/wireless/libertas/libertas_sdio.ko
AUTOLOAD:=$(call AutoProbe,libertas libertas_sdio)
endef
define KernelPackage/mac80211-hwsim
$(call KernelPackage/mac80211/Default)
TITLE:=mac80211 HW simulation device
DEPENDS+= +kmod-mac80211 +@DRIVER_11N_SUPPORT
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/mac80211_hwsim.ko
AUTOLOAD:=$(call AutoProbe,mac80211_hwsim)
endef
define KernelPackage/net-libipw
$(call KernelPackage/mac80211/Default)
TITLE:=libipw for ipw2100 and ipw2200
DEPENDS:=@PCI_SUPPORT +kmod-crypto-core +kmod-crypto-arc4 +kmod-crypto-aes +<API key> +kmod-lib80211 +kmod-cfg80211 +@DRIVER_WEXT_SUPPORT
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ipw2x00/libipw.ko
AUTOLOAD:=$(call AutoProbe,libipw)
endef
define KernelPackage/net-libipw/description
Hardware independent IEEE 802.11 networking stack for ipw2100 and ipw2200.
endef
IPW2100_NAME:=ipw2100-fw
IPW2100_VERSION:=1.3
define Download/net-ipw2100
URL:=http://bughost.org/firmware/
FILE:=$(IPW2100_NAME)-$(IPW2100_VERSION).tgz
MD5SUM=<API key>
endef
$(eval $(call Download,net-ipw2100))
define KernelPackage/net-ipw2100
$(call KernelPackage/mac80211/Default)
TITLE:=Intel IPW2100 driver
DEPENDS:=@PCI_SUPPORT +kmod-net-libipw
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ipw2x00/ipw2100.ko
AUTOLOAD:=$(call AutoProbe,ipw2100)
endef
define KernelPackage/net-ipw2100/description
Kernel support for Intel IPW2100
Includes:
- ipw2100
endef
IPW2200_NAME:=ipw2200-fw
IPW2200_VERSION:=3.1
define Download/net-ipw2200
URL:=http://bughost.org/firmware/
FILE:=$(IPW2200_NAME)-$(IPW2200_VERSION).tgz
MD5SUM=<API key>
endef
$(eval $(call Download,net-ipw2200))
define KernelPackage/net-ipw2200
$(call KernelPackage/mac80211/Default)
TITLE:=Intel IPW2200 driver
DEPENDS:=@PCI_SUPPORT +kmod-net-libipw
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ipw2x00/ipw2200.ko
AUTOLOAD:=$(call AutoProbe,ipw2200)
endef
define KernelPackage/net-ipw2200/description
Kernel support for Intel IPW2200
Includes:
- ipw2200
endef
define KernelPackage/net-hermes
$(call KernelPackage/mac80211/Default)
TITLE:=Hermes 802.11b chipset support
DEPENDS:=@PCI_SUPPORT||PCMCIA_SUPPORT +kmod-cfg80211 +@DRIVER_WEXT_SUPPORT
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/orinoco/orinoco.ko
AUTOLOAD:=$(call AutoProbe,orinoco)
endef
define KernelPackage/net-hermes/description
Kernel support for Hermes 802.11b chipsets
endef
define KernelPackage/net-hermes-pci
$(call KernelPackage/mac80211/Default)
TITLE:=Intersil Prism 2.5 PCI support
DEPENDS:=@PCI_SUPPORT +kmod-net-hermes
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/orinoco/orinoco_pci.ko
AUTOLOAD:=$(call AutoProbe,orinoco_pci)
endef
define KernelPackage/net-hermes-pci/description
Kernel modules for Intersil Prism 2.5 PCI support
endef
define KernelPackage/net-hermes-plx
$(call KernelPackage/mac80211/Default)
TITLE:=PLX9052 based PCI adaptor
DEPENDS:=@PCI_SUPPORT +kmod-net-hermes
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/orinoco/orinoco_plx.ko
AUTOLOAD:=$(call AutoProbe,orinoco_plx)
endef
define KernelPackage/net-hermes-plx/description
Kernel modules for Hermes in PLX9052 based PCI adaptors
endef
define KernelPackage/net-hermes-pcmcia
$(call KernelPackage/mac80211/Default)
TITLE:=Hermes based PCMCIA adaptors
DEPENDS:=@PCMCIA_SUPPORT +kmod-net-hermes @BROKEN
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/orinoco/orinoco_cs.ko
AUTOLOAD:=$(call AutoProbe,orinoco_cs)
endef
define KernelPackage/net-hermes-pcmcia/description
Kernel modules for Hermes based PCMCIA adaptors
endef
define KernelPackage/iwlagn
$(call KernelPackage/mac80211/Default)
DEPENDS:= +kmod-mac80211 @PCI_SUPPORT +@DRIVER_11N_SUPPORT
TITLE:=Intel AGN Wireless support
FILES:= \
$(PKG_BUILD_DIR)/drivers/net/wireless/iwlwifi/iwlwifi.ko \
$(PKG_BUILD_DIR)/drivers/net/wireless/iwlwifi/dvm/iwldvm.ko
AUTOLOAD:=$(call AutoProbe,iwlwifi iwldvm)
MENU:=1
endef
define KernelPackage/iwlagn/description
iwlagn kernel module for Intel 5000/5150/1000/6000/6050/6005/6030/100 support
endef
define KernelPackage/iwlagn/config
if PACKAGE_kmod-iwlagn
config IWL5000_FW
bool "Intel 5000 Firmware"
default y
help
Download and install firmware for:
Intel Wireless WiFi 5100AGN, 5300AGN, and 5350AGN
config IWL5150_FW
bool "Intel 5150 Firmware"
default y
help
Download and install firmware for:
Intel Wireless WiFi 5150AGN
config IWL1000_FW
bool "Intel 1000 Firmware"
default y
help
Download and install firmware for:
Intel Centrino Wireless-N 1000
config IWL6000_FW
bool "Intel 6000 Firmware"
default y
help
Download and install firmware for:
Intel Centrino Ultimate-N 6300 and Advanced-N 6200
config IWL6050_FW
bool "Intel 6050 Firmware"
default y
help
Download and install firmware for:
Intel Centrino Advanced-N + WiMAX 6250 and Wireless-N + WiMAX 6150
config IWL6005_FW
bool "Intel 6005 Firmware"
default y
help
Download and install firmware for:
Intel Centrino Advanced-N 6205
config IWL6030_FW
bool "Intel 6030 Firmware"
default y
help
Download and install firmware for:
Intel Centrino Advanced-N 6230, Wireless-N 1030, Wireless-N 130 and Advanced-N 6235
config IWL7260_FW
bool "Intel 7260 Firmware"
default y
help
Download and install firmware for:
Intel Dual Band Wireless-N 7260 and Intel Dual Band Wireless-AC 7260
config IWL7265_FW
bool "Intel 7265 Firmware"
default y
help
Download and install firmware for:
Intel Wireless 7265
config IWL100_FW
bool "Intel 100 Firmware"
default y
help
Download and install firmware for:
Intel Centrino Wireless-N 100
config IWL2000_FW
bool "Intel 2000 Firmware"
default y
help
Download and install firmware for:
Intel Centrino Wireless-N 2200
config IWL2030_FW
bool "Intel 2030 Firmware"
default y
help
Download and install firmware for:
Intel Centrino Wireless-N 2230
config IWL105_FW
bool "Intel 105 Firmware"
default y
help
Download and install firmware for:
Intel Centrino Wireless-N 105
config IWL135_FW
bool "Intel 135 Firmware"
default y
help
Download and install firmware for:
Intel Centrino Wireless-N 135
config IWL3160_FW
bool "Intel 3160 Firmware"
default y
help
Download and install firmware for:
Intel Wireless 3160
endif
endef
define KernelPackage/iwl-legacy
$(call KernelPackage/mac80211/Default)
DEPENDS:= +kmod-mac80211 @PCI_SUPPORT
TITLE:=Intel legacy Wireless support
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/iwlegacy/iwlegacy.ko
AUTOLOAD:=$(call AutoProbe,iwlegacy)
endef
define KernelPackage/iwl-legacy/description
iwl-legacy kernel module for legacy Intel wireless support
endef
define KernelPackage/iwl3945
$(call KernelPackage/mac80211/Default)
DEPENDS:= +kmod-mac80211 +kmod-iwl-legacy
TITLE:=Intel iwl3945 Wireless support
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/iwlegacy/iwl3945.ko
AUTOLOAD:=$(call AutoProbe,iwl3945)
endef
define KernelPackage/iwl3945/description
iwl3945 kernel module for Intel 3945 support
endef
define KernelPackage/iwl4965
$(call KernelPackage/mac80211/Default)
DEPENDS:= +kmod-mac80211 +kmod-iwl-legacy +@DRIVER_11N_SUPPORT
TITLE:=Intel iwl4965 Wireless support
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/iwlegacy/iwl4965.ko
AUTOLOAD:=$(call AutoProbe,iwl4965)
endef
define KernelPackage/iwl4965/description
iwl4965 kernel module for Intel 4965 support
endef
define KernelPackage/mwl8k
$(call KernelPackage/mac80211/Default)
TITLE:=Driver for Marvell TOPDOG 802.11 Wireless cards
URL:=http://wireless.kernel.org/en/users/Drivers/mwl8k
DEPENDS+= @PCI_SUPPORT +kmod-mac80211 +@DRIVER_11N_SUPPORT
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/mwl8k.ko
AUTOLOAD:=$(call AutoProbe,mwl8k)
endef
define KernelPackage/mwl8k/description
Kernel modules for Marvell TOPDOG 802.11 Wireless cards
endef
define KernelPackage/mwifiex-pcie
$(call KernelPackage/mac80211/Default)
TITLE:=Driver for Marvell 802.11n/802.11ac PCIe Wireless cards
URL:=http://wireless.kernel.org/en/users/Drivers/mwifiex
DEPENDS+= @PCI_SUPPORT +kmod-mac80211 +@DRIVER_11N_SUPPORT
FILES:= \
$(PKG_BUILD_DIR)/drivers/net/wireless/mwifiex/mwifiex.ko \
$(PKG_BUILD_DIR)/drivers/net/wireless/mwifiex/mwifiex_pcie.ko
AUTOLOAD:=$(call AutoProbe,mwifiex_pcie)
endef
define KernelPackage/mwifiex-pcie/description
Kernel modules for Marvell 802.11n/802.11ac PCIe Wireless cards
endef
define KernelPackage/wlcore
$(call KernelPackage/mac80211/Default)
TITLE:=TI common driver part
DEPENDS+= @TARGET_omap +kmod-mac80211 +@DRIVER_11N_SUPPORT
FILES:= \
$(PKG_BUILD_DIR)/drivers/net/wireless/ti/wlcore/wlcore.ko \
$(PKG_BUILD_DIR)/drivers/net/wireless/ti/wlcore/wlcore_sdio.ko
AUTOLOAD:=$(call AutoProbe,wlcore wlcore_sdio)
endef
define KernelPackage/wlcore/description
This module contains some common parts needed by TI Wireless drivers.
endef
define KernelPackage/wl12xx
$(call KernelPackage/mac80211/Default)
TITLE:=Driver for TI WL12xx
URL:=http://wireless.kernel.org/en/users/Drivers/wl12xx
DEPENDS+= +kmod-wlcore
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ti/wl12xx/wl12xx.ko
AUTOLOAD:=$(call AutoProbe,wl12xx)
endef
define KernelPackage/wl12xx/description
Kernel modules for TI WL12xx
endef
define KernelPackage/wl18xx
$(call KernelPackage/mac80211/Default)
TITLE:=Driver for TI WL18xx
URL:=http://wireless.kernel.org/en/users/Drivers/wl18xx
DEPENDS+= +kmod-wlcore
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/ti/wl18xx/wl18xx.ko
AUTOLOAD:=$(call AutoProbe,wl18xx)
endef
define KernelPackage/wl18xx/description
Kernel modules for TI WL18xx
endef
#Broadcom firmware
ifneq ($(CONFIG_B43_FW_6_30),)
PKG_B43_FWV4_NAME:=broadcom-wl
<API key>:=6.30.163.46
PKG_B43_FWV4_OBJECT:=$(PKG_B43_FWV4_NAME)-$(<API key>).wl_apsta.o
PKG_B43_FWV4_SOURCE:=$(PKG_B43_FWV4_NAME)-$(<API key>).tar.bz2
<API key>:=http:
PKG_B43_FWV4_MD5SUM:=<API key>
else
ifneq ($(CONFIG_B43_FW_5_10),)
PKG_B43_FWV4_NAME:=broadcom-wl
<API key>:=5.10.56.27.3
PKG_B43_FWV4_OBJECT:=$(PKG_B43_FWV4_NAME)-$(<API key>)/driver/wl_apsta/wl_prebuilt.o
PKG_B43_FWV4_SOURCE:=$(PKG_B43_FWV4_NAME)-$(<API key>)_mipsel.tar.bz2
<API key>:=http://mirror2.openwrt.org/sources/
PKG_B43_FWV4_MD5SUM:=<API key>
else
ifneq ($(CONFIG_B43_FW_4_178),)
PKG_B43_FWV4_NAME:=broadcom-wl
<API key>:=4.178.10.4
PKG_B43_FWV4_OBJECT:=$(PKG_B43_FWV4_NAME)-$(<API key>)/linux/wl_apsta.o
PKG_B43_FWV4_SOURCE:=$(PKG_B43_FWV4_NAME)-$(<API key>).tar.bz2
<API key>:=http://mirror2.openwrt.org/sources/
PKG_B43_FWV4_MD5SUM:=<API key>
else
ifneq ($(<API key>),)
PKG_B43_FWV4_NAME:=broadcom-wl
<API key>:=5.100.138
PKG_B43_FWV4_OBJECT:=$(PKG_B43_FWV4_NAME)-$(<API key>)/linux/wl_apsta.o
PKG_B43_FWV4_SOURCE:=$(PKG_B43_FWV4_NAME)-$(<API key>).tar.bz2
<API key>:=http:
PKG_B43_FWV4_MD5SUM:=<API key>
else
PKG_B43_FWV4_NAME:=broadcom-wl
<API key>:=4.150.10.5
PKG_B43_FWV4_OBJECT:=$(PKG_B43_FWV4_NAME)-$(<API key>)/driver/wl_apsta_mimo.o
PKG_B43_FWV4_SOURCE:=$(PKG_B43_FWV4_NAME)-$(<API key>).tar.bz2
<API key>:=http://mirror2.openwrt.org/sources/
PKG_B43_FWV4_MD5SUM:=<API key>
endif
endif
endif
endif
ifneq ($(<API key>),)
PKG_B43_FWV4_NAME:=broadcom-wl
<API key>:=5.2
PKG_B43_FWV4_OBJECT:=openfwwf-$(<API key>)
PKG_B43_FWV4_SOURCE:=openfwwf-$(<API key>).tar.gz
<API key>:=http:
PKG_B43_FWV4_MD5SUM:=<API key>
endif
PKG_B43_FWV3_NAME:=wl_apsta
<API key>:=3.130.20.0
PKG_B43_FWV3_SOURCE:=$(PKG_B43_FWV3_NAME)-$(<API key>).o
<API key>:=http://downloads.openwrt.org/sources/
PKG_B43_FWV3_MD5SUM:=<API key>
define Download/b43
FILE:=$(PKG_B43_FWV4_SOURCE)
URL:=$(<API key>)
MD5SUM:=$(PKG_B43_FWV4_MD5SUM)
endef
$(eval $(call Download,b43))
define Download/b43legacy
FILE:=$(PKG_B43_FWV3_SOURCE)
URL:=$(<API key>)
MD5SUM:=$(PKG_B43_FWV3_MD5SUM)
endef
$(eval $(call Download,b43legacy))
define KernelPackage/b43
$(call KernelPackage/mac80211/Default)
TITLE:=Broadcom 43xx wireless support
URL:=http://linuxwireless.org/en/users/Drivers/b43
KCONFIG:= \
CONFIG_HW_RANDOM=y
# Depend on PCI_SUPPORT to make sure we can select kmod-bcma or kmod-ssb
DEPENDS += \
@PCI_SUPPORT +kmod-mac80211 \
$(if $(<API key>),+kmod-ssb) \
$(if $(<API key>),+kmod-bcma)
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/b43/b43.ko
AUTOLOAD:=$(call AutoProbe,b43)
MENU:=1
endef
define KernelPackage/b43/config
config PACKAGE_B43_USE_SSB
select PACKAGE_kmod-ssb
tristate
depends on !TARGET_brcm47xx && !TARGET_brcm63xx
default PACKAGE_kmod-b43 if <API key>
default PACKAGE_kmod-b43 if <API key>
config <API key>
select PACKAGE_kmod-bcma
tristate
depends on !TARGET_brcm47xx
default PACKAGE_kmod-b43 if <API key>
default PACKAGE_kmod-b43 if <API key>
if PACKAGE_kmod-b43
choice
prompt "b43 firmware version"
default B43_FW_5_100_138
help
This option allows you to select the version of the b43 firmware.
config B43_FW_4_150
bool "Firmware 410.2160 from driver 4.150.10.5 (old stable)"
help
Old stable firmware for BCM43xx devices.
If unsure, select this.
config B43_FW_4_178
bool "Firmware 478.104 from driver 4.178.10.4"
help
Older firmware for BCM43xx devices.
If unsure, select the "stable" firmware.
config B43_FW_5_10
bool "Firmware 508.1084 from driver 5.10.56.27"
help
Older firmware for BCM43xx devices.
If unsure, select the "stable" firmware.
config B43_FW_5_100_138
bool "Firmware 666.2 from driver 5.100.138 (stable)"
help
The currently default firmware for BCM43xx devices.
This firmware currently gets most of the testing and is needed for some N-PHY devices.
If unsure, select the this firmware.
config B43_FW_6_30
bool "Firmware 784.2 from driver 6.30.163.46 (experimental)"
help
Newer experimental firmware for BCM43xx devices.
This firmware is mostly untested.
If unsure, select the "stable" firmware.
config B43_OPENFIRMWARE
bool "Open FirmWare for WiFi networks"
help
Opensource firmware for BCM43xx devices.
Do _not_ select this, unless you know what you are doing.
The Opensource firmware is not suitable for embedded devices, yet.
It does not support QoS, which is bad for AccessPoints.
It does not support hardware crypto acceleration, which is a showstopper
for embedded devices with low CPU resources.
If unsure, select the "stable" firmware.
endchoice
config B43_FW_SQUASH
bool "Remove unnecessary firmware files"
depends on !B43_OPENFIRMWARE
default y
help
This options allows you to remove unnecessary b43 firmware files
from the final rootfs image. This can reduce the rootfs size by
up to 200k.
If unsure, say Y.
config <API key>
string "Core revisions to include"
depends on B43_FW_SQUASH
default "5,6,7,8,9,10,11,13,15" if <API key>
default "16,28,29,30" if <API key>
default "5,6,7,8,9,10,11,13,15,16,28,29,30"
help
This is a comma seperated list of core revision numbers.
Example (keep files for rev5 only):
5
Example (keep files for rev5 and rev11):
5,11
config <API key>
string "PHY types to include"
depends on B43_FW_SQUASH
default "G,LP" if <API key>
default "N,HT" if <API key>
default "G,LP,N,HT"
help
This is a comma seperated list of PHY types:
A => A-PHY
AG => Dual A-PHY G-PHY
G => G-PHY
LP => LP-PHY
N => N-PHY
HT => HT-PHY
LCN => LCN-PHY
LCN40 => LCN40-PHY
AC => AC-PHY
Example (keep files for G-PHY only):
G
Example (keep files for G-PHY and N-PHY):
G,N
choice
prompt "Supported buses"
default <API key>
help
This allows choosing buses that b43 should support.
config <API key>
depends on !<API key> && !<API key>
bool "BCMA and SSB"
config <API key>
depends on !<API key>
bool "BCMA only"
config <API key>
depends on !<API key>
bool "SSB only"
endchoice
config PACKAGE_B43_DEBUG
bool "Enable debug output and debugfs for b43"
default n
help
Enable additional debug output and runtime sanity checks for b43
and enables the debugfs interface.
If unsure, say N.
config PACKAGE_B43_PIO
bool "Enable support for PIO transfer mode"
default n
help
Enable support for using PIO instead of DMA. Unless you have DMA
transfer problems you don't need this.
If unsure, say N.
config PACKAGE_B43_PHY_G
bool "Enable support for G-PHYs"
default n if <API key>
default y
help
Enable support for G-PHY. This includes support for the following devices:
PCI: BCM4306, BCM4311, BCM4318
SoC: BCM5352E, BCM4712
If unsure, say Y.
config PACKAGE_B43_PHY_N
bool "Enable support for N-PHYs"
default n if <API key>
default y
help
Enable support for N-PHY. This includes support for the following devices:
PCI: BCM4321, BCM4322, BCM43222, BCM43224, BCM43225
SoC: BCM4716, BCM4717, BCM4718
Currently only 11g speed is available.
If unsure, say Y.
config PACKAGE_B43_PHY_LP
bool "Enable support for LP-PHYs"
default n if <API key>
default y
help
Enable support for LP-PHY. This includes support for the following devices:
PCI: BCM4312
SoC: BCM5354
If unsure, say Y.
config PACKAGE_B43_PHY_HT
bool "Enable support for HT-PHYs"
default n if <API key>
default y
help
Enable support for HT-PHY. This includes support for the following devices:
PCI: BCM4331
Currently only 11g speed is available.
If unsure, say Y.
config PACKAGE_B43_PHY_LCN
bool "Enable support for LCN-PHYs"
depends on BROKEN
default n
help
Currently broken.
If unsure, say N.
endif
endef
define KernelPackage/b43/description
Kernel module for Broadcom 43xx wireless support (mac80211 stack) new
endef
define KernelPackage/b43legacy
$(call KernelPackage/mac80211/Default)
TITLE:=Broadcom 43xx-legacy wireless support
URL:=http://linuxwireless.org/en/users/Drivers/b43
KCONFIG:= \
CONFIG_HW_RANDOM=y
DEPENDS+= +kmod-mac80211 +!(TARGET_brcm47xx||TARGET_brcm63xx):kmod-ssb
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/b43legacy/b43legacy.ko
AUTOLOAD:=$(call AutoProbe,b43legacy)
MENU:=1
endef
define KernelPackage/b43legacy/config
if <API key>
config B43LEGACY_FW_SQUASH
bool "Remove unnecessary firmware files"
default y
help
This options allows you to remove unnecessary b43legacy firmware files
from the final rootfs image. This can reduce the rootfs size by
up to 50k.
If unsure, say Y.
config <API key>
string "Core revisions to include"
depends on B43LEGACY_FW_SQUASH
default "1,2,3,4"
help
This is a comma seperated list of core revision numbers.
Example (keep files for rev4 only):
4
Example (keep files for rev2 and rev4):
2,4
endif
endef
define KernelPackage/b43legacy/description
Kernel module for Broadcom 43xx-legacy wireless support (mac80211 stack) new
endef
define KernelPackage/brcmutil
$(call KernelPackage/mac80211/Default)
TITLE:=Broadcom IEEE802.11n common driver parts
URL:=http://linuxwireless.org/en/users/Drivers/brcm80211
DEPENDS+=@PCI_SUPPORT||USB_SUPPORT
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/brcm80211/brcmutil/brcmutil.ko
AUTOLOAD:=$(call AutoProbe,brcmutil)
MENU:=1
endef
define KernelPackage/brcmutil/description
This module contains some common parts needed by Broadcom Wireless drivers brcmsmac and brcmfmac.
endef
define KernelPackage/brcmutil/config
if <API key>
config <API key>
bool "Broadcom wireless driver debugging"
help
Say Y, if you want to debug brcmsmac and brcmfmac wireless driver.
endif
endef
<API key>:=broadcom-wl
<API key>:=5.100.138
<API key>:=$(<API key>)-$(<API key>)/linux/wl_apsta.o
<API key>:=$(<API key>)-$(<API key>).tar.bz2
<API key>:=http:
<API key>:=<API key>
define Download/brcmsmac
FILE:=$(<API key>)
URL:=$(<API key>)
MD5SUM:=$(<API key>)
endef
$(eval $(call Download,brcmsmac))
define KernelPackage/brcmsmac
$(call KernelPackage/mac80211/Default)
TITLE:=Broadcom IEEE802.11n PCIe SoftMAC WLAN driver
URL:=http://linuxwireless.org/en/users/Drivers/brcm80211
DEPENDS+= +kmod-mac80211 +@DRIVER_11N_SUPPORT +!TARGET_brcm47xx:kmod-bcma +kmod-lib-cordic +kmod-lib-crc8 +kmod-brcmutil
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/brcm80211/brcmsmac/brcmsmac.ko
AUTOLOAD:=$(call AutoProbe,brcmsmac)
MENU:=1
endef
define KernelPackage/brcmsmac/description
Kernel module for Broadcom IEEE802.11n PCIe Wireless cards
endef
define KernelPackage/brcmsmac/config
if <API key>
config <API key>
bool "Use firmware extracted from broadcom proprietary driver"
default y
help
Instead of using the official brcmsmac firmware a firmware
version 666.2 extracted from the proprietary Broadcom driver
is used. This is needed to get core rev 17 used in bcm4716
to work.
If unsure, say Y.
endif
endef
define KernelPackage/brcmfmac
$(call KernelPackage/mac80211/Default)
TITLE:=Broadcom IEEE802.11n USB FullMAC WLAN driver
URL:=http://linuxwireless.org/en/users/Drivers/brcm80211
DEPENDS+= @USB_SUPPORT +kmod-usb-core +kmod-cfg80211 +@DRIVER_11N_SUPPORT +kmod-brcmutil
FILES:=$(PKG_BUILD_DIR)/drivers/net/wireless/brcm80211/brcmfmac/brcmfmac.ko
AUTOLOAD:=$(call AutoProbe,brcmfmac)
endef
define KernelPackage/brcmfmac/description
Kernel module for Broadcom IEEE802.11n USB Wireless cards
endef
config_package=$(if $(CONFIG_PACKAGE_kmod-$(1)),m)
config-y:= \
WLAN \
NL80211_TESTMODE \
CFG80211_WEXT \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
<API key> \
config-$(call config_package,cfg80211) += CFG80211
config-$(call config_package,mac80211) += MAC80211
config-$(<API key>) += MAC80211_MESH
ifdef <API key>
config-y += \
CFG80211_DEBUGFS \
MAC80211_DEBUGFS \
ATH9K_DEBUGFS \
ATH9K_HTC_DEBUGFS \
ATH10K_DEBUGFS \
CARL9170_DEBUGFS \
ATH5K_DEBUG
endif
config-$(call config_package,lib80211) += LIB80211 LIB80211_CRYPT_WEP LIB80211_CRYPT_CCMP LIB80211_CRYPT_TKIP
config-$(call config_package,ath) += ATH_CARDS ATH_COMMON
config-$(<API key>) += ATH_DEBUG ATH10K_DEBUG
config-$(<API key>) += ATH9K_DFS_CERTIFIED <API key>
config-$(call config_package,ath9k) += ATH9K
config-$(call config_package,ath9k-common) += ATH9K_COMMON
config-$(<API key>) += ATH9K_AHB
config-$(CONFIG_PCI) += ATH9K_PCI
config-$(<API key>) += ATH_USER_REGD
config-$(<API key>) += ATH9K_PCOEM
config-$(call config_package,ath9k-htc) += ATH9K_HTC
config-$(call config_package,ath10k) += ATH10K ATH10K_PCI
config-$(call config_package,ath5k) += ATH5K
ifdef <API key>
config-y += ATH5K_AHB
else
config-y += ATH5K_PCI
endif
config-$(call config_package,carl9170) += CARL9170
config-$(call config_package,b43) += B43
config-$(<API key>) += <API key>
config-$(<API key>) += B43_BUSES_BCMA
config-$(<API key>) += B43_BUSES_SSB
config-$(<API key>) += B43_PHY_G
config-$(<API key>) += B43_PHY_N
config-$(<API key>) += B43_PHY_LP
config-$(<API key>) += B43_PHY_HT
config-$(<API key>) += B43_PIO
config-$(<API key>) += B43_DEBUG
config-$(call config_package,b43legacy) += B43LEGACY
config-y += B43LEGACY_DMA_MODE
config-$(call config_package,brcmutil) += BRCMUTIL
config-$(call config_package,brcmsmac) += BRCMSMAC
config-$(call config_package,brcmfmac) += BRCMFMAC
config-y += BRCMFMAC_USB
config-$(<API key>) += BRCMDBG
config-$(call config_package,mac80211-hwsim) += MAC80211_HWSIM
config-$(call config_package,rt2x00-lib) += RT2X00 RT2X00_LIB
config-$(call config_package,rt2x00-pci) += RT2X00_LIB_PCI
config-$(call config_package,rt2x00-mmio) += RT2X00_LIB_MMIO
config-$(call config_package,rt2x00-usb) += RT2X00_LIB_USB
config-$(<API key>) += RT2X00_LIB_DEBUGFS
config-$(<API key>) += RT2X00_DEBUG
config-$(call config_package,rt2400-pci) += RT2400PCI
config-$(call config_package,rt2500-pci) += RT2500PCI
config-$(call config_package,rt2500-usb) += RT2500USB
config-$(call config_package,rt61-pci) += RT61PCI
config-$(call config_package,rt73-usb) += RT73USB
config-$(call config_package,rt2800-lib) += RT2800_LIB
config-$(call config_package,rt2800-soc) += RT2800SOC
config-$(call config_package,rt2800-pci) += RT2800PCI
config-y += RT2800PCI_RT33XX RT2800PCI_RT35XX RT2800PCI_RT53XX RT2800PCI_RT3290
config-$(call config_package,rt2800-usb) += RT2800USB
config-y += RT2800USB_RT33XX RT2800USB_RT35XX RT2800USB_RT3573 RT2800USB_RT53XX RT2800USB_RT55XX
config-$(call config_package,iwl-legacy) += IWLEGACY
config-$(call config_package,iwl3945) += IWL3945
config-$(call config_package,iwl4965) += IWL4965
config-$(call config_package,iwlagn) += IWLWIFI IWLDVM
config-$(call config_package,net-libipw) += LIBIPW
config-$(call config_package,net-ipw2100) += IPW2100
config-$(call config_package,net-ipw2200) += IPW2200
config-$(call config_package,p54-common) += P54_COMMON
config-$(call config_package,p54-pci) += P54_PCI
config-$(call config_package,p54-usb) += P54_USB
config-$(call config_package,p54-spi) += P54_SPI
config-$(call config_package,net-hermes) += HERMES
config-$(call config_package,net-hermes-pci) += PCI_HERMES
config-$(call config_package,net-hermes-plx) += PLX_HERMES
config-$(call config_package,net-hermes-pcmcia) += PCMCIA_HERMES
config-y += HERMES_PRISM
config-$(call config_package,adm8211) += ADM8211
config-$(call config_package,libertas-sd) += LIBERTAS LIBERTAS_SDIO
config-$(call config_package,libertas-usb) += LIBERTAS LIBERTAS_USB
config-$(call config_package,mwl8k) += MWL8K
config-$(call config_package,mwifiex-pcie) += MWIFIEX MWIFIEX_PCIE
config-$(call config_package,rtl8180) += RTL8180
config-$(call config_package,rtl8187) += RTL8187
config-$(call config_package,wlcore) += WLCORE WLCORE_SDIO
config-$(call config_package,wl12xx) += WL12XX
config-$(call config_package,wl18xx) += WL18XX
config-y += WL_TI <API key>
config-$(call config_package,zd1211rw) += ZD1211RW
config-$(call config_package,rtlwifi) += RTL_CARDS RTLWIFI
config-$(call config_package,rtlwifi-pci) += RTLWIFI_PCI
config-$(call config_package,rtlwifi-usb) += RTLWIFI_USB
config-$(call config_package,rtl8192c-common) += RTL8192C_COMMON
config-$(call config_package,rtl8192ce) += RTL8192CE
config-$(call config_package,rtl8192se) += RTL8192SE
config-$(call config_package,rtl8192de) += RTL8192DE
config-$(call config_package,rtl8192cu) += RTL8192CU
config-$(<API key>) += RTLWIFI_DEBUG
config-$(<API key>) += MAC80211_LEDS B43_LEDS B43LEGACY_LEDS
MAKE_OPTS:= -C "$(PKG_BUILD_DIR)" \
CROSS_COMPILE="$(KERNEL_CROSS)" \
ARCH="$(LINUX_KARCH)" \
EXTRA_CFLAGS="-I$(PKG_BUILD_DIR)/include" \
KLIB_BUILD="$(LINUX_DIR)" \
MODPROBE=true \
KLIB=$(TARGET_MODULES_DIR) \
KERNEL_SUBLEVEL=$(lastword $(subst ., ,$(KERNEL_PATCHVER))) \
<API key>=
ifneq ($(findstring c,$(OPENWRT_VERBOSE)),)
MAKE_OPTS += V=1
endif
define ConfigVars
$(subst $(space),,$(foreach opt,$(config-$(1)),CPTCFG_$(opt)=$(1)
))
endef
define mac80211_config
$(call ConfigVars,m)$(call ConfigVars,y)
endef
$(eval $(call shexport,mac80211_config))
define Build/Prepare
rm -rf $(PKG_BUILD_DIR)
mkdir -p $(PKG_BUILD_DIR)
$(PKG_UNPACK)
$(Build/Patch)
$(TAR) -C $(PKG_BUILD_DIR) -xzf $(DL_DIR)/$(IPW2100_NAME)-$(IPW2100_VERSION).tgz
$(TAR) -C $(PKG_BUILD_DIR) -xzf $(DL_DIR)/$(IPW2200_NAME)-$(IPW2200_VERSION).tgz
$(TAR) -C $(PKG_BUILD_DIR) -xjf $(DL_DIR)/$(ZD1211FW_NAME)-$(ZD1211FW_VERSION).tar.bz2
$(TAR) -C $(PKG_BUILD_DIR) -xjf $(DL_DIR)/$(<API key>)
$(TAR) -C $(PKG_BUILD_DIR) -xjf $(DL_DIR)/$(<API key>)
rm -rf \
$(PKG_BUILD_DIR)/include/linux/ssb \
$(PKG_BUILD_DIR)/include/linux/bcma \
$(PKG_BUILD_DIR)/include/net/bluetooth
rm -f \
$(PKG_BUILD_DIR)/include/linux/cordic.h \
$(PKG_BUILD_DIR)/include/linux/crc8.h \
$(PKG_BUILD_DIR)/include/linux/eeprom_93cx6.h \
$(PKG_BUILD_DIR)/include/linux/wl12xx.h \
$(PKG_BUILD_DIR)/include/linux/spi/libertas_spi.h \
$(PKG_BUILD_DIR)/include/net/ieee80211.h
echo 'compat-wireless-$(PKG_VERSION)-$(PKG_RELEASE)-$(REVISION)' > $(PKG_BUILD_DIR)/compat_version
$(CP) ./files/regdb.txt $(PKG_BUILD_DIR)/net/wireless/db.txt
endef
ifneq ($(<API key>)$(<API key>),)
define Build/Compile/kmod
rm -rf $(PKG_BUILD_DIR)/modules
+$(MAKE) $(PKG_JOBS) $(MAKE_OPTS) modules
endef
endif
define Build/Configure
cmp $(PKG_BUILD_DIR)/include/linux/ath9k_platform.h $(LINUX_DIR)/include/linux/ath9k_platform.h
cmp $(PKG_BUILD_DIR)/include/linux/ath5k_platform.h $(LINUX_DIR)/include/linux/ath5k_platform.h
cmp $(PKG_BUILD_DIR)/include/linux/rt2x00_platform.h $(LINUX_DIR)/include/linux/rt2x00_platform.h
endef
define Build/Compile
$(SH_FUNC) var2file "$(call shvar,mac80211_config)" $(PKG_BUILD_DIR)/.config
$(MAKE) $(MAKE_OPTS) allnoconfig
$(call Build/Compile/kmod)
endef
define Build/InstallDev
mkdir -p \
$(1)/usr/include/mac80211 \
$(1)/usr/include/mac80211-backport \
$(1)/usr/include/mac80211/ath \
$(1)/usr/include/net/mac80211
|
#include <linux/moduleparam.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/hdreg.h>
#include <linux/kdev_t.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/scatterlist.h>
#include <linux/string_helpers.h>
#include <linux/delay.h>
#include <linux/capability.h>
#include <linux/compat.h>
#include <linux/mmc/ioctl.h>
#include <linux/mmc/card.h>
#include <linux/mmc/host.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/sd.h>
#include <asm/uaccess.h>
#include "queue.h"
MODULE_ALIAS("mmc:block");
#ifdef MODULE_PARAM_PREFIX
#undef MODULE_PARAM_PREFIX
#endif
#define MODULE_PARAM_PREFIX "mmcblk."
#define <API key> 113
#define <API key> 0x00
#define <API key> 0x01
#define <API key> 0x80
#define <API key> 0x81
#define <API key> 0x88
#define MMC_BLK_TIMEOUT_MS (30 * 1000) /* 30 sec timeout */
#define <API key> 240000 /* msec */
#define mmc_req_rel_wr(req) (((req->cmd_flags & REQ_FUA) || \
(req->cmd_flags & REQ_META)) && \
(rq_data_dir(req) == WRITE))
#define PACKED_CMD_VER 0x01
#define PACKED_CMD_WR 0x02
#define <API key> 5000
#define <API key>(stats, reason) \
do { \
if (stats->enabled) \
stats->pack_stop_reason[reason]++; \
} while (0)
#define <API key> 17
#define <API key> 5
#define <API key> 2
#define <API key> 5
#define <API key> 100
static DEFINE_MUTEX(block_mutex);
/*
* The defaults come from config options but can be overriden by module
* or bootarg options.
*/
static int perdev_minors = <API key>;
/*
* We've only got one major, so number of mmcblk devices is
* limited to 256 / number of minors per device.
*/
static int max_devices;
/* 256 minors, so at most 256 separate devices */
static DECLARE_BITMAP(dev_use, 256);
static DECLARE_BITMAP(name_use, 256);
/*
* There is one mmc_blk_data per slot.
*/
struct mmc_blk_data {
spinlock_t lock;
struct gendisk *disk;
struct mmc_queue queue;
struct list_head part;
unsigned int flags;
#define MMC_BLK_CMD23 (1 << 0) /* Can do SET_BLOCK_COUNT for multiblock */
#define MMC_BLK_REL_WR (1 << 1) /* MMC Reliable write support */
unsigned int usage;
unsigned int read_only;
unsigned int part_type;
unsigned int name_idx;
unsigned int reset_done;
#define MMC_BLK_READ BIT(0)
#define MMC_BLK_WRITE BIT(1)
#define MMC_BLK_DISCARD BIT(2)
#define MMC_BLK_SECDISCARD BIT(3)
/*
* Only set in main mmc_blk_data associated
* with mmc_card with mmc_set_drvdata, and keeps
* track of the current selected device partition.
*/
unsigned int part_curr;
struct device_attribute force_ro;
struct device_attribute power_ro_lock;
struct device_attribute <API key>;
struct device_attribute <API key>;
struct device_attribute no_pack_for_random;
int area_type;
};
static DEFINE_MUTEX(open_lock);
enum {
MMC_PACKED_N_IDX = -1,
MMC_PACKED_N_ZERO,
MMC_PACKED_N_SINGLE,
};
module_param(perdev_minors, int, 0444);
MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device");
static inline void <API key>(struct mmc_queue_req *mqrq)
{
mqrq->packed_cmd = MMC_PACKED_NONE;
mqrq->packed_num = MMC_PACKED_N_ZERO;
}
static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk)
{
struct mmc_blk_data *md;
mutex_lock(&open_lock);
md = disk->private_data;
if (md && md->usage == 0)
md = NULL;
if (md)
md->usage++;
mutex_unlock(&open_lock);
return md;
}
static inline int mmc_get_devidx(struct gendisk *disk)
{
int devidx = disk->first_minor / perdev_minors;
return devidx;
}
static void mmc_blk_put(struct mmc_blk_data *md)
{
mutex_lock(&open_lock);
md->usage
if (md->usage == 0) {
int devidx = mmc_get_devidx(md->disk);
blk_cleanup_queue(md->queue.queue);
__clear_bit(devidx, dev_use);
put_disk(md->disk);
kfree(md);
}
mutex_unlock(&open_lock);
}
static ssize_t power_ro_lock_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
struct mmc_card *card = md->queue.card;
int locked = 0;
if (card->ext_csd.boot_ro_lock & <API key>)
locked = 2;
else if (card->ext_csd.boot_ro_lock & <API key>)
locked = 1;
ret = snprintf(buf, PAGE_SIZE, "%d\n", locked);
return ret;
}
static ssize_t power_ro_lock_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int ret;
struct mmc_blk_data *md, *part_md;
struct mmc_card *card;
unsigned long set;
if (kstrtoul(buf, 0, &set))
return -EINVAL;
if (set != 1)
return count;
md = mmc_blk_get(dev_to_disk(dev));
card = md->queue.card;
mmc_claim_host(card->host);
ret = mmc_switch(card, <API key>, EXT_CSD_BOOT_WP,
card->ext_csd.boot_ro_lock |
<API key>,
card->ext_csd.part_time);
if (ret)
pr_err("%s: Locking boot partition ro until next power on failed: %d\n", md->disk->disk_name, ret);
else
card->ext_csd.boot_ro_lock |= <API key>;
mmc_release_host(card->host);
if (!ret) {
pr_info("%s: Locking boot partition ro until next power on\n",
md->disk->disk_name);
set_disk_ro(md->disk, 1);
list_for_each_entry(part_md, &md->part, part)
if (part_md->area_type == <API key>) {
pr_info("%s: Locking boot partition ro until next power on\n", part_md->disk->disk_name);
set_disk_ro(part_md->disk, 1);
}
}
mmc_blk_put(md);
return count;
}
static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
int ret;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
ret = snprintf(buf, PAGE_SIZE, "%d",
get_disk_ro(dev_to_disk(dev)) ^
md->read_only);
mmc_blk_put(md);
return ret;
}
static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int ret;
char *end;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
unsigned long set = simple_strtoul(buf, &end, 0);
if (end == buf) {
ret = -EINVAL;
goto out;
}
set_disk_ro(dev_to_disk(dev), set || md->read_only);
ret = count;
out:
mmc_blk_put(md);
return ret;
}
static ssize_t
<API key>(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
int <API key>;
int ret;
<API key> = md->queue.<API key>;
ret = snprintf(buf, PAGE_SIZE, "%d\n", <API key>);
mmc_blk_put(md);
return ret;
}
static ssize_t
<API key>(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int value;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
sscanf(buf, "%d", &value);
if (value >= 0)
md->queue.<API key> = value;
mmc_blk_put(md);
return count;
}
static ssize_t
<API key>(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
struct mmc_card *card = md->queue.card;
int ret;
if (!card)
ret = -EINVAL;
else
ret = snprintf(buf, PAGE_SIZE, "%d\n",
card->bkops_info.<API key>);
mmc_blk_put(md);
return ret;
}
static ssize_t
<API key>(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int value;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
struct mmc_card *card = md->queue.card;
unsigned int card_size;
int ret = count;
if (!card) {
ret = -EINVAL;
goto exit;
}
sscanf(buf, "%d", &value);
if ((value <= 0) || (value >= 100)) {
ret = -EINVAL;
goto exit;
}
card_size = (unsigned int)get_capacity(md->disk);
if (card_size <= 0) {
ret = -EINVAL;
goto exit;
}
card->bkops_info.<API key> = value;
card->bkops_info.<API key> =
(card_size * value) / 100;
pr_debug("%s: size_percentage = %d, min_sectors = %d",
mmc_hostname(card->host),
card->bkops_info.<API key>,
card->bkops_info.<API key>);
exit:
mmc_blk_put(md);
return count;
}
static ssize_t
<API key>(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
int ret;
ret = snprintf(buf, PAGE_SIZE, "%d\n", md->queue.no_pack_for_random);
mmc_blk_put(md);
return ret;
}
static ssize_t
<API key>(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int value;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
struct mmc_card *card = md->queue.card;
int ret = count;
if (!card) {
ret = -EINVAL;
goto exit;
}
sscanf(buf, "%d", &value);
if (value < 0) {
pr_err("%s: value %d is not valid. old value remains = %d",
mmc_hostname(card->host), value,
md->queue.no_pack_for_random);
ret = -EINVAL;
goto exit;
}
md->queue.no_pack_for_random = (value > 0) ? true : false;
pr_debug("%s: no_pack_for_random: new value = %d",
mmc_hostname(card->host),
md->queue.no_pack_for_random);
exit:
mmc_blk_put(md);
return ret;
}
static int mmc_blk_open(struct block_device *bdev, fmode_t mode)
{
struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk);
int ret = -ENXIO;
mutex_lock(&block_mutex);
if (md) {
if (md->usage == 2)
check_disk_change(bdev);
ret = 0;
if ((mode & FMODE_WRITE) && md->read_only) {
mmc_blk_put(md);
ret = -EROFS;
}
}
mutex_unlock(&block_mutex);
return ret;
}
static int mmc_blk_release(struct gendisk *disk, fmode_t mode)
{
struct mmc_blk_data *md = disk->private_data;
mutex_lock(&block_mutex);
mmc_blk_put(md);
mutex_unlock(&block_mutex);
return 0;
}
static int
mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16);
geo->heads = 4;
geo->sectors = 16;
return 0;
}
struct mmc_blk_ioc_data {
struct mmc_ioc_cmd ic;
unsigned char *buf;
u64 buf_bytes;
};
static struct mmc_blk_ioc_data *<API key>(
struct mmc_ioc_cmd __user *user)
{
struct mmc_blk_ioc_data *idata;
int err;
idata = kzalloc(sizeof(*idata), GFP_KERNEL);
if (!idata) {
err = -ENOMEM;
goto out;
}
if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) {
err = -EFAULT;
goto idata_err;
}
idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks;
if (idata->buf_bytes > MMC_IOC_MAX_BYTES) {
err = -EOVERFLOW;
goto idata_err;
}
if (!idata->buf_bytes)
return idata;
idata->buf = kzalloc(idata->buf_bytes, GFP_KERNEL);
if (!idata->buf) {
err = -ENOMEM;
goto idata_err;
}
if (copy_from_user(idata->buf, (void __user *)(unsigned long)
idata->ic.data_ptr, idata->buf_bytes)) {
err = -EFAULT;
goto copy_err;
}
return idata;
copy_err:
kfree(idata->buf);
idata_err:
kfree(idata);
out:
return ERR_PTR(err);
}
struct scatterlist *mmc_blk_get_sg(struct mmc_card *card,
unsigned char *buf, int *sg_len, int size)
{
struct scatterlist *sg;
struct scatterlist *sl;
int total_sec_cnt, sec_cnt;
int max_seg_size, len;
total_sec_cnt = size;
max_seg_size = card->host->max_seg_size;
len = (size - 1 + max_seg_size) / max_seg_size;
sl = kmalloc(sizeof(struct scatterlist) * len, GFP_KERNEL);
if (!sl) {
return NULL;
}
sg = (struct scatterlist *)sl;
sg_init_table(sg, len);
while (total_sec_cnt) {
if (total_sec_cnt < max_seg_size)
sec_cnt = total_sec_cnt;
else
sec_cnt = max_seg_size;
sg_set_page(sg, virt_to_page(buf), sec_cnt, offset_in_page(buf));
buf = buf + sec_cnt;
total_sec_cnt = total_sec_cnt - sec_cnt;
if (total_sec_cnt == 0)
break;
sg = sg_next(sg);
}
if (sg)
sg_mark_end(sg);
*sg_len = len;
return sl;
}
static int mmc_blk_ioctl_cmd(struct block_device *bdev,
struct mmc_ioc_cmd __user *ic_ptr)
{
struct mmc_blk_ioc_data *idata;
struct mmc_blk_data *md;
struct mmc_card *card;
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct mmc_request mrq = {NULL};
struct scatterlist *sg = 0;
int err = 0;
/*
* The caller must have CAP_SYS_RAWIO, and must be calling this on the
* whole block device, not on a partition. This prevents overspray
* between sibling partitions.
*/
if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
return -EPERM;
idata = <API key>(ic_ptr);
if (IS_ERR(idata))
return PTR_ERR(idata);
md = mmc_blk_get(bdev->bd_disk);
if (!md) {
err = -EINVAL;
goto blk_err;
}
card = md->queue.card;
if (IS_ERR(card)) {
err = PTR_ERR(card);
goto cmd_done;
}
cmd.opcode = idata->ic.opcode;
cmd.arg = idata->ic.arg;
cmd.flags = idata->ic.flags;
if (idata->buf_bytes) {
int len;
data.blksz = idata->ic.blksz;
data.blocks = idata->ic.blocks;
sg = mmc_blk_get_sg(card, idata->buf, &len, idata->buf_bytes);
data.sg = sg;
data.sg_len = len;
if (idata->ic.write_flag)
data.flags = MMC_DATA_WRITE;
else
data.flags = MMC_DATA_READ;
/* data.flags must already be set before doing this. */
<API key>(&data, card);
/* Allow overriding the timeout_ns for empirical tuning. */
if (idata->ic.data_timeout_ns)
data.timeout_ns = idata->ic.data_timeout_ns;
if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) {
/*
* Pretend this is a data transfer and rely on the
* host driver to compute timeout. When all host
* drivers support cmd.cmd_timeout for R1B, this
* can be changed to:
*
* mrq.data = NULL;
* cmd.cmd_timeout = idata->ic.cmd_timeout_ms;
*/
data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000;
}
mrq.data = &data;
}
mrq.cmd = &cmd;
mmc_claim_host(card->host);
if (idata->ic.is_acmd) {
err = mmc_app_cmd(card->host, card);
if (err)
goto cmd_rel_host;
}
mmc_wait_for_req(card->host, &mrq);
if (cmd.error) {
dev_err(mmc_dev(card->host), "%s: cmd error %d\n",
__func__, cmd.error);
err = cmd.error;
goto cmd_rel_host;
}
if (data.error) {
dev_err(mmc_dev(card->host), "%s: data error %d\n",
__func__, data.error);
err = data.error;
goto cmd_rel_host;
}
/*
* According to the SD specs, some commands require a delay after
* issuing the command.
*/
if (idata->ic.postsleep_min_us)
usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us);
if (copy_to_user(&(ic_ptr->response), cmd.resp, sizeof(cmd.resp))) {
err = -EFAULT;
goto cmd_rel_host;
}
if (!idata->ic.write_flag) {
if (copy_to_user((void __user *)(unsigned long) idata->ic.data_ptr,
idata->buf, idata->buf_bytes)) {
err = -EFAULT;
goto cmd_rel_host;
}
}
cmd_rel_host:
mmc_release_host(card->host);
cmd_done:
mmc_blk_put(md);
if (sg)
kfree(sg);
blk_err:
kfree(idata->buf);
kfree(idata);
return err;
}
static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
int ret = -EINVAL;
if (cmd == MMC_IOC_CMD)
ret = mmc_blk_ioctl_cmd(bdev, (struct mmc_ioc_cmd __user *)arg);
return ret;
}
#ifdef CONFIG_COMPAT
static int <API key>(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg));
}
#endif
static const struct <API key> mmc_bdops = {
.open = mmc_blk_open,
.release = mmc_blk_release,
.getgeo = mmc_blk_getgeo,
.owner = THIS_MODULE,
.ioctl = mmc_blk_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = <API key>,
#endif
};
static inline int mmc_blk_part_switch(struct mmc_card *card,
struct mmc_blk_data *md)
{
int ret;
struct mmc_blk_data *main_md = mmc_get_drvdata(card);
if (main_md->part_curr == md->part_type)
return 0;
if (mmc_card_mmc(card)) {
u8 part_config = card->ext_csd.part_config;
part_config &= ~<API key>;
part_config |= md->part_type;
ret = mmc_switch(card, <API key>,
EXT_CSD_PART_CONFIG, part_config,
card->ext_csd.part_time);
if (ret)
return ret;
card->ext_csd.part_config = part_config;
}
main_md->part_curr = md->part_type;
return 0;
}
static u32 <API key>(struct mmc_card *card)
{
int err;
u32 result;
__be32 *blocks;
struct mmc_request mrq = {NULL};
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct scatterlist sg;
cmd.opcode = MMC_APP_CMD;
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, 0);
if (err)
return (u32)-1;
if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD))
return (u32)-1;
memset(&cmd, 0, sizeof(struct mmc_command));
cmd.opcode = <API key>;
cmd.arg = 0;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
data.blksz = 4;
data.blocks = 1;
data.flags = MMC_DATA_READ;
data.sg = &sg;
data.sg_len = 1;
<API key>(&data, card);
mrq.cmd = &cmd;
mrq.data = &data;
blocks = kmalloc(4, GFP_KERNEL);
if (!blocks)
return (u32)-1;
sg_init_one(&sg, blocks, 4);
mmc_wait_for_req(card->host, &mrq);
result = ntohl(*blocks);
kfree(blocks);
if (cmd.error || data.error)
result = (u32)-1;
return result;
}
static int send_stop(struct mmc_card *card, u32 *status)
{
struct mmc_command cmd = {0};
int err;
cmd.opcode = <API key>;
cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, 5);
if (err == 0)
*status = cmd.resp[0];
return err;
}
static int get_card_status(struct mmc_card *card, u32 *status, int retries)
{
struct mmc_command cmd = {0};
int err;
cmd.opcode = MMC_SEND_STATUS;
if (!mmc_host_is_spi(card->host))
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, retries);
if (err == 0)
*status = cmd.resp[0];
return err;
}
#define ERR_NOMEDIUM 3
#define ERR_RETRY 2
#define ERR_ABORT 1
#define ERR_CONTINUE 0
static int mmc_blk_cmd_error(struct request *req, const char *name, int error,
bool status_valid, u32 status)
{
switch (error) {
case -EILSEQ:
/* response crc error, retry the r/w cmd */
pr_err("%s: %s sending %s command, card status %
req->rq_disk->disk_name, "response CRC error",
name, status);
return ERR_RETRY;
case -ETIMEDOUT:
pr_err("%s: %s sending %s command, card status %
req->rq_disk->disk_name, "timed out", name, status);
/* If the status cmd initially failed, retry the r/w cmd */
if (!status_valid) {
pr_err("%s: status not valid, retrying timeout\n", req->rq_disk->disk_name);
return ERR_RETRY;
}
if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND)) {
pr_err("%s: command error, retrying timeout\n", req->rq_disk->disk_name);
return ERR_RETRY;
}
/* Otherwise abort the command */
pr_err("%s: not retrying timeout\n", req->rq_disk->disk_name);
return ERR_ABORT;
default:
/* We don't understand the error code the driver gave us */
pr_err("%s: unknown error %d sending read/write command, card status %
req->rq_disk->disk_name, error, status);
return ERR_ABORT;
}
}
static int <API key>(struct mmc_card *card, struct request *req,
struct mmc_blk_request *brq, int *ecc_err, int *gen_err)
{
bool <API key> = true;
u32 status, stop_status = 0;
int err, retry;
if (mmc_card_removed(card))
return ERR_NOMEDIUM;
/*
* Try to get card status which indicates both the card state
* and why there was no response. If the first attempt fails,
* we can't be sure the returned status is for the r/w command.
*/
for (retry = 2; retry >= 0; retry
err = get_card_status(card, &status, 0);
if (!err)
break;
<API key> = false;
pr_err("%s: error %d sending status command, %sing\n",
req->rq_disk->disk_name, err, retry ? "retry" : "abort");
}
/* We couldn't get a response from the card. Give up. */
if (err) {
/* Check if the card is removed */
if (<API key>(card->host))
return ERR_NOMEDIUM;
return ERR_ABORT;
}
/* Flag ECC errors */
if ((status & R1_CARD_ECC_FAILED) ||
(brq->stop.resp[0] & R1_CARD_ECC_FAILED) ||
(brq->cmd.resp[0] & R1_CARD_ECC_FAILED))
*ecc_err = 1;
/* Flag General errors */
if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
if ((status & R1_ERROR) ||
(brq->stop.resp[0] & R1_ERROR)) {
pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n",
req->rq_disk->disk_name, __func__,
brq->stop.resp[0], status);
*gen_err = 1;
}
/*
* Check the current card state. If it is in some data transfer
* mode, tell it to stop (and hopefully transition back to TRAN.)
*/
if (R1_CURRENT_STATE(status) == R1_STATE_DATA ||
R1_CURRENT_STATE(status) == R1_STATE_RCV) {
err = send_stop(card, &stop_status);
if (err)
pr_err("%s: error %d sending stop command\n",
req->rq_disk->disk_name, err);
/*
* If the stop cmd also timed out, the card is probably
* not present, so abort. Other errors are bad news too.
*/
if (err)
return ERR_ABORT;
if (stop_status & R1_CARD_ECC_FAILED)
*ecc_err = 1;
if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
if (stop_status & R1_ERROR) {
pr_err("%s: %s: general error sending stop command, stop cmd response %
req->rq_disk->disk_name, __func__,
stop_status);
*gen_err = 1;
}
}
/* Check for set block count errors */
if (brq->sbc.error)
return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error,
<API key>, status);
/* Check for r/w command errors */
if (brq->cmd.error)
return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error,
<API key>, status);
/* Data errors */
if (!brq->stop.error)
return ERR_CONTINUE;
/* Now for stop errors. These aren't fatal to the transfer. */
pr_err("%s: error %d sending stop command, original cmd response %#x, card status %#x\n",
req->rq_disk->disk_name, brq->stop.error,
brq->cmd.resp[0], status);
/*
* Subsitute in our own stop status as this will give the error
* state which happened during the execution of the r/w command.
*/
if (stop_status) {
brq->stop.resp[0] = stop_status;
brq->stop.error = 0;
}
return ERR_CONTINUE;
}
static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
int type)
{
int err;
if (md->reset_done & type)
return -EEXIST;
md->reset_done |= type;
err = mmc_hw_reset(host);
/* Ensure we switch back to the correct partition */
if (err != -EOPNOTSUPP) {
struct mmc_blk_data *main_md = mmc_get_drvdata(host->card);
int part_err;
main_md->part_curr = main_md->part_type;
part_err = mmc_blk_part_switch(host->card, md);
if (part_err) {
/*
* We have failed to get back into the correct
* partition, so we need to abort the whole request.
*/
return -ENODEV;
}
}
return err;
}
static inline void <API key>(struct mmc_blk_data *md, int type)
{
md->reset_done &= ~type;
}
static int <API key>(struct mmc_queue *mq, struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
unsigned int from, nr, arg;
int err = 0, type = MMC_BLK_DISCARD;
if (!mmc_can_erase(card)) {
err = -EOPNOTSUPP;
goto out;
}
from = blk_rq_pos(req);
nr = blk_rq_sectors(req);
if (card->ext_csd.bkops_en)
card->bkops_info.sectors_changed += blk_rq_sectors(req);
if (mmc_can_discard(card))
arg = MMC_DISCARD_ARG;
else if (mmc_can_trim(card))
arg = MMC_TRIM_ARG;
else
arg = MMC_ERASE_ARG;
retry:
if (card->quirks & <API key>) {
err = mmc_switch(card, <API key>,
<API key>,
arg == MMC_TRIM_ARG ?
<API key> :
<API key>,
0);
if (err)
goto out;
}
err = mmc_erase(card, from, nr, arg);
out:
if (err == -EIO && !mmc_blk_reset(md, card->host, type))
goto retry;
if (!err)
<API key>(md, type);
blk_end_request(req, err, blk_rq_bytes(req));
return err ? 0 : 1;
}
static int <API key>(struct mmc_queue *mq,
struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
unsigned int from, nr, arg;
int err = 0, type = MMC_BLK_SECDISCARD;
if (!(<API key>(card))) {
err = -EOPNOTSUPP;
goto out;
}
from = blk_rq_pos(req);
nr = blk_rq_sectors(req);
if (mmc_can_trim(card) && !<API key>(card, from, nr))
arg = <API key>;
else
arg = <API key>;
retry:
if (card->quirks & <API key>) {
err = mmc_switch(card, <API key>,
<API key>,
arg == <API key> ?
<API key> :
<API key>,
0);
if (err)
goto out_retry;
}
err = mmc_erase(card, from, nr, arg);
if (err == -EIO)
goto out_retry;
if (err)
goto out;
if (arg == <API key>) {
if (card->quirks & <API key>) {
err = mmc_switch(card, <API key>,
<API key>,
<API key>,
0);
if (err)
goto out_retry;
}
err = mmc_erase(card, from, nr, <API key>);
if (err == -EIO)
goto out_retry;
if (err)
goto out;
}
out_retry:
if (err && !mmc_blk_reset(md, card->host, type))
goto retry;
if (!err)
<API key>(md, type);
out:
blk_end_request(req, err, blk_rq_bytes(req));
return err ? 0 : 1;
}
static int <API key>(struct mmc_queue *mq,
struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
int err = 0;
BUG_ON(!card);
BUG_ON(!card->host);
if (!(mmc_can_sanitize(card) &&
(card->host->caps2 & MMC_CAP2_SANITIZE))) {
pr_warning("%s: %s - SANITIZE is not supported\n",
mmc_hostname(card->host), __func__);
err = -EOPNOTSUPP;
goto out;
}
pr_debug("%s: %s - SANITIZE IN PROGRESS...\n",
mmc_hostname(card->host), __func__);
err = <API key>(card, <API key>,
<API key>, 1,
<API key>);
if (err)
pr_err("%s: %s - mmc_switch() with "
"<API key> failed. err=%d\n",
mmc_hostname(card->host), __func__, err);
pr_debug("%s: %s - SANITIZE COMPLETED\n", mmc_hostname(card->host),
__func__);
out:
blk_end_request(req, err, blk_rq_bytes(req));
return err ? 0 : 1;
}
static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
int ret = 0;
ret = mmc_flush_cache(card);
if (ret)
ret = -EIO;
blk_end_request_all(req, ret);
return ret ? 0 : 1;
}
/*
* Reformat current write as a reliable write, supporting
* both legacy and the enhanced reliable write MMC cards.
* In each transfer we'll handle only as much as a single
* reliable write can handle, thus finish the request in
* partial completions.
*/
static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
struct mmc_card *card,
struct request *req)
{
if (!(card->ext_csd.rel_param & <API key>)) {
/* Legacy mode imposes restrictions on transfers. */
if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors))
brq->data.blocks = 1;
if (brq->data.blocks > card->ext_csd.rel_sectors)
brq->data.blocks = card->ext_csd.rel_sectors;
else if (brq->data.blocks < card->ext_csd.rel_sectors)
brq->data.blocks = 1;
}
}
#define CMD_ERRORS \
(R1_OUT_OF_RANGE | /* Command argument out of range */ \
R1_ADDRESS_ERROR | /* Misaligned address */ \
R1_BLOCK_LEN_ERROR | /* Transferred block length incorrect */\
R1_WP_VIOLATION | /* Tried to write to protected block */ \
R1_CC_ERROR | /* Card controller error */ \
R1_ERROR) /* General/unknown error */
static int mmc_blk_err_check(struct mmc_card *card,
struct mmc_async_req *areq)
{
struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req,
mmc_active);
struct mmc_blk_request *brq = &mq_mrq->brq;
struct request *req = mq_mrq->req;
int ecc_err = 0, gen_err = 0;
/*
* sbc.error indicates a problem with the set block count
* command. No data will have been transferred.
*
* cmd.error indicates a problem with the r/w command. No
* data will have been transferred.
*
* stop.error indicates a problem with the stop command. Data
* may have been transferred, or may still be transferring.
*/
if (brq->sbc.error || brq->cmd.error || brq->stop.error ||
brq->data.error) {
switch (<API key>(card, req, brq, &ecc_err, &gen_err)) {
case ERR_RETRY:
return MMC_BLK_RETRY;
case ERR_ABORT:
return MMC_BLK_ABORT;
case ERR_NOMEDIUM:
return MMC_BLK_NOMEDIUM;
case ERR_CONTINUE:
break;
}
}
/*
* Check for errors relating to the execution of the
* initial command - such as address errors. No data
* has been transferred.
*/
if (brq->cmd.resp[0] & CMD_ERRORS) {
pr_err("%s: r/w command failed, status = %
req->rq_disk->disk_name, brq->cmd.resp[0]);
return MMC_BLK_ABORT;
}
/*
* Everything else is either success, or a data error of some
* kind. If it was a write, we may have transitioned to
* program mode, which we have to wait for it to complete.
*/
if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) {
u32 status;
unsigned long timeout;
/* Check stop command response */
if (brq->stop.resp[0] & R1_ERROR) {
pr_err("%s: %s: general error sending stop command, stop cmd response %
req->rq_disk->disk_name, __func__,
brq->stop.resp[0]);
gen_err = 1;
}
timeout = jiffies + msecs_to_jiffies(MMC_BLK_TIMEOUT_MS);
do {
int err = get_card_status(card, &status, 5);
if (err) {
pr_err("%s: error %d requesting status\n",
req->rq_disk->disk_name, err);
return MMC_BLK_CMD_ERR;
}
if (status & R1_ERROR) {
pr_err("%s: %s: general error sending status command, card status %
req->rq_disk->disk_name, __func__,
status);
gen_err = 1;
}
/* Timeout if the device never becomes ready for data
* and never leaves the program state.
*/
if (time_after(jiffies, timeout)) {
pr_err("%s: Card stuck in programming state!"\
" %s %s\n", mmc_hostname(card->host),
req->rq_disk->disk_name, __func__);
return MMC_BLK_CMD_ERR;
}
/*
* Some cards mishandle the status bits,
* so make sure to check both the busy
* indication and the card state.
*/
} while (!(status & R1_READY_FOR_DATA) ||
(R1_CURRENT_STATE(status) == R1_STATE_PRG));
}
/* if general error occurs, retry the write operation. */
if (gen_err) {
pr_warn("%s: retrying write for general error\n",
req->rq_disk->disk_name);
return MMC_BLK_RETRY;
}
if (brq->data.error) {
pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n",
req->rq_disk->disk_name, brq->data.error,
(unsigned)blk_rq_pos(req),
(unsigned)blk_rq_sectors(req),
brq->cmd.resp[0], brq->stop.resp[0]);
if (rq_data_dir(req) == READ) {
if (ecc_err)
return MMC_BLK_ECC_ERR;
return MMC_BLK_DATA_ERR;
} else {
return MMC_BLK_CMD_ERR;
}
}
if (!brq->data.bytes_xfered)
return MMC_BLK_RETRY;
if (mq_mrq->packed_cmd != MMC_PACKED_NONE) {
if (unlikely(brq->data.blocks << 9 != brq->data.bytes_xfered))
return MMC_BLK_PARTIAL;
else
return MMC_BLK_SUCCESS;
}
if (blk_rq_bytes(req) != brq->data.bytes_xfered)
return MMC_BLK_PARTIAL;
return MMC_BLK_SUCCESS;
}
/*
* <API key>() - re-insert request back to the scheduler
* @areq: request to re-insert.
*
* Request may be packed or single. When fails to reinsert request, it will be
* requeued to the the dispatch queue.
*/
static void <API key>(struct mmc_async_req *areq)
{
struct request *prq;
int ret = 0;
struct mmc_queue_req *mq_rq;
struct request_queue *q;
mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
q = mq_rq->req->q;
if (mq_rq->packed_cmd != MMC_PACKED_NONE) {
while (!list_empty(&mq_rq->packed_list)) {
/* return requests in reverse order */
prq = list_entry_rq(mq_rq->packed_list.prev);
list_del_init(&prq->queuelist);
spin_lock_irq(q->queue_lock);
ret = <API key>(q, prq);
if (ret) {
blk_requeue_request(q, prq);
spin_unlock_irq(q->queue_lock);
goto reinsert_error;
}
spin_unlock_irq(q->queue_lock);
}
} else {
spin_lock_irq(q->queue_lock);
ret = <API key>(q, mq_rq->req);
if (ret)
blk_requeue_request(q, mq_rq->req);
spin_unlock_irq(q->queue_lock);
}
return;
reinsert_error:
pr_err("%s: <API key>() failed (%d)",
mq_rq->req->rq_disk->disk_name, ret);
/*
* -EIO will be reported for this request and rest of packed_list.
* Urgent request will be proceeded anyway, while upper layer
* responsibility to re-send failed requests
*/
while (!list_empty(&mq_rq->packed_list)) {
prq = list_entry_rq(mq_rq->packed_list.next);
list_del_init(&prq->queuelist);
spin_lock_irq(q->queue_lock);
blk_requeue_request(q, prq);
spin_unlock_irq(q->queue_lock);
}
}
/*
* <API key>() - update of the stopped request
* @card: the MMC card associated with the request.
* @areq: interrupted async request.
*
* Get stopped request state from card and update successfully done part of
* the request by setting packed_fail_idx. The packed_fail_idx is index of
* first uncompleted request in packed request list, for non-packed request
* packed_fail_idx remains unchanged.
*
* Returns: MMC_BLK_SUCCESS for success, MMC_BLK_ABORT otherwise
*/
static int <API key>(struct mmc_card *card,
struct mmc_async_req *areq)
{
int ret = MMC_BLK_SUCCESS;
u8 *ext_csd;
int correctly_done;
struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req,
mmc_active);
struct request *prq;
u8 req_index = 0;
if (mq_rq->packed_cmd == MMC_PACKED_NONE)
return MMC_BLK_SUCCESS;
ext_csd = kmalloc(512, GFP_KERNEL);
if (!ext_csd)
return MMC_BLK_ABORT;
/* get correctly programmed sectors number from card */
ret = mmc_send_ext_csd(card, ext_csd);
if (ret) {
pr_err("%s: error %d reading ext_csd\n",
mmc_hostname(card->host), ret);
ret = MMC_BLK_ABORT;
goto exit;
}
correctly_done = card->ext_csd.data_sector_size *
(ext_csd[<API key> + 0] << 0 |
ext_csd[<API key> + 1] << 8 |
ext_csd[<API key> + 2] << 16 |
ext_csd[<API key> + 3] << 24);
list_for_each_entry(prq, &mq_rq->packed_list, queuelist) {
if ((correctly_done - (int)blk_rq_bytes(prq)) < 0) {
/* prq is not successfull */
mq_rq->packed_fail_idx = req_index;
break;
}
correctly_done -= blk_rq_bytes(prq);
req_index++;
}
exit:
kfree(ext_csd);
return ret;
}
static int <API key>(struct mmc_card *card,
struct mmc_async_req *areq)
{
struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req,
mmc_active);
struct request *req = mq_rq->req;
int err, check, status;
u8 ext_csd[512];
mq_rq->packed_retries
check = mmc_blk_err_check(card, areq);
err = get_card_status(card, &status, 0);
if (err) {
pr_err("%s: error %d sending status command\n",
req->rq_disk->disk_name, err);
return MMC_BLK_ABORT;
}
if (status & R1_EXCEPTION_EVENT) {
err = mmc_send_ext_csd(card, ext_csd);
if (err) {
pr_err("%s: error %d sending ext_csd\n",
req->rq_disk->disk_name, err);
return MMC_BLK_ABORT;
}
if ((ext_csd[<API key>] &
<API key>) &&
(ext_csd[<API key>] &
<API key>)) {
if (ext_csd[<API key>] &
<API key>) {
mq_rq->packed_fail_idx =
ext_csd[<API key>] - 1;
return MMC_BLK_PARTIAL;
}
}
}
return check;
}
static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
struct mmc_card *card,
int disable_multi,
struct mmc_queue *mq)
{
u32 readcmd, writecmd;
struct mmc_blk_request *brq = &mqrq->brq;
struct request *req = mqrq->req;
struct mmc_blk_data *md = mq->data;
bool do_data_tag;
/*
* Reliable writes are used to implement Forced Unit Access and
* REQ_META accesses, and are supported only on MMCs.
*
* XXX: this really needs a good explanation of why REQ_META
* is treated special.
*/
bool do_rel_wr = ((req->cmd_flags & REQ_FUA) ||
(req->cmd_flags & REQ_META)) &&
(rq_data_dir(req) == WRITE) &&
(md->flags & MMC_BLK_REL_WR);
memset(brq, 0, sizeof(struct mmc_blk_request));
brq->mrq.cmd = &brq->cmd;
brq->mrq.data = &brq->data;
brq->cmd.arg = blk_rq_pos(req);
if (!mmc_card_blockaddr(card))
brq->cmd.arg <<= 9;
brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
brq->data.blksz = 512;
brq->stop.opcode = <API key>;
brq->stop.arg = 0;
brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
brq->data.blocks = blk_rq_sectors(req);
brq->data.fault_injected = false;
/*
* The block layer doesn't support all sector count
* restrictions, so we need to be prepared for too big
* requests.
*/
if (brq->data.blocks > card->host->max_blk_count)
brq->data.blocks = card->host->max_blk_count;
if (brq->data.blocks > 1) {
/*
* After a read error, we redo the request one sector
* at a time in order to accurately determine which
* sectors can be read successfully.
*/
if (disable_multi)
brq->data.blocks = 1;
/* Some controllers can't do multiblock reads due to hw bugs */
if (card->host->caps2 & <API key> &&
rq_data_dir(req) == READ)
brq->data.blocks = 1;
}
if (brq->data.blocks > 1 || do_rel_wr) {
/* SPI multiblock writes terminate using a special
* token, not a STOP_TRANSMISSION request.
*/
if (!mmc_host_is_spi(card->host) ||
rq_data_dir(req) == READ)
brq->mrq.stop = &brq->stop;
readcmd = <API key>;
writecmd = <API key>;
} else {
brq->mrq.stop = NULL;
readcmd = <API key>;
writecmd = MMC_WRITE_BLOCK;
}
if (rq_data_dir(req) == READ) {
brq->cmd.opcode = readcmd;
brq->data.flags |= MMC_DATA_READ;
} else {
brq->cmd.opcode = writecmd;
brq->data.flags |= MMC_DATA_WRITE;
}
if (do_rel_wr)
mmc_apply_rel_rw(brq, card, req);
/*
* Data tag is used only during writing meta data to speed
* up write and any subsequent read of this meta data
*/
do_data_tag = (card->ext_csd.data_tag_unit_size) &&
(req->cmd_flags & REQ_META) &&
(rq_data_dir(req) == WRITE) &&
((brq->data.blocks * brq->data.blksz) >=
card->ext_csd.data_tag_unit_size);
/*
* Pre-defined multi-block transfers are preferable to
* open ended-ones (and necessary for reliable writes).
* However, it is not sufficient to just send CMD23,
* and avoid the final CMD12, as on an error condition
* CMD12 (stop) needs to be sent anyway. This, coupled
* with Auto-CMD23 enhancements provided by some
* hosts, means that the complexity of dealing
* with this is best left to the host. If CMD23 is
* supported by card and host, we'll fill sbc in and let
* the host deal with handling it correctly. This means
* that for hosts that don't expose MMC_CAP_CMD23, no
* change of behavior will be observed.
*
* N.B: Some MMC cards experience perf degradation.
* We'll avoid using CMD23-bounded multiblock writes for
* these, while retaining features like reliable writes.
*/
if ((md->flags & MMC_BLK_CMD23) && mmc_op_multi(brq->cmd.opcode) &&
(do_rel_wr || !(card->quirks & <API key>) ||
do_data_tag)) {
brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
brq->sbc.arg = brq->data.blocks |
(do_rel_wr ? (1 << 31) : 0) |
(do_data_tag ? (1 << 29) : 0);
brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
brq->mrq.sbc = &brq->sbc;
}
<API key>(&brq->data, card);
brq->data.sg = mqrq->sg;
brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
/*
* Adjust the sg list so it is the same size as the
* request.
*/
if (brq->data.blocks != blk_rq_sectors(req)) {
int i, data_size = brq->data.blocks << 9;
struct scatterlist *sg;
for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
data_size -= sg->length;
if (data_size <= 0) {
sg->length += data_size;
i++;
break;
}
}
brq->data.sg_len = i;
}
mqrq->mmc_active.mrq = &brq->mrq;
mqrq->mmc_active.cmd_flags = req->cmd_flags;
mqrq->mmc_active.err_check = mmc_blk_err_check;
mqrq->mmc_active.reinsert_req = <API key>;
mqrq->mmc_active.<API key> =
<API key>;
<API key>(mqrq);
}
/**
* <API key>() - disables packing mode
* @mq: MMC queue.
*
*/
void <API key>(struct mmc_queue *mq)
{
if (mq) {
mq->wr_packing_enabled = false;
mq-><API key> = 0;
}
}
EXPORT_SYMBOL(<API key>);
static int get_packed_trigger(int potential, struct mmc_card *card,
struct request *req, int curr_trigger)
{
static int num_mean_elements = 1;
static unsigned long mean_potential = <API key>;
unsigned int trigger = curr_trigger;
unsigned int <API key> = card->ext_csd.max_packed_writes;
/* scale down the upper bound to 75% */
<API key> = (<API key> * 3) / 4;
/*
* since the most common calls for this function are with small
* potential write values and since we don't want these calls to affect
* the packed trigger, set a lower bound and ignore calls with
* potential lower than that bound
*/
if (potential <= <API key>)
return trigger;
/*
* this is to prevent integer overflow in the following calculation:
* once every <API key> reset the algorithm
*/
if (num_mean_elements > <API key>) {
num_mean_elements = 1;
mean_potential = <API key>;
}
/*
* get next mean value based on previous mean value and current
* potential packed writes. Calculation is as follows:
* mean_pot[i+1] =
* ((mean_pot[i] * num_mean_elem) + potential)/(num_mean_elem + 1)
*/
mean_potential *= num_mean_elements;
/*
* add num_mean_elements so that the division of two integers doesn't
* lower mean_potential too much
*/
if (potential > mean_potential)
mean_potential += num_mean_elements;
mean_potential += potential;
/* this is for gaining more precision when dividing two integers */
mean_potential *= <API key>;
/* this completes the mean calculation */
mean_potential /= ++num_mean_elements;
mean_potential /= <API key>;
/*
* if current potential packed writes is greater than the mean potential
* then the heuristic is that the following workload will contain many
* write requests, therefore we lower the packed trigger. In the
* opposite case we want to increase the trigger in order to get less
* packing events.
*/
if (potential >= mean_potential)
trigger = (trigger <= <API key>) ?
<API key> : trigger - 1;
else
trigger = (trigger >= <API key>) ?
<API key> : trigger + 1;
/*
* an urgent read request indicates a packed list being interrupted
* by this read, therefore we aim for less packing, hence the trigger
* gets increased
*/
if (req && (req->cmd_flags & REQ_URGENT) && (rq_data_dir(req) == READ))
trigger += <API key>;
return trigger;
}
static void <API key>(struct mmc_queue *mq,
struct request *req)
{
struct mmc_host *host = mq->card->host;
int data_dir;
if (!(host->caps2 & MMC_CAP2_PACKED_WR))
return;
/*
* In case the packing control is not supported by the host, it should
* not have an effect on the write packing. Therefore we have to enable
* the write packing
*/
if (!(host->caps2 & <API key>)) {
mq->wr_packing_enabled = true;
return;
}
if (!req || (req && (req->cmd_flags & REQ_FLUSH))) {
if (mq-><API key> >
mq-><API key>)
mq->wr_packing_enabled = true;
mq-><API key> =
get_packed_trigger(mq-><API key>,
mq->card, req,
mq-><API key>);
mq-><API key> = 0;
return;
}
data_dir = rq_data_dir(req);
if (data_dir == READ) {
<API key>(mq);
mq-><API key> =
get_packed_trigger(mq-><API key>,
mq->card, req,
mq-><API key>);
mq-><API key> = 0;
mq->wr_packing_enabled = false;
return;
} else if (data_dir == WRITE) {
mq-><API key>++;
}
if (mq-><API key> >
mq-><API key>)
mq->wr_packing_enabled = true;
}
struct mmc_wr_pack_stats *<API key>(struct mmc_card *card)
{
if (!card)
return NULL;
return &card->wr_pack_stats;
}
EXPORT_SYMBOL(<API key>);
void <API key>(struct mmc_card *card)
{
int <API key> = 0;
if (!card || !card->wr_pack_stats.packing_events)
return;
<API key> = card->ext_csd.max_packed_writes;
spin_lock(&card->wr_pack_stats.lock);
memset(card->wr_pack_stats.packing_events, 0,
(<API key> + 1) *
sizeof(*card->wr_pack_stats.packing_events));
memset(&card->wr_pack_stats.pack_stop_reason, 0,
sizeof(card->wr_pack_stats.pack_stop_reason));
card->wr_pack_stats.enabled = true;
spin_unlock(&card->wr_pack_stats.lock);
}
EXPORT_SYMBOL(<API key>);
void <API key>(struct mmc_card *card)
{
int i;
int <API key> = 0;
if ((!card) || (!card->wr_pack_stats.packing_events))
return;
<API key> = card->ext_csd.max_packed_writes;
spin_lock(&card->wr_pack_stats.lock);
pr_info("%s: write packing statistics:\n",
mmc_hostname(card->host));
for (i = 1 ; i <= <API key> ; ++i) {
if (card->wr_pack_stats.packing_events[i] != 0)
pr_info("%s: Packed %d reqs - %d times\n",
mmc_hostname(card->host), i,
card->wr_pack_stats.packing_events[i]);
}
pr_info("%s: stopped packing due to the following reasons:\n",
mmc_hostname(card->host));
if (card->wr_pack_stats.pack_stop_reason[EXCEEDS_SEGMENTS])
pr_info("%s: %d times: exceedmax num of segments\n",
mmc_hostname(card->host),
card->wr_pack_stats.pack_stop_reason[EXCEEDS_SEGMENTS]);
if (card->wr_pack_stats.pack_stop_reason[EXCEEDS_SECTORS])
pr_info("%s: %d times: exceeding the max num of sectors\n",
mmc_hostname(card->host),
card->wr_pack_stats.pack_stop_reason[EXCEEDS_SECTORS]);
if (card->wr_pack_stats.pack_stop_reason[WRONG_DATA_DIR])
pr_info("%s: %d times: wrong data direction\n",
mmc_hostname(card->host),
card->wr_pack_stats.pack_stop_reason[WRONG_DATA_DIR]);
if (card->wr_pack_stats.pack_stop_reason[FLUSH_OR_DISCARD])
pr_info("%s: %d times: flush or discard\n",
mmc_hostname(card->host),
card->wr_pack_stats.pack_stop_reason[FLUSH_OR_DISCARD]);
if (card->wr_pack_stats.pack_stop_reason[EMPTY_QUEUE])
pr_info("%s: %d times: empty queue\n",
mmc_hostname(card->host),
card->wr_pack_stats.pack_stop_reason[EMPTY_QUEUE]);
if (card->wr_pack_stats.pack_stop_reason[REL_WRITE])
pr_info("%s: %d times: rel write\n",
mmc_hostname(card->host),
card->wr_pack_stats.pack_stop_reason[REL_WRITE]);
if (card->wr_pack_stats.pack_stop_reason[THRESHOLD])
pr_info("%s: %d times: Threshold\n",
mmc_hostname(card->host),
card->wr_pack_stats.pack_stop_reason[THRESHOLD]);
spin_unlock(&card->wr_pack_stats.lock);
}
EXPORT_SYMBOL(<API key>);
static u8 <API key>(struct mmc_queue *mq, struct request *req)
{
struct request_queue *q = mq->queue;
struct mmc_card *card = mq->card;
struct request *cur = req, *next = NULL;
struct mmc_blk_data *md = mq->data;
bool en_rel_wr = card->ext_csd.rel_param & <API key>;
unsigned int req_sectors = 0, phys_segments = 0;
unsigned int max_blk_count, max_phys_segs;
u8 put_back = 0;
u8 max_packed_rw = 0;
u8 reqs = 0;
struct mmc_wr_pack_stats *stats = &card->wr_pack_stats;
<API key>(mq->mqrq_cur);
if (!(md->flags & MMC_BLK_CMD23) ||
!card->ext_csd.packed_event_en)
goto no_packed;
if (!mq->wr_packing_enabled)
goto no_packed;
if ((rq_data_dir(cur) == WRITE) &&
(card->host->caps2 & MMC_CAP2_PACKED_WR))
max_packed_rw = card->ext_csd.max_packed_writes;
if (max_packed_rw == 0)
goto no_packed;
if (mmc_req_rel_wr(cur) &&
(md->flags & MMC_BLK_REL_WR) &&
!en_rel_wr)
goto no_packed;
if (mmc_large_sec(card) &&
!IS_ALIGNED(blk_rq_sectors(cur), 8))
goto no_packed;
max_blk_count = min(card->host->max_blk_count,
card->host->max_req_size >> 9);
if (unlikely(max_blk_count > 0xffff))
max_blk_count = 0xffff;
max_phys_segs = queue_max_segments(q);
req_sectors += blk_rq_sectors(cur);
phys_segments += cur->nr_phys_segments;
if (rq_data_dir(cur) == WRITE) {
req_sectors++;
phys_segments++;
}
spin_lock(&stats->lock);
while (reqs < max_packed_rw - 1) {
/* We should stop no-more packing its nopacked_period */
if ((card->host->caps2 & <API key>)
&& <API key>(mq->nopacked_period))
break;
spin_lock_irq(q->queue_lock);
next = blk_fetch_request(q);
spin_unlock_irq(q->queue_lock);
if (!next) {
<API key>(stats, EMPTY_QUEUE);
break;
}
if (mmc_large_sec(card) &&
!IS_ALIGNED(blk_rq_sectors(next), 8)) {
<API key>(stats, LARGE_SEC_ALIGN);
put_back = 1;
break;
}
if (next->cmd_flags & REQ_DISCARD ||
next->cmd_flags & REQ_FLUSH) {
<API key>(stats, FLUSH_OR_DISCARD);
put_back = 1;
break;
}
if (rq_data_dir(cur) != rq_data_dir(next)) {
<API key>(stats, WRONG_DATA_DIR);
put_back = 1;
break;
}
if (mmc_req_rel_wr(next) &&
(md->flags & MMC_BLK_REL_WR) &&
!en_rel_wr) {
<API key>(stats, REL_WRITE);
put_back = 1;
break;
}
req_sectors += blk_rq_sectors(next);
if (req_sectors > max_blk_count) {
if (stats->enabled)
stats->pack_stop_reason[EXCEEDS_SECTORS]++;
put_back = 1;
break;
}
phys_segments += next->nr_phys_segments;
if (phys_segments > max_phys_segs) {
<API key>(stats, EXCEEDS_SEGMENTS);
put_back = 1;
break;
}
if (mq->no_pack_for_random) {
if ((blk_rq_pos(cur) + blk_rq_sectors(cur)) !=
blk_rq_pos(next)) {
<API key>(stats, RANDOM);
put_back = 1;
break;
}
}
if (rq_data_dir(next) == WRITE) {
mq-><API key>++;
if (card->ext_csd.bkops_en)
card->bkops_info.sectors_changed +=
blk_rq_sectors(next);
}
list_add_tail(&next->queuelist, &mq->mqrq_cur->packed_list);
cur = next;
reqs++;
}
if (put_back) {
spin_lock_irq(q->queue_lock);
blk_requeue_request(q, next);
spin_unlock_irq(q->queue_lock);
}
if (stats->enabled) {
if (reqs + 1 <= card->ext_csd.max_packed_writes)
stats->packing_events[reqs + 1]++;
if (reqs + 1 == max_packed_rw)
<API key>(stats, THRESHOLD);
}
spin_unlock(&stats->lock);
if (reqs > 0) {
list_add(&req->queuelist, &mq->mqrq_cur->packed_list);
mq->mqrq_cur->packed_num = ++reqs;
mq->mqrq_cur->packed_retries = reqs;
return reqs;
}
no_packed:
<API key>(mq->mqrq_cur);
return 0;
}
static void <API key>(struct mmc_queue_req *mqrq,
struct mmc_card *card,
struct mmc_queue *mq)
{
struct mmc_blk_request *brq = &mqrq->brq;
struct request *req = mqrq->req;
struct request *prq;
struct mmc_blk_data *md = mq->data;
bool do_rel_wr, do_data_tag;
u32 *packed_cmd_hdr = mqrq->packed_cmd_hdr;
u8 i = 1;
mqrq->packed_cmd = MMC_PACKED_WRITE;
mqrq->packed_blocks = 0;
mqrq->packed_fail_idx = MMC_PACKED_N_IDX;
memset(packed_cmd_hdr, 0, sizeof(mqrq->packed_cmd_hdr));
packed_cmd_hdr[0] = (mqrq->packed_num << 16) |
(PACKED_CMD_WR << 8) | PACKED_CMD_VER;
/*
* Argument for each entry of packed group
*/
list_for_each_entry(prq, &mqrq->packed_list, queuelist) {
do_rel_wr = mmc_req_rel_wr(prq) && (md->flags & MMC_BLK_REL_WR);
do_data_tag = (card->ext_csd.data_tag_unit_size) &&
(prq->cmd_flags & REQ_META) &&
(rq_data_dir(prq) == WRITE) &&
((brq->data.blocks * brq->data.blksz) >=
card->ext_csd.data_tag_unit_size);
/* Argument of CMD23 */
packed_cmd_hdr[(i * 2)] =
(do_rel_wr ? <API key> : 0) |
(do_data_tag ? <API key> : 0) |
blk_rq_sectors(prq);
/* Argument of CMD18 or CMD25 */
packed_cmd_hdr[((i * 2)) + 1] =
mmc_card_blockaddr(card) ?
blk_rq_pos(prq) : blk_rq_pos(prq) << 9;
mqrq->packed_blocks += blk_rq_sectors(prq);
i++;
}
memset(brq, 0, sizeof(struct mmc_blk_request));
brq->mrq.cmd = &brq->cmd;
brq->mrq.data = &brq->data;
brq->mrq.sbc = &brq->sbc;
brq->mrq.stop = &brq->stop;
brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
brq->sbc.arg = <API key> | (mqrq->packed_blocks + 1);
brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
brq->cmd.opcode = <API key>;
brq->cmd.arg = blk_rq_pos(req);
if (!mmc_card_blockaddr(card))
brq->cmd.arg <<= 9;
brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
brq->data.blksz = 512;
brq->data.blocks = mqrq->packed_blocks + 1;
brq->data.flags |= MMC_DATA_WRITE;
brq->data.fault_injected = false;
brq->stop.opcode = <API key>;
brq->stop.arg = 0;
brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
<API key>(&brq->data, card);
brq->data.sg = mqrq->sg;
brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
mqrq->mmc_active.mrq = &brq->mrq;
mqrq->mmc_active.cmd_flags = req->cmd_flags;
/*
* This is intended for packed commands tests usage - in case these
* functions are not in use the respective pointers are NULL
*/
if (mq->err_check_fn)
mqrq->mmc_active.err_check = mq->err_check_fn;
else
mqrq->mmc_active.err_check = <API key>;
if (mq->packed_test_fn)
mq->packed_test_fn(mq->queue, mqrq);
mqrq->mmc_active.reinsert_req = <API key>;
mqrq->mmc_active.<API key> =
<API key>;
<API key>(mqrq);
}
static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card,
struct mmc_blk_request *brq, struct request *req,
int ret)
{
struct mmc_queue_req *mq_rq;
mq_rq = container_of(brq, struct mmc_queue_req, brq);
/*
* If this is an SD card and we're writing, we can first
* mark the known good sectors as ok.
*
* If the card is not SD, we can still ok written sectors
* as reported by the controller (which might be less than
* the real number of written sectors, but never more).
*/
if (mmc_card_sd(card)) {
u32 blocks;
if (!brq->data.fault_injected) {
blocks = <API key>(card);
if (blocks != (u32)-1)
ret = blk_end_request(req, 0, blocks << 9);
} else
ret = blk_end_request(req, 0, brq->data.bytes_xfered);
} else {
if (mq_rq->packed_cmd == MMC_PACKED_NONE)
ret = blk_end_request(req, 0, brq->data.bytes_xfered);
}
return ret;
}
static int <API key>(struct mmc_queue_req *mq_rq)
{
struct request *prq;
int idx = mq_rq->packed_fail_idx, i = 0;
int ret = 0;
while (!list_empty(&mq_rq->packed_list)) {
prq = list_entry_rq(mq_rq->packed_list.next);
if (idx == i) {
/* retry from error index */
mq_rq->packed_num -= idx;
mq_rq->req = prq;
ret = 1;
if (mq_rq->packed_num == MMC_PACKED_N_SINGLE) {
list_del_init(&prq->queuelist);
<API key>(mq_rq);
}
return ret;
}
list_del_init(&prq->queuelist);
blk_end_request(prq, 0, blk_rq_bytes(prq));
i++;
}
<API key>(mq_rq);
return ret;
}
static void <API key>(struct mmc_queue_req *mq_rq)
{
struct request *prq;
while (!list_empty(&mq_rq->packed_list)) {
prq = list_entry_rq(mq_rq->packed_list.next);
list_del_init(&prq->queuelist);
blk_end_request(prq, -EIO, blk_rq_bytes(prq));
}
<API key>(mq_rq);
}
static void <API key>(struct mmc_queue *mq,
struct mmc_queue_req *mq_rq)
{
struct request *prq;
struct request_queue *q = mq->queue;
while (!list_empty(&mq_rq->packed_list)) {
prq = list_entry_rq(mq_rq->packed_list.prev);
if (prq->queuelist.prev != &mq_rq->packed_list) {
list_del_init(&prq->queuelist);
spin_lock_irq(q->queue_lock);
blk_requeue_request(mq->queue, prq);
spin_unlock_irq(q->queue_lock);
} else {
list_del_init(&prq->queuelist);
}
}
<API key>(mq_rq);
}
static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
struct mmc_blk_request *brq = &mq->mqrq_cur->brq;
int ret = 1, disable_multi = 0, retry = 0, type;
enum mmc_blk_status status;
struct mmc_queue_req *mq_rq;
struct request *req;
struct mmc_async_req *areq;
const u8 packed_num = 2;
u8 reqs = 0;
if (!rqc && !mq->mqrq_prev->req)
return 0;
if (rqc) {
if ((card->ext_csd.bkops_en) && (rq_data_dir(rqc) == WRITE))
card->bkops_info.sectors_changed += blk_rq_sectors(rqc);
reqs = <API key>(mq, rqc);
}
do {
if (rqc) {
if (reqs >= packed_num)
<API key>(mq->mqrq_cur,
card, mq);
else
mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
areq = &mq->mqrq_cur->mmc_active;
} else
areq = NULL;
areq = mmc_start_req(card->host, areq, (int *) &status);
if (!areq) {
if (status == MMC_BLK_NEW_REQUEST)
mq->flags |= <API key>;
return 0;
}
mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
brq = &mq_rq->brq;
req = mq_rq->req;
type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
<API key>(mq_rq);
switch (status) {
case MMC_BLK_URGENT:
if (mq_rq->packed_cmd != MMC_PACKED_NONE) {
/* complete successfully transmitted part */
if (<API key>(mq_rq))
/* process for not transmitted part */
<API key>(areq);
} else {
<API key>(areq);
}
mq->flags |= <API key>;
ret = 0;
break;
case MMC_BLK_URGENT_DONE:
case MMC_BLK_SUCCESS:
case MMC_BLK_PARTIAL:
/*
* A block was successfully transferred.
*/
<API key>(md, type);
if (mq_rq->packed_cmd != MMC_PACKED_NONE) {
ret = <API key>(mq_rq);
break;
} else {
ret = blk_end_request(req, 0,
brq->data.bytes_xfered);
}
/*
* If the blk_end_request function returns non-zero even
* though all data has been transferred and no errors
* were returned by the host controller, it's a bug.
*/
if (status == MMC_BLK_SUCCESS && ret) {
pr_err("%s BUG rq_tot %d d_xfer %d\n",
__func__, blk_rq_bytes(req),
brq->data.bytes_xfered);
rqc = NULL;
goto cmd_abort;
}
break;
case MMC_BLK_CMD_ERR:
ret = mmc_blk_cmd_err(md, card, brq, req, ret);
if (!mmc_blk_reset(md, card->host, type))
break;
goto cmd_abort;
case MMC_BLK_RETRY:
if (retry++ < 5)
break;
/* Fall through */
case MMC_BLK_ABORT:
if (!mmc_blk_reset(md, card->host, type))
break;
goto cmd_abort;
case MMC_BLK_DATA_ERR: {
int err;
err = mmc_blk_reset(md, card->host, type);
if (!err)
break;
if (err == -ENODEV ||
mq_rq->packed_cmd != MMC_PACKED_NONE)
goto cmd_abort;
/* Fall through */
}
case MMC_BLK_ECC_ERR:
if (brq->data.blocks > 1) {
/* Redo read one sector at a time */
pr_warning("%s: retrying using single block read\n",
req->rq_disk->disk_name);
disable_multi = 1;
break;
}
/*
* After an error, we redo I/O one sector at a
* time, so we only reach here after trying to
* read a single sector.
*/
ret = blk_end_request(req, -EIO,
brq->data.blksz);
if (!ret)
goto start_new_req;
break;
case MMC_BLK_NOMEDIUM:
goto cmd_abort;
default:
pr_err("%s:%s: Unhandled return value (%d)",
req->rq_disk->disk_name,
__func__, status);
goto cmd_abort;
}
if (ret) {
if (mq_rq->packed_cmd == MMC_PACKED_NONE) {
/*
* In case of a incomplete request
* prepare it again and resend.
*/
mmc_blk_rw_rq_prep(mq_rq, card,
disable_multi, mq);
mmc_start_req(card->host,
&mq_rq->mmc_active, NULL);
} else {
if (!mq_rq->packed_retries)
goto cmd_abort;
<API key>(mq_rq, card, mq);
mmc_start_req(card->host,
&mq_rq->mmc_active, NULL);
}
}
} while (ret);
return 1;
cmd_abort:
if (mq_rq->packed_cmd == MMC_PACKED_NONE) {
if (mmc_card_removed(card))
req->cmd_flags |= REQ_QUIET;
while (ret)
ret = blk_end_request(req, -EIO,
blk_rq_cur_bytes(req));
} else {
<API key>(mq_rq);
}
start_new_req:
if (rqc) {
/*
* If current request is packed, it needs to put back.
*/
if (mq->mqrq_cur->packed_cmd != MMC_PACKED_NONE)
<API key>(mq, mq->mqrq_cur);
mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
mmc_start_req(card->host, &mq->mqrq_cur->mmc_active, NULL);
}
return 0;
}
static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req)
{
int ret;
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
#ifdef <API key>
if (<API key>(card->host)) {
mmc_resume_bus(card->host);
mmc_blk_set_blksize(md, card);
}
#endif
if (req && !mq->mqrq_prev->req) {
/* claim host only for the first request */
mmc_claim_host(card->host);
if (card->ext_csd.bkops_en)
mmc_stop_bkops(card);
}
ret = mmc_blk_part_switch(card, md);
if (ret) {
if (req) {
blk_end_request_all(req, -EIO);
}
ret = 0;
goto out;
}
<API key>(mq, req);
mq->flags &= ~<API key>;
mq->flags &= ~<API key>;
if (req && req->cmd_flags & REQ_SANITIZE) {
/* complete ongoing async transfer before issuing sanitize */
if (card->host && card->host->areq)
mmc_blk_issue_rw_rq(mq, NULL);
ret = <API key>(mq, req);
} else if (req && req->cmd_flags & REQ_DISCARD) {
/* complete ongoing async transfer before issuing discard */
if (card->host->areq)
mmc_blk_issue_rw_rq(mq, NULL);
if (req->cmd_flags & REQ_SECURE)
ret = <API key>(mq, req);
else
ret = <API key>(mq, req);
} else if (req && req->cmd_flags & REQ_FLUSH) {
/* complete ongoing async transfer before issuing flush */
if (card->host->areq)
mmc_blk_issue_rw_rq(mq, NULL);
ret = mmc_blk_issue_flush(mq, req);
} else {
ret = mmc_blk_issue_rw_rq(mq, req);
}
out:
/*
* packet burst is over, when one of the following occurs:
* - no more requests and new request notification is not in progress
* - urgent notification in progress and current request is not urgent
* (all existing requests completed or reinserted to the block layer)
*/
if ((!req && !(mq->flags & <API key>)) ||
((mq->flags & <API key>) &&
!(mq->mqrq_cur->req->cmd_flags & REQ_URGENT))) {
if (mmc_card_need_bkops(card))
mmc_start_bkops(card, false);
/* release host only when there are no more requests */
mmc_release_host(card->host);
}
return ret;
}
static inline int mmc_blk_readonly(struct mmc_card *card)
{
return mmc_card_readonly(card) ||
!(card->csd.cmdclass & CCC_BLOCK_WRITE);
}
static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
struct device *parent,
sector_t size,
bool default_ro,
const char *subname,
int area_type)
{
struct mmc_blk_data *md;
int devidx, ret;
unsigned int percentage =
<API key>;
devidx = find_first_zero_bit(dev_use, max_devices);
if (devidx >= max_devices)
return ERR_PTR(-ENOSPC);
__set_bit(devidx, dev_use);
md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
if (!md) {
ret = -ENOMEM;
goto out;
}
/*
* !subname implies we are creating main mmc_blk_data that will be
* associated with mmc_card with mmc_set_drvdata. Due to device
* partitions, devidx will not coincide with a per-physical card
* index anymore so we keep track of a name index.
*/
if (!subname) {
md->name_idx = find_first_zero_bit(name_use, max_devices);
__set_bit(md->name_idx, name_use);
} else
md->name_idx = ((struct mmc_blk_data *)
dev_to_disk(parent)->private_data)->name_idx;
md->area_type = area_type;
/*
* Set the read-only status based on the supported commands
* and the write protect switch.
*/
md->read_only = mmc_blk_readonly(card);
md->disk = alloc_disk(perdev_minors);
if (md->disk == NULL) {
ret = -ENOMEM;
goto err_kfree;
}
spin_lock_init(&md->lock);
INIT_LIST_HEAD(&md->part);
md->usage = 1;
ret = mmc_init_queue(&md->queue, card, &md->lock, subname);
if (ret)
goto err_putdisk;
md->queue.issue_fn = mmc_blk_issue_rq;
md->queue.data = md;
md->disk->major = MMC_BLOCK_MAJOR;
md->disk->first_minor = devidx * perdev_minors;
md->disk->fops = &mmc_bdops;
md->disk->private_data = md;
md->disk->queue = md->queue.queue;
md->disk->driverfs_dev = parent;
set_disk_ro(md->disk, md->read_only || default_ro);
md->disk->flags = GENHD_FL_EXT_DEVT;
/*
* As discussed on lkml, GENHD_FL_REMOVABLE should:
*
* - be set for removable media with permanent block devices
* - be unset for removable block devices with permanent media
*
* Since MMC block devices clearly fall under the second
* case, we do not set GENHD_FL_REMOVABLE. Userspace
* should use the block device creation/destruction hotplug
* messages to tell when the card is present.
*/
snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
"mmcblk%d%s", md->name_idx, subname ? subname : "");
<API key>(md->queue.queue, 512);
set_capacity(md->disk, size);
card->bkops_info.<API key> = percentage;
card->bkops_info.<API key> =
((unsigned int)size * percentage) / 100;
if (mmc_host_cmd23(card->host)) {
if (mmc_card_mmc(card) ||
(mmc_card_sd(card) &&
card->scr.cmds & <API key> &&
mmc_sd_card_uhs(card)))
md->flags |= MMC_BLK_CMD23;
}
if (mmc_card_mmc(card) &&
md->flags & MMC_BLK_CMD23 &&
((card->ext_csd.rel_param & <API key>) ||
card->ext_csd.rel_sectors)) {
md->flags |= MMC_BLK_REL_WR;
blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA);
}
return md;
err_putdisk:
put_disk(md->disk);
err_kfree:
kfree(md);
out:
return ERR_PTR(ret);
}
static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card)
{
sector_t size;
struct mmc_blk_data *md;
if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) {
/*
* The EXT_CSD sector count is in number or 512 byte
* sectors.
*/
size = card->ext_csd.sectors;
} else {
/*
* The CSD capacity field is in units of read_blkbits.
* set_capacity takes units of 512 bytes.
*/
size = card->csd.capacity << (card->csd.read_blkbits - 9);
}
md = mmc_blk_alloc_req(card, &card->dev, size, false, NULL,
<API key>);
return md;
}
static int mmc_blk_alloc_part(struct mmc_card *card,
struct mmc_blk_data *md,
unsigned int part_type,
sector_t size,
bool default_ro,
const char *subname,
int area_type)
{
char cap_str[10];
struct mmc_blk_data *part_md;
part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro,
subname, area_type);
if (IS_ERR(part_md))
return PTR_ERR(part_md);
part_md->part_type = part_type;
list_add(&part_md->part, &md->part);
string_get_size((u64)get_capacity(part_md->disk) << 9, STRING_UNITS_2,
cap_str, sizeof(cap_str));
pr_info("%s: %s %s partition %u %s\n",
part_md->disk->disk_name, mmc_card_id(card),
mmc_card_name(card), part_md->part_type, cap_str);
return 0;
}
/* MMC Physical partitions consist of two boot partitions and
* up to four general purpose partitions.
* For each partition enabled in EXT_CSD a block device will be allocatedi
* to provide access to the partition.
*/
static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md)
{
int idx, ret = 0;
if (!mmc_card_mmc(card))
return 0;
for (idx = 0; idx < card->nr_parts; idx++) {
if (card->part[idx].size) {
ret = mmc_blk_alloc_part(card, md,
card->part[idx].part_cfg,
card->part[idx].size >> 9,
card->part[idx].force_ro,
card->part[idx].name,
card->part[idx].area_type);
if (ret)
return ret;
}
}
return ret;
}
static void mmc_blk_remove_req(struct mmc_blk_data *md)
{
struct mmc_card *card;
if (md) {
card = md->queue.card;
device_remove_file(disk_to_dev(md->disk),
&md-><API key>);
if (md->disk->flags & GENHD_FL_UP) {
device_remove_file(disk_to_dev(md->disk), &md->force_ro);
if ((md->area_type & <API key>) &&
card->ext_csd.boot_ro_lockable)
device_remove_file(disk_to_dev(md->disk),
&md->power_ro_lock);
/* Stop new requests from getting into the queue */
del_gendisk(md->disk);
}
/* Then flush out any already in there */
mmc_cleanup_queue(&md->queue);
mmc_blk_put(md);
}
}
static void <API key>(struct mmc_card *card,
struct mmc_blk_data *md)
{
struct list_head *pos, *q;
struct mmc_blk_data *part_md;
__clear_bit(md->name_idx, name_use);
list_for_each_safe(pos, q, &md->part) {
part_md = list_entry(pos, struct mmc_blk_data, part);
list_del(pos);
mmc_blk_remove_req(part_md);
}
}
static int mmc_add_disk(struct mmc_blk_data *md)
{
int ret;
struct mmc_card *card = md->queue.card;
add_disk(md->disk);
md->force_ro.show = force_ro_show;
md->force_ro.store = force_ro_store;
sysfs_attr_init(&md->force_ro.attr);
md->force_ro.attr.name = "force_ro";
md->force_ro.attr.mode = S_IRUGO | S_IWUSR;
ret = device_create_file(disk_to_dev(md->disk), &md->force_ro);
if (ret)
goto force_ro_fail;
if ((md->area_type & <API key>) &&
card->ext_csd.boot_ro_lockable) {
umode_t mode;
if (card->ext_csd.boot_ro_lock & <API key>)
mode = S_IRUGO;
else
mode = S_IRUGO | S_IWUSR;
md->power_ro_lock.show = power_ro_lock_show;
md->power_ro_lock.store = power_ro_lock_store;
sysfs_attr_init(&md->power_ro_lock.attr);
md->power_ro_lock.attr.mode = mode;
md->power_ro_lock.attr.name =
"<API key>";
ret = device_create_file(disk_to_dev(md->disk),
&md->power_ro_lock);
if (ret)
goto power_ro_lock_fail;
}
md-><API key>.show =
<API key>;
md-><API key>.store =
<API key>;
sysfs_attr_init(&md-><API key>.attr);
md-><API key>.attr.name =
"<API key>";
md-><API key>.attr.mode = S_IRUGO | S_IWUSR;
ret = device_create_file(disk_to_dev(md->disk),
&md-><API key>);
if (ret)
goto <API key>;
md-><API key>.show = <API key>;
md-><API key>.store = <API key>;
sysfs_attr_init(&md-><API key>.attr);
md-><API key>.attr.name = "<API key>";
md-><API key>.attr.mode = S_IRUGO | S_IWUSR;
ret = device_create_file(disk_to_dev(md->disk),
&md-><API key>);
if (ret)
goto <API key>;
md->no_pack_for_random.show = <API key>;
md->no_pack_for_random.store = <API key>;
sysfs_attr_init(&md->no_pack_for_random.attr);
md->no_pack_for_random.attr.name = "no_pack_for_random";
md->no_pack_for_random.attr.mode = S_IRUGO | S_IWUSR;
ret = device_create_file(disk_to_dev(md->disk),
&md->no_pack_for_random);
if (ret)
goto <API key>;
return ret;
<API key>:
device_remove_file(disk_to_dev(md->disk),
&md-><API key>);
<API key>:
device_remove_file(disk_to_dev(md->disk),
&md-><API key>);
<API key>:
device_remove_file(disk_to_dev(md->disk), &md->power_ro_lock);
power_ro_lock_fail:
device_remove_file(disk_to_dev(md->disk), &md->force_ro);
force_ro_fail:
del_gendisk(md->disk);
return ret;
}
#define CID_MANFID_SANDISK 0x2
#define CID_MANFID_TOSHIBA 0x11
#define CID_MANFID_MICRON 0x13
#define CID_MANFID_SAMSUNG 0x15
static const struct mmc_fixup blk_fixups[] =
{
MMC_FIXUP("SEM02G", CID_MANFID_SANDISK, 0x100, add_quirk,
<API key>),
MMC_FIXUP("SEM04G", CID_MANFID_SANDISK, 0x100, add_quirk,
<API key>),
MMC_FIXUP("SEM08G", CID_MANFID_SANDISK, 0x100, add_quirk,
<API key>),
MMC_FIXUP("SEM16G", CID_MANFID_SANDISK, 0x100, add_quirk,
<API key>),
MMC_FIXUP("SEM32G", CID_MANFID_SANDISK, 0x100, add_quirk,
<API key>),
/*
* Some MMC cards experience performance degradation with CMD23
* instead of CMD12-bounded multiblock transfers. For now we'll
* black list what's bad...
* - Certain Toshiba cards.
*
* N.B. This doesn't affect SD cards.
*/
MMC_FIXUP("MMC08G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("MMC16G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("MMC32G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
/*
* Some Micron MMC cards needs longer data read timeout than
* indicated in CSD.
*/
MMC_FIXUP(CID_NAME_ANY, CID_MANFID_MICRON, 0x200, add_quirk_mmc,
<API key>),
/* Some TLC movinand cards needs Sync operation for performance*/
MMC_FIXUP("S5U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("J5U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("J5U00B", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("J5U00A", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("L7U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("N5U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("K5U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("K5U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("K7U00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("M4G1YC", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("M8G1WA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("MAG2WA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
MMC_FIXUP("MBG4WA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
/* Some INAND MCP devices advertise incorrect timeout values */
MMC_FIXUP("SEM04G", 0x45, CID_OEMID_ANY, add_quirk_mmc,
<API key>),
END_FIXUP
};
static int mmc_blk_probe(struct mmc_card *card)
{
struct mmc_blk_data *md, *part_md;
char cap_str[10];
/*
* Check that the card supports the command class(es) we need.
*/
if (!(card->csd.cmdclass & CCC_BLOCK_READ))
return -ENODEV;
md = mmc_blk_alloc(card);
if (IS_ERR(md))
return PTR_ERR(md);
string_get_size((u64)get_capacity(md->disk) << 9, STRING_UNITS_2,
cap_str, sizeof(cap_str));
pr_info("%s: %s %s %s %s\n",
md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
cap_str, md->read_only ? "(ro)" : "");
if (mmc_blk_alloc_parts(card, md))
goto out;
mmc_set_drvdata(card, md);
mmc_fixup_device(card, blk_fixups);
#ifdef <API key>
<API key>(card->host, 1);
#endif
if (mmc_add_disk(md))
goto out;
list_for_each_entry(part_md, &md->part, part) {
if (mmc_add_disk(part_md))
goto out;
}
return 0;
out:
<API key>(card, md);
mmc_blk_remove_req(md);
return 0;
}
static void mmc_blk_remove(struct mmc_card *card)
{
struct mmc_blk_data *md = mmc_get_drvdata(card);
<API key>(card, md);
mmc_claim_host(card->host);
mmc_blk_part_switch(card, md);
mmc_release_host(card->host);
mmc_blk_remove_req(md);
mmc_set_drvdata(card, NULL);
#ifdef <API key>
<API key>(card->host, 0);
#endif
}
#ifdef CONFIG_PM
static int mmc_blk_suspend(struct mmc_card *card)
{
struct mmc_blk_data *part_md;
struct mmc_blk_data *md = mmc_get_drvdata(card);
int rc = 0;
if (md) {
rc = mmc_queue_suspend(&md->queue);
if (rc)
goto out;
list_for_each_entry(part_md, &md->part, part) {
rc = mmc_queue_suspend(&part_md->queue);
if (rc)
goto out_resume;
}
}
goto out;
out_resume:
mmc_queue_resume(&md->queue);
list_for_each_entry(part_md, &md->part, part) {
mmc_queue_resume(&part_md->queue);
}
out:
return rc;
}
static int mmc_blk_resume(struct mmc_card *card)
{
struct mmc_blk_data *part_md;
struct mmc_blk_data *md = mmc_get_drvdata(card);
if (md) {
/*
* Resume involves the card going into idle state,
* so current partition is always the main one.
*/
md->part_curr = md->part_type;
mmc_queue_resume(&md->queue);
list_for_each_entry(part_md, &md->part, part) {
mmc_queue_resume(&part_md->queue);
}
}
return 0;
}
#else
#define mmc_blk_suspend NULL
#define mmc_blk_resume NULL
#endif
static struct mmc_driver mmc_driver = {
.drv = {
.name = "mmcblk",
},
.probe = mmc_blk_probe,
.remove = mmc_blk_remove,
.suspend = mmc_blk_suspend,
.resume = mmc_blk_resume,
};
static int __init mmc_blk_init(void)
{
int res;
if (perdev_minors != <API key>)
pr_info("mmcblk: using %d minors per device\n", perdev_minors);
max_devices = 256 / perdev_minors;
res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
if (res)
goto out;
res = mmc_register_driver(&mmc_driver);
if (res)
goto out2;
return 0;
out2:
unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
out:
return res;
}
static void __exit mmc_blk_exit(void)
{
<API key>(&mmc_driver);
unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
}
module_init(mmc_blk_init);
module_exit(mmc_blk_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
|
#ifndef <API key>
#define <API key>
#ifdef CONFIG_VMSPLIT_2G
#define VMALLOC_END (PAGE_OFFSET + 0x7A000000)
#else
#if defined (CONFIG_LGE_4G_DDR)
/* 2010-06-29 [junyeong.han@lge.com] Support 512MB SDRAM */
/* To support 512MB SDRAM in VMSPLIT_3G */
#define VMALLOC_END (PAGE_OFFSET + 0x3A000000)
#else /* original */
#define VMALLOC_END (PAGE_OFFSET + 0x20000000)
#endif
#endif
#endif
|
//# LCExtension.cc: Extend an LCRegion along straight lines to other dimensions
//
//# Associated Universities, Inc. Washington DC, USA.
//
//# This library is free software; you can redistribute it and/or modify it
//
//
//# option) any later version.
//
//# This library is distributed in the hope that it will be useful, but WITHOUT
//
//# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
//
//
//
//# along with this library; if not, write to the Free Software Foundation,
//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
//
//# Correspondence concerning AIPS++ should be addressed as follows:
//# Internet email: aips2-request@nrao.edu.
//# Postal address: AIPS++ Project Office
//# National Radio Astronomy Observatory
//# 520 Edgemont Road
//# Charlottesville, VA 22903-2475 USA
//
//
#include <casacore/lattices/LRegions/LCExtension.h>
#include <casacore/lattices/LRegions/LCBox.h>
#include <casacore/casa/Arrays/Vector.h>
#include <casacore/tables/Tables/TableRecord.h>
#include <casacore/casa/Utilities/GenSort.h>
#include <casacore/casa/Exceptions/Error.h>
namespace casacore { //# NAMESPACE CASACORE - BEGIN
LCExtension::LCExtension()
{}
LCExtension::LCExtension (const LCRegion& region,
const IPosition& extendAxes,
const LCBox& extendBox)
: LCRegionMulti (True, region.cloneRegion())
{
// Fill the other members variables and determine the bounding box.
fill (extendAxes, extendBox);
}
LCExtension::LCExtension (Bool takeOver,
const LCRegion* region,
const IPosition& extendAxes,
const LCBox& extendBox)
: LCRegionMulti (takeOver, region)
{
// Fill the other members variables and determine the bounding box.
fill (extendAxes, extendBox);
}
LCExtension::LCExtension (const LCExtension& other)
: LCRegionMulti (other),
itsExtendAxes (other.itsExtendAxes),
itsRegionAxes (other.itsRegionAxes),
itsExtendBox (other.itsExtendBox)
{}
LCExtension::~LCExtension()
{}
LCExtension& LCExtension::operator= (const LCExtension& other)
{
if (this != &other) {
LCRegionMulti::operator= (other);
itsExtendAxes.resize (other.itsExtendAxes.nelements());
itsRegionAxes.resize (other.itsRegionAxes.nelements());
itsExtendAxes = other.itsExtendAxes;
itsRegionAxes = other.itsRegionAxes;
itsExtendBox = other.itsExtendBox;
}
return *this;
}
Bool LCExtension::operator== (const LCRegion& other) const
{
// Check if parent class matches.
// If so, we can safely cast.
if (! LCRegionMulti::operator== (other)) {
return False;
}
const LCExtension& that = (const LCExtension&)other;
// Check the private data
if (! itsExtendAxes.isEqual (that.itsExtendAxes)
|| ! itsRegionAxes.isEqual (that.itsRegionAxes)
|| !(itsExtendBox == that.itsExtendBox)) {
return False;
}
return True;
}
LCRegion* LCExtension::cloneRegion() const
{
return new LCExtension (*this);
}
LCRegion* LCExtension::doTranslate (const Vector<Float>& translateVector,
const IPosition& newLatticeShape) const
{
uInt i;
// First translate the extendBox.
// Take appropriate elements from the vectors.
uInt nre = itsExtendAxes.nelements();
Vector<Float> boxTransVec (nre);
IPosition boxLatShape (nre);
for (i=0; i<nre; i++) {
uInt axis = itsExtendAxes(i);
boxTransVec(i) = translateVector(axis);
boxLatShape(i) = newLatticeShape(axis);
}
LCBox* boxPtr = (LCBox*)(itsExtendBox.translate (boxTransVec, boxLatShape));
// Now translate the region.
uInt nrr = itsRegionAxes.nelements();
Vector<Float> regTransVec (nrr);
IPosition regLatShape (nrr);
for (i=0; i<nrr; i++) {
uInt axis = itsRegionAxes(i);
regTransVec(i) = translateVector(axis);
regLatShape(i) = newLatticeShape(axis);
}
LCRegion* regPtr = region().translate (regTransVec, regLatShape);
// Create the new LCExtension object.
LCExtension* extPtr = new LCExtension (*regPtr, itsExtendAxes, *boxPtr);
delete boxPtr;
delete regPtr;
return extPtr;
}
String LCExtension::className()
{
return "LCExtension";
}
String LCExtension::type() const
{
return className();
}
TableRecord LCExtension::toRecord (const String& tableName) const
{
TableRecord rec;
defineRecordFields (rec, className());
rec.defineRecord ("region", region().toRecord (tableName));
rec.define ("axes", itsExtendAxes.asVector());
rec.defineRecord ("box", itsExtendBox.toRecord (tableName));
return rec;
}
LCExtension* LCExtension::fromRecord (const TableRecord& rec,
const String& tableName)
{
// Initialize pointers to 0 to get rid of gcc-2.95 warnings.
LCRegion* regPtr = 0;
regPtr = LCRegion::fromRecord (rec.asRecord("region"), tableName);
LCBox* boxPtr = 0;
boxPtr = (LCBox*)(LCRegion::fromRecord (rec.asRecord("box"), tableName));
LCExtension* extPtr = new LCExtension (True, regPtr,
Vector<Int>(rec.toArrayInt ("axes")),
*boxPtr);
delete boxPtr;
return extPtr;
}
void LCExtension::fillRegionAxes()
{
uInt nre = itsExtendAxes.nelements();
uInt nrr = region().ndim();
uInt nrdim = nre+nrr;
// allAxes will get the remaining (thus region) axes at the end.
IPosition allAxes = IPosition::makeAxisPath (nrdim, itsExtendAxes);
itsRegionAxes.resize (nrr);
for (uInt i=nre; i<nrdim; i++) {
uInt axis = allAxes(i);
itsRegionAxes(i-nre) = axis;
}
}
void LCExtension::fill (const IPosition& extendAxes, const LCBox& extendBox)
{
// Check if extend axes are specified correctly.
// They do not need to be in ascending order, but duplicates are
// not allowed.
IPosition regionShape = region().shape();
uInt nre = extendAxes.nelements();
if (nre == 0) {
throw (AipsError ("LCExtension::LCExtension - "
"no extend axes have been specified"));
}
if (nre != extendBox.blc().nelements()) {
throw (AipsError ("LCExtension::LCExtension - "
"number of axes in extend box mismatches "
"number of extend axes"));
}
// The axes can be specified in any order. We want them ordered.
// So sort them and fill itsExtendAxes and itsExtendBox.
itsExtendAxes.resize (nre);
IPosition boxLatShape(nre);
Vector<Float> boxLatBlc(nre);
Vector<Float> boxLatTrc(nre);
Vector<uInt> reginx(nre);
GenSortIndirect<ssize_t>::sort (reginx, extendAxes.storage(), nre);
Int first = -1;
for (uInt i=0; i<nre; i++) {
uInt axis = reginx(i);
itsExtendAxes(i) = extendAxes(axis);
boxLatShape(i) = extendBox.latticeShape()(axis);
boxLatBlc(i) = extendBox.blc()(axis);
boxLatTrc(i) = extendBox.trc()(axis);
if (itsExtendAxes(i) <= first) {
throw (AipsError ("LCExtension::LCExtension - "
"extend axes multiply specified"));
}
first = itsExtendAxes(i);
}
itsExtendBox = LCBox (boxLatBlc, boxLatTrc, boxLatShape);
// Fill itsRegionAxes, i.e. the mapping of the axis of the contributing
// region into the extended region.
fillRegionAxes();
// Make up the lattice shape from the region and box latticeshape.
// Fill the bounding box from blc/trc in region and box.
uInt nrr = itsRegionAxes.nelements();
uInt nrdim = nre+nrr;
IPosition latShape(nrdim);
IPosition blc (nrdim);
IPosition trc (nrdim);
const IPosition& regionShp = region().latticeShape();
const IPosition& regionBlc = region().boundingBox().start();
const IPosition& regionTrc = region().boundingBox().end();
for (uInt i=0; i<nrr; i++) {
uInt axis = itsRegionAxes(i);
latShape(axis) = regionShp(i);
blc(axis) = regionBlc(i);
trc(axis) = regionTrc(i);
}
const IPosition& boxShp = itsExtendBox.latticeShape();
const IPosition& boxBlc = itsExtendBox.boundingBox().start();
const IPosition& boxTrc = itsExtendBox.boundingBox().end();
for (uInt i=0; i<nre; i++) {
uInt axis = itsExtendAxes(i);
latShape(axis) = boxShp(i);
blc(axis) = boxBlc(i);
trc(axis) = boxTrc(i);
}
<API key> (latShape, Slicer(blc, trc, Slicer::endIsLast));
fillHasMask();
}
void LCExtension::multiGetSlice (Array<Bool>& buffer,
const Slicer& section)
{
buffer.resize (section.length());
uInt i;
uInt nre = itsExtendAxes.nelements();
uInt nrr = itsRegionAxes.nelements();
// Read the required region section.
// This means we have to create a Slicer for those axes only.
IPosition blc(nrr);
IPosition len(nrr);
IPosition inc(nrr);
IPosition shape(buffer.ndim(), 1);
for (i=0; i<nrr; i++) {
uInt axis = itsRegionAxes(i);
blc(i) = section.start()(axis);
len(i) = section.length()(axis);
inc(i) = section.stride()(axis);
shape(axis) = len(i);
}
Array<Bool> tmpbuf(len);
LCRegion* reg = (LCRegion*)(regions()[0]);
reg->doGetSlice (tmpbuf, Slicer(blc, len, inc));
// Reform tmpbuf, so it has the same dimensionality as buffer.
Array<Bool> mask = tmpbuf.reform (shape);
// Now we have to extend tmpbuf along all extend axes.
const IPosition& length = section.length();
IPosition pos (buffer.ndim(), 0);
IPosition end (buffer.shape() - 1);
//# Iterate along itsExtendAxes (the new axes) through the new mask.
for (;;) {
for (i=0; i<nre; i++) {
end(itsExtendAxes(i)) = pos(itsExtendAxes(i));
}
//# Set each section of the mask to the mask of the region.
buffer(pos,end) = mask;
//# Go to the next section.
for (i=0; i<nre; i++) {
if (++pos(itsExtendAxes(i)) < length(itsExtendAxes(i))) {
break;
}
// This dimension is done. Reset it and continue with the next.
pos(itsExtendAxes(i)) = 0;
}
//# End the iteration when all dimensions are done.
if (i == nre) {
break;
}
}
}
IPosition LCExtension::doNiceCursorShape (uInt maxPixels) const
{
return Lattice<Bool>::doNiceCursorShape (maxPixels);
}
} //# NAMESPACE CASACORE - END
|
<?php
namespace Composer\Command;
use Composer\Composer;
use Composer\Factory;
use Composer\Config;
use Composer\Downloader\TransportException;
use Composer\Repository\PlatformRepository;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Composer\Util\ConfigValidator;
use Composer\Util\IniHelper;
use Composer\Util\ProcessExecutor;
use Composer\Util\RemoteFilesystem;
use Composer\Util\<API key>;
use Composer\SelfUpdate\Keys;
use Composer\SelfUpdate\Versions;
use Composer\IO\NullIO;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class DiagnoseCommand extends BaseCommand
{
/** @var RemoteFilesystem */
protected $rfs;
/** @var ProcessExecutor */
protected $process;
/** @var int */
protected $exitCode = 0;
protected function configure()
{
$this
->setName('diagnose')
->setDescription('Diagnoses the system to identify common errors.')
->setHelp(
EOT
The <info>diagnose</info> command checks common errors to help debugging problems.
The process exit code will be 1 in case of warnings and 2 for errors.
Read more at https://getcomposer.org/doc/03-cli.md#diagnose
EOT
)
;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer(false);
$io = $this->getIO();
if ($composer) {
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$io->write('Checking composer.json: ', false);
$this->outputResult($this->checkComposerSchema());
}
if ($composer) {
$config = $composer->getConfig();
} else {
$config = Factory::createConfig();
}
$config->merge(array('config' => array('secure-http' => false)));
$config->prohibitUrlByConfig('http://repo.packagist.org', new NullIO);
$this->rfs = Factory::<API key>($io, $config);
$this->process = new ProcessExecutor($io);
$io->write('Checking platform settings: ', false);
$this->outputResult($this->checkPlatform());
$io->write('Checking git settings: ', false);
$this->outputResult($this->checkGit());
$io->write('Checking http connectivity to packagist: ', false);
$this->outputResult($this->checkHttp('http', $config));
$io->write('Checking https connectivity to packagist: ', false);
$this->outputResult($this->checkHttp('https', $config));
$opts = <API key>(<API key>::getContext('http://example.org'));
if (!empty($opts['http']['proxy'])) {
$io->write('Checking HTTP proxy: ', false);
$this->outputResult($this->checkHttpProxy());
$io->write('Checking HTTP proxy support for request_fulluri: ', false);
$this->outputResult($this-><API key>());
$io->write('Checking HTTPS proxy support for request_fulluri: ', false);
$this->outputResult($this-><API key>());
}
if ($oauth = $config->get('github-oauth')) {
foreach ($oauth as $domain => $token) {
$io->write('Checking '.$domain.' oauth access: ', false);
$this->outputResult($this->checkGithubOauth($domain, $token));
}
} else {
$io->write('Checking github.com rate limit: ', false);
try {
$rate = $this->getGithubRateLimit('github.com');
if (!is_array($rate)) {
$this->outputResult($rate);
} elseif (10 > $rate['remaining']) {
$io->write('<warning>WARNING</warning>');
$io->write(sprintf(
'<comment>Github has a rate limit on their API. '
. 'You currently have <options=bold>%u</options=bold> '
. 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL
. 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL
. ' https://getcomposer.org/doc/articles/troubleshooting.md#<API key></comment>',
$rate['remaining'],
$rate['limit']
));
} else {
$this->outputResult(true);
}
} catch (\Exception $e) {
if ($e instanceof TransportException && $e->getCode() === 401) {
$this->outputResult('<comment>The oauth token for github.com seems invalid, run "composer config --global --unset github-oauth.github.com" to remove it</comment>');
} else {
$this->outputResult($e);
}
}
}
$io->write('Checking disk free space: ', false);
$this->outputResult($this->checkDiskSpace($config));
if ('phar:' === substr(__FILE__, 0, 5)) {
$io->write('Checking pubkeys: ', false);
$this->outputResult($this->checkPubKeys($config));
$io->write('Checking composer version: ', false);
$this->outputResult($this->checkVersion($config));
}
$io->write(sprintf('Composer version: <comment>%s</comment>', Composer::VERSION));
$platformOverrides = $config->get('platform') ?: array();
$platformRepo = new PlatformRepository(array(), $platformOverrides);
$phpPkg = $platformRepo->findPackage('php', '*');
$phpVersion = $phpPkg->getPrettyVersion();
if (false !== strpos($phpPkg->getDescription(), 'overridden')) {
$phpVersion .= ' - ' . $phpPkg->getDescription();
}
$io->write(sprintf('PHP version: <comment>%s</comment>', $phpVersion));
if (defined('PHP_BINARY')) {
$io->write(sprintf('PHP binary path: <comment>%s</comment>', PHP_BINARY));
}
return $this->exitCode;
}
private function checkComposerSchema()
{
$validator = new ConfigValidator($this->getIO());
list($errors, , $warnings) = $validator->validate(Factory::getComposerFile());
if ($errors || $warnings) {
$messages = array(
'error' => $errors,
'warning' => $warnings,
);
$output = '';
foreach ($messages as $style => $msgs) {
foreach ($msgs as $msg) {
$output .= '<' . $style . '>' . $msg . '</' . $style . '>' . PHP_EOL;
}
}
return rtrim($output);
}
return true;
}
private function checkGit()
{
$this->process->execute('git config color.ui', $output);
if (strtolower(trim($output)) === 'always') {
return '<comment>Your git color.ui setting is set to always, this is known to create issues. Use "git config --global color.ui true" to set it correctly.</comment>';
}
return true;
}
private function checkHttp($proto, Config $config)
{
$result = $this->checkConnectivity();
if ($result !== true) {
return $result;
}
$disableTls = false;
$result = array();
if ($proto === 'https' && $config->get('disable-tls') === true) {
$disableTls = true;
$result[] = '<warning>Composer is configured to disable SSL/TLS protection. This will leave remote HTTPS requests vulnerable to Man-In-The-Middle attacks.</warning>';
}
if ($proto === 'https' && !extension_loaded('openssl') && !$disableTls) {
$result[] = '<error>Composer is configured to use SSL/TLS protection but the openssl extension is not available.</error>';
}
try {
$this->rfs->getContents('packagist.org', $proto . '://repo.packagist.org/packages.json', false);
} catch (TransportException $e) {
if (false !== strpos($e->getMessage(), 'cafile')) {
$result[] = '<error>[' . get_class($e) . '] ' . $e->getMessage() . '</error>';
$result[] = '<error>Unable to locate a valid CA certificate file. You must set a valid \'cafile\' option.</error>';
$result[] = '<error>You can alternatively disable this error, at your own risk, by enabling the \'disable-tls\' option.</error>';
} else {
array_unshift($result, '[' . get_class($e) . '] ' . $e->getMessage());
}
}
if (count($result) > 0) {
return $result;
}
return true;
}
private function checkHttpProxy()
{
$result = $this->checkConnectivity();
if ($result !== true) {
return $result;
}
$protocol = extension_loaded('openssl') ? 'https' : 'http';
try {
$json = json_decode($this->rfs->getContents('packagist.org', $protocol . '://repo.packagist.org/packages.json', false), true);
$hash = reset($json['provider-includes']);
$hash = $hash['sha256'];
$path = str_replace('%hash%', $hash, key($json['provider-includes']));
$provider = $this->rfs->getContents('packagist.org', $protocol . '://repo.packagist.org/'.$path, false);
if (hash('sha256', $provider) !== $hash) {
return 'It seems that your proxy is modifying http traffic on the fly';
}
} catch (\Exception $e) {
return $e;
}
return true;
}
private function <API key>()
{
$result = $this->checkConnectivity();
if ($result !== true) {
return $result;
}
$url = 'http://repo.packagist.org/packages.json';
try {
$this->rfs->getContents('packagist.org', $url, false);
} catch (TransportException $e) {
try {
$this->rfs->getContents('packagist.org', $url, false, array('http' => array('request_fulluri' => false)));
} catch (TransportException $e) {
return 'Unable to assess the situation, maybe packagist.org is down ('.$e->getMessage().')';
}
return 'It seems there is a problem with your proxy server, try setting the "<API key>" and "<API key>" environment variables to "false"';
}
return true;
}
private function <API key>()
{
$result = $this->checkConnectivity();
if ($result !== true) {
return $result;
}
if (!extension_loaded('openssl')) {
return 'You need the openssl extension installed for this check';
}
$url = 'https://api.github.com/repos/Seldaek/jsonlint/zipball/1.0.0';
try {
$this->rfs->getContents('github.com', $url, false);
} catch (TransportException $e) {
try {
$this->rfs->getContents('github.com', $url, false, array('http' => array('request_fulluri' => false)));
} catch (TransportException $e) {
return 'Unable to assess the situation, maybe github is down ('.$e->getMessage().')';
}
return 'It seems there is a problem with your proxy server, try setting the "<API key>" environment variable to "false"';
}
return true;
}
private function checkGithubOauth($domain, $token)
{
$result = $this->checkConnectivity();
if ($result !== true) {
return $result;
}
$this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
try {
$url = $domain === 'github.com' ? 'https:
return $this->rfs->getContents($domain, $url, false, array(
'retry-auth-failure' => false,
)) ? true : 'Unexpected error';
} catch (\Exception $e) {
if ($e instanceof TransportException && $e->getCode() === 401) {
return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>';
}
return $e;
}
}
/**
* @param string $domain
* @param string $token
* @throws TransportException
* @return array|string
*/
private function getGithubRateLimit($domain, $token = null)
{
$result = $this->checkConnectivity();
if ($result !== true) {
return $result;
}
if ($token) {
$this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
}
$url = $domain === 'github.com' ? 'https:
$json = $this->rfs->getContents($domain, $url, false, array('retry-auth-failure' => false));
$data = json_decode($json, true);
return $data['resources']['core'];
}
private function checkDiskSpace($config)
{
$minSpaceFree = 1024 * 1024;
if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
|| (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
) {
return '<error>The disk hosting '.$dir.' is full</error>';
}
return true;
}
private function checkPubKeys($config)
{
$home = $config->get('home');
$errors = array();
$io = $this->getIO();
if (file_exists($home.'/keys.tags.pub') && file_exists($home.'/keys.dev.pub')) {
$io->write('');
}
if (file_exists($home.'/keys.tags.pub')) {
$io->write('Tags Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.tags.pub'));
} else {
$errors[] = '<error>Missing pubkey for tags verification</error>';
}
if (file_exists($home.'/keys.dev.pub')) {
$io->write('Dev Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.dev.pub'));
} else {
$errors[] = '<error>Missing pubkey for dev verification</error>';
}
if ($errors) {
$errors[] = '<error>Run composer self-update --update-keys to set them up</error>';
}
return $errors ?: true;
}
private function checkVersion($config)
{
$result = $this->checkConnectivity();
if ($result !== true) {
return $result;
}
$versionsUtil = new Versions($config, $this->rfs);
$latest = $versionsUtil->getLatest();
if (Composer::VERSION !== $latest['version'] && Composer::VERSION !== '@package_version@') {
return '<comment>You are not running the latest '.$versionsUtil->getChannel().' version, run `composer self-update` to update ('.Composer::VERSION.' => '.$latest['version'].')</comment>';
}
return true;
}
/**
* @param bool|string|\Exception $result
*/
private function outputResult($result)
{
$io = $this->getIO();
if (true === $result) {
$io->write('<info>OK</info>');
return;
}
$hadError = false;
$hadWarning = false;
if ($result instanceof \Exception) {
$result = '<error>['.get_class($result).'] '.$result->getMessage().'</error>';
}
if (!$result) {
// falsey results should be considered as an error, even if there is nothing to output
$hadError = true;
} else {
if (!is_array($result)) {
$result = array($result);
}
foreach ($result as $message) {
if (false !== strpos($message, '<error>')) {
$hadError = true;
} elseif (false !== strpos($message, '<warning>')) {
$hadWarning = true;
}
}
}
if ($hadError) {
$io->write('<error>FAIL</error>');
$this->exitCode = max($this->exitCode, 2);
} elseif ($hadWarning) {
$io->write('<warning>WARNING</warning>');
$this->exitCode = max($this->exitCode, 1);
}
if ($result) {
foreach ($result as $message) {
$io->write($message);
}
}
}
private function checkPlatform()
{
$output = '';
$out = function ($msg, $style) use (&$output) {
$output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL;
};
// code below taken from getcomposer.org/installer, any changes should be made there and replicated here
$errors = array();
$warnings = array();
$displayIniMessage = false;
$iniMessage = PHP_EOL.PHP_EOL.IniHelper::getMessage();
$iniMessage .= PHP_EOL.'If you can not modify the ini file, you can also run `php -d option=value` to modify ini values on the fly. You can use -d multiple times.';
if (!function_exists('json_decode')) {
$errors['json'] = true;
}
if (!extension_loaded('Phar')) {
$errors['phar'] = true;
}
if (!extension_loaded('filter')) {
$errors['filter'] = true;
}
if (!extension_loaded('hash')) {
$errors['hash'] = true;
}
if (!extension_loaded('iconv') && !extension_loaded('mbstring')) {
$errors['iconv_mbstring'] = true;
}
if (!filter_var(ini_get('allow_url_fopen'), <API key>)) {
$errors['allow_url_fopen'] = true;
}
if (extension_loaded('ionCube Loader') && <API key>() < 40009) {
$errors['ioncube'] = <API key>();
}
if (PHP_VERSION_ID < 50302) {
$errors['php'] = PHP_VERSION;
}
if (!isset($errors['php']) && PHP_VERSION_ID < 50304) {
$warnings['php'] = PHP_VERSION;
}
if (!extension_loaded('openssl')) {
$errors['openssl'] = true;
}
if (extension_loaded('openssl') && <API key> < 0x1000100f) {
$warnings['openssl_version'] = true;
}
if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && filter_var(ini_get('apc.enable_cli'), <API key>)) {
$warnings['apc_cli'] = true;
}
if (!extension_loaded('zlib')) {
$warnings['zlib'] = true;
}
ob_start();
phpinfo(INFO_GENERAL);
$phpinfo = ob_get_clean();
if (preg_match('{Configure Command(?: *</td><td class="v">| *=> *)(.*?)(?:</td>|$)}m', $phpinfo, $match)) {
$configure = $match[1];
if (false !== strpos($configure, '--enable-sigchild')) {
$warnings['sigchild'] = true;
}
if (false !== strpos($configure, '--with-curlwrappers')) {
$warnings['curlwrappers'] = true;
}
}
if (filter_var(ini_get('xdebug.profiler_enabled'), <API key>)) {
$warnings['xdebug_profile'] = true;
} elseif (extension_loaded('xdebug')) {
$warnings['xdebug_loaded'] = true;
}
if (!empty($errors)) {
foreach ($errors as $error => $current) {
switch ($error) {
case 'json':
$text = PHP_EOL."The json extension is missing.".PHP_EOL;
$text .= "Install it or recompile php without --disable-json";
break;
case 'phar':
$text = PHP_EOL."The phar extension is missing.".PHP_EOL;
$text .= "Install it or recompile php without --disable-phar";
break;
case 'filter':
$text = PHP_EOL."The filter extension is missing.".PHP_EOL;
$text .= "Install it or recompile php without --disable-filter";
break;
case 'hash':
$text = PHP_EOL."The hash extension is missing.".PHP_EOL;
$text .= "Install it or recompile php without --disable-hash";
break;
case 'iconv_mbstring':
$text = PHP_EOL."The iconv OR mbstring extension is required and both are missing.".PHP_EOL;
$text .= "Install either of them or recompile php without --disable-iconv";
break;
case 'unicode':
$text = PHP_EOL."The detect_unicode setting must be disabled.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
$text .= " detect_unicode = Off";
$displayIniMessage = true;
break;
case 'suhosin':
$text = PHP_EOL."The suhosin.executor.include.whitelist setting is incorrect.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini` or suhosin.ini (Example path [for Debian]: /etc/php5/cli/conf.d/suhosin.ini):".PHP_EOL;
$text .= " suhosin.executor.include.whitelist = phar ".$current;
$displayIniMessage = true;
break;
case 'php':
$text = PHP_EOL."Your PHP ({$current}) is too old, you must upgrade to PHP 5.3.2 or higher.";
break;
case 'allow_url_fopen':
$text = PHP_EOL."The allow_url_fopen setting is incorrect.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
$text .= " allow_url_fopen = On";
$displayIniMessage = true;
break;
case 'ioncube':
$text = PHP_EOL."Your ionCube Loader extension ($current) is incompatible with Phar files.".PHP_EOL;
$text .= "Upgrade to ionCube 4.0.9 or higher or remove this line (path may be different) from your `php.ini` to disable it:".PHP_EOL;
$text .= " zend_extension = /usr/lib/php5/20090626+lfs/<API key>.3.so";
$displayIniMessage = true;
break;
case 'openssl':
$text = PHP_EOL."The openssl extension is missing, which means that secure HTTPS transfers are impossible.".PHP_EOL;
$text .= "If possible you should enable it or recompile php with --with-openssl";
break;
}
$out($text, 'error');
}
$output .= PHP_EOL;
}
if (!empty($warnings)) {
foreach ($warnings as $warning => $current) {
switch ($warning) {
case 'apc_cli':
$text = "The apc.enable_cli setting is incorrect.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
$text .= " apc.enable_cli = Off";
$displayIniMessage = true;
break;
case 'zlib':
$text = 'The zlib extension is not loaded, this can slow down Composer a lot.'.PHP_EOL;
$text .= 'If possible, enable it or recompile php with --with-zlib'.PHP_EOL;
$displayIniMessage = true;
break;
case 'sigchild':
$text = "PHP was compiled with --enable-sigchild which can cause issues on some platforms.".PHP_EOL;
$text .= "Recompile it without this flag if possible, see also:".PHP_EOL;
$text .= " https://bugs.php.net/bug.php?id=22999";
break;
case 'curlwrappers':
$text = "PHP was compiled with --with-curlwrappers which will cause issues with HTTP authentication and GitHub.".PHP_EOL;
$text .= " Recompile it without this flag if possible";
break;
case 'php':
$text = "Your PHP ({$current}) is quite old, upgrading to PHP 5.3.4 or higher is recommended.".PHP_EOL;
$text .= " Composer works with 5.3.2+ for most people, but there might be edge case issues.";
break;
case 'openssl_version':
// Attempt to parse version number out, fallback to whole string value.
$opensslVersion = strstr(trim(strstr(<API key>, ' ')), ' ', true);
$opensslVersion = $opensslVersion ?: <API key>;
$text = "The OpenSSL library ({$opensslVersion}) used by PHP does not support TLSv1.2 or TLSv1.1.".PHP_EOL;
$text .= "If possible you should upgrade OpenSSL to version 1.0.1 or above.";
break;
case 'xdebug_loaded':
$text = "The xdebug extension is loaded, this can slow down Composer a little.".PHP_EOL;
$text .= " Disabling it when using Composer is recommended.";
break;
case 'xdebug_profile':
$text = "The xdebug.profiler_enabled setting is enabled, this can slow down Composer a lot.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini` to disable it:".PHP_EOL;
$text .= " xdebug.profiler_enabled = 0";
$displayIniMessage = true;
break;
}
$out($text, 'comment');
}
}
if ($displayIniMessage) {
$out($iniMessage, 'comment');
}
return !$warnings && !$errors ? true : $output;
}
/**
* Check if allow_url_fopen is ON
*
* @return bool|string
*/
private function checkConnectivity()
{
if (!ini_get('allow_url_fopen')) {
$result = '<info>Skipped because allow_url_fopen is missing.</info>';
return $result;
}
return true;
}
}
|
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/i2c.h>
#include <linux/uaccess.h>
#include <linux/miscdevice.h>
#include <media/msm_camera.h>
#include <mach/gpio.h>
#include "mt9d113.h"
#define <API key>
#ifdef <API key>
#define <API key>
#endif
#if defined(<API key>)
#include <linux/workqueue.h>
static struct platform_device *pdev_wq = NULL;
static struct workqueue_struct *mt9d113_wq = NULL;
static void mt9d113_workqueue(struct work_struct *work);
static DECLARE_WORK(mt9d113_cb_work, mt9d113_workqueue);
#endif
#define MT9D113_CAMIO_MCLK 24000000
#define <API key> "mt9d113"
#define MT9D113_I2C_BUS_ID (0)
#define <API key> 0x78
#define <API key> 0x79
#define <API key> 0x0000
#define MT9D113_MODEL_ID 0x2580
#define <API key> 0x31FE
#define <API key> 0x0003
#define <API key> 0x0018
#if defined(CONFIG_MACH_R750) || defined(CONFIG_MACH_JOE)
#define <API key> 39
#define <API key> 0
#else
#undef <API key>
#undef <API key>
#endif
struct mt9d113_work_t {
struct work_struct work;
};
struct mt9d113_ctrl_t {
const struct <API key> *sensordata;
};
static struct mt9d113_work_t *mt9d113_sensorw = NULL;
static struct i2c_client *mt9d113_client = NULL;
static struct mt9d113_ctrl_t *mt9d113_ctrl = NULL;
static uint16_t model_id;
DECLARE_MUTEX(mt9d113_sem);
static struct wake_lock mt9d113_wake_lock;
static int mt9d113_sensor_init(const struct <API key> *data);
static int <API key>(void __user *argp);
static int <API key>(void);
static int <API key>(void);
static int32_t <API key>(void);
static void <API key>(void);
extern int32_t <API key>(enum <API key> pwr_mode);
extern int <API key>(const struct <API key> *data,
uint32_t gpio_switch,
uint32_t switch_val);
#ifdef CONFIG_ZTE_PLATFORM
#ifdef <API key>
extern int zte_get_ftm_flag(void);
#endif
#endif
static inline void <API key>(void)
{
CDBG("%s: entry\n", __func__);
wake_lock_init(&mt9d113_wake_lock, WAKE_LOCK_IDLE, "mt9d113");
}
static inline void <API key>(void)
{
CDBG("%s: entry\n", __func__);
wake_lock_destroy(&mt9d113_wake_lock);
}
static inline void <API key>(void)
{
CDBG("%s: entry\n", __func__);
wake_lock(&mt9d113_wake_lock);
}
static inline void <API key>(void)
{
CDBG("%s: entry\n", __func__);
wake_unlock(&mt9d113_wake_lock);
}
static int <API key>(const struct <API key> *dev, uint32_t on)
{
int rc;
CDBG("%s: entry\n", __func__);
rc = gpio_request(dev->sensor_pwd, "mt9d113");
if (0 == rc)
{
rc = <API key>(dev->sensor_pwd, on);
mdelay(10);
}
gpio_free(dev->sensor_pwd);
return rc;
}
static int mt9d113_hard_reset(const struct <API key> *dev)
{
int rc = 0;
CDBG("%s: entry\n", __func__);
rc = gpio_request(dev->sensor_reset, "mt9d113");
if (0 == rc)
{
rc = <API key>(dev->sensor_reset, 1);
mdelay(10);
rc = <API key>(dev->sensor_reset, 0);
mdelay(10);
rc = <API key>(dev->sensor_reset, 1);
mdelay(10);
}
gpio_free(dev->sensor_reset);
return rc;
}
static int32_t mt9d113_i2c_txdata(unsigned short saddr,
unsigned char *txdata,
int length)
{
struct i2c_msg msg[] = {
{
.addr = saddr,
.flags = 0,
.len = length,
.buf = txdata,
},
};
if (i2c_transfer(mt9d113_client->adapter, msg, 1) < 0)
{
CCRT("%s: failed!\n", __func__);
return -EIO;
}
return 0;
}
static int32_t mt9d113_i2c_write(unsigned short saddr,
unsigned short waddr,
unsigned short wdata,
enum mt9d113_width_t width)
{
int32_t rc = -EFAULT;
unsigned char buf[4];
memset(buf, 0, sizeof(buf));
switch (width)
{
case WORD_LEN:
{
buf[0] = (waddr & 0xFF00) >> 8;
buf[1] = (waddr & 0x00FF);
buf[2] = (wdata & 0xFF00) >> 8;
buf[3] = (wdata & 0x00FF);
rc = mt9d113_i2c_txdata(saddr, buf, 4);
}
break;
case BYTE_LEN:
{
buf[0] = waddr;
buf[1] = wdata;
rc = mt9d113_i2c_txdata(saddr, buf, 2);
}
break;
default:
{
rc = -EFAULT;
}
break;
}
if (rc < 0)
{
CCRT("%s: waddr = 0x%x, wdata = 0x%x, failed!\n", __func__, waddr, wdata);
}
return rc;
}
static int32_t <API key>(struct <API key> const *reg_conf_tbl,
int len)
{
uint32_t i;
int32_t rc = 0;
#ifdef <API key>
for (i = 0; i < len; i++)
{
rc = mt9d113_i2c_write(mt9d113_client->addr,
reg_conf_tbl[i].waddr,
reg_conf_tbl[i].wdata,
reg_conf_tbl[i].width);
if (rc < 0)
{
break;
}
if (reg_conf_tbl[i].mdelay_time != 0)
{
mdelay(reg_conf_tbl[i].mdelay_time);
}
if (0x00 == (!(i | 0xFFFFFFE0) && 0x0F))
{
mdelay(1);
}
}
#else
if(reg_conf_tbl == mt9d113_regs.prevsnap_tbl)
{
for (i = 0; i < len; i++)
{
rc = mt9d113_i2c_write(mt9d113_client->addr,
reg_conf_tbl[i].waddr,
reg_conf_tbl[i].wdata,
reg_conf_tbl[i].width);
if (rc < 0)
{
break;
}
if (reg_conf_tbl[i].mdelay_time != 0)
{
mdelay(reg_conf_tbl[i].mdelay_time);
}
if ((i < (len >> 6)) && (0x00 == (!(i | 0xFFFFFFE0) && 0x0F)))
{
mdelay(1);
}
}
}
else
{
for (i = 0; i < len; i++)
{
rc = mt9d113_i2c_write(mt9d113_client->addr,
reg_conf_tbl[i].waddr,
reg_conf_tbl[i].wdata,
reg_conf_tbl[i].width);
if (rc < 0)
{
break;
}
if (reg_conf_tbl[i].mdelay_time != 0)
{
mdelay(reg_conf_tbl[i].mdelay_time);
}
}
}
#endif
return rc;
}
static int mt9d113_i2c_rxdata(unsigned short saddr,
unsigned char *rxdata,
int length)
{
struct i2c_msg msgs[] = {
{
.addr = saddr,
.flags = 0,
.len = 2,
.buf = rxdata,
},
{
.addr = saddr,
.flags = I2C_M_RD,
.len = length,
.buf = rxdata,
},
};
if (i2c_transfer(mt9d113_client->adapter, msgs, 2) < 0)
{
CCRT("%s: failed!\n", __func__);
return -EIO;
}
return 0;
}
static int32_t mt9d113_i2c_read(unsigned short saddr,
unsigned short raddr,
unsigned short *rdata,
enum mt9d113_width_t width)
{
int32_t rc = 0;
unsigned char buf[4];
if (!rdata)
{
CCRT("%s: rdata points to NULL!\n", __func__);
return -EIO;
}
memset(buf, 0, sizeof(buf));
switch (width)
{
case WORD_LEN:
{
buf[0] = (raddr & 0xFF00) >> 8;
buf[1] = (raddr & 0x00FF);
rc = mt9d113_i2c_rxdata(saddr, buf, 2);
if (rc < 0)
{
return rc;
}
*rdata = buf[0] << 8 | buf[1];
}
break;
default:
{
rc = -EFAULT;
}
break;
}
if (rc < 0)
{
CCRT("%s: failed!\n", __func__);
}
return rc;
}
static int32_t __attribute__((unused)) mt9d113_af_trigger(void)
{
CDBG("%s: not supported!\n", __func__);
return 0;
}
static int32_t mt9d113_set_wb(int8_t wb_mode)
{
int32_t rc = 0;
CDBG("%s: entry: wb_mode=%d\n", __func__, wb_mode);
switch (wb_mode)
{
case CAMERA_WB_MODE_AWB:
{
rc = <API key>(mt9d113_regs.wb_auto_tbl,
mt9d113_regs.wb_auto_tbl_sz);
}
break;
case <API key>:
{
rc = <API key>(mt9d113_regs.wb_daylight_tbl,
mt9d113_regs.wb_daylight_tbl_sz);
}
break;
case <API key>:
{
rc = <API key>(mt9d113_regs.wb_incandescent_tbl,
mt9d113_regs.<API key>);
}
break;
case <API key>:
{
rc = <API key>(mt9d113_regs.wb_flourescant_tbl,
mt9d113_regs.<API key>);
}
break;
case <API key>:
{
rc = <API key>(mt9d113_regs.wb_cloudy_tbl,
mt9d113_regs.wb_cloudy_tbl_sz);
}
break;
default:
{
CCRT("%s: parameter error!\n", __func__);
rc = -EFAULT;
}
}
mdelay(100);
return rc;
}
static int32_t <API key>(int8_t contrast)
{
int32_t rc = 0;
CDBG("%s: entry: contrast=%d\n", __func__, contrast);
switch (contrast)
{
case CAMERA_CONTRAST_0:
{
rc = <API key>(mt9d113_regs.contrast_tbl[0],
mt9d113_regs.contrast_tbl_sz[0]);
}
break;
case CAMERA_CONTRAST_1:
{
rc = <API key>(mt9d113_regs.contrast_tbl[1],
mt9d113_regs.contrast_tbl_sz[1]);
}
break;
case CAMERA_CONTRAST_2:
{
rc = <API key>(mt9d113_regs.contrast_tbl[2],
mt9d113_regs.contrast_tbl_sz[2]);
}
break;
case CAMERA_CONTRAST_3:
{
rc = <API key>(mt9d113_regs.contrast_tbl[3],
mt9d113_regs.contrast_tbl_sz[3]);
}
break;
case CAMERA_CONTRAST_4:
{
rc = <API key>(mt9d113_regs.contrast_tbl[4],
mt9d113_regs.contrast_tbl_sz[4]);
}
break;
default:
{
CCRT("%s: parameter error!\n", __func__);
rc = -EFAULT;
}
}
mdelay(100);
return rc;
}
static int32_t <API key>(int8_t brightness)
{
int32_t rc = 0;
CCRT("%s: entry: brightness=%d\n", __func__, brightness);
switch (brightness)
{
case CAMERA_BRIGHTNESS_0:
{
rc = <API key>(mt9d113_regs.brightness_tbl[0],
mt9d113_regs.brightness_tbl_sz[0]);
}
break;
case CAMERA_BRIGHTNESS_1:
{
rc = <API key>(mt9d113_regs.brightness_tbl[1],
mt9d113_regs.brightness_tbl_sz[1]);
}
break;
case CAMERA_BRIGHTNESS_2:
{
rc = <API key>(mt9d113_regs.brightness_tbl[2],
mt9d113_regs.brightness_tbl_sz[2]);
}
break;
case CAMERA_BRIGHTNESS_3:
{
rc = <API key>(mt9d113_regs.brightness_tbl[3],
mt9d113_regs.brightness_tbl_sz[3]);
}
break;
case CAMERA_BRIGHTNESS_4:
{
rc = <API key>(mt9d113_regs.brightness_tbl[4],
mt9d113_regs.brightness_tbl_sz[4]);
}
break;
case CAMERA_BRIGHTNESS_5:
{
rc = <API key>(mt9d113_regs.brightness_tbl[5],
mt9d113_regs.brightness_tbl_sz[5]);
}
break;
case CAMERA_BRIGHTNESS_6:
{
rc = <API key>(mt9d113_regs.brightness_tbl[6],
mt9d113_regs.brightness_tbl_sz[6]);
}
break;
default:
{
CCRT("%s: parameter error!\n", __func__);
rc = -EFAULT;
}
}
return rc;
}
static int32_t <API key>(int8_t saturation)
{
int32_t rc = 0;
CCRT("%s: entry: saturation=%d\n", __func__, saturation);
switch (saturation)
{
case CAMERA_SATURATION_0:
{
rc = <API key>(mt9d113_regs.saturation_tbl[0],
mt9d113_regs.saturation_tbl_sz[0]);
}
break;
case CAMERA_SATURATION_1:
{
rc = <API key>(mt9d113_regs.saturation_tbl[1],
mt9d113_regs.saturation_tbl_sz[1]);
}
break;
case CAMERA_SATURATION_2:
{
rc = <API key>(mt9d113_regs.saturation_tbl[2],
mt9d113_regs.saturation_tbl_sz[2]);
}
break;
case CAMERA_SATURATION_3:
{
rc = <API key>(mt9d113_regs.saturation_tbl[3],
mt9d113_regs.saturation_tbl_sz[3]);
}
break;
case CAMERA_SATURATION_4:
{
rc = <API key>(mt9d113_regs.saturation_tbl[4],
mt9d113_regs.saturation_tbl_sz[4]);
}
break;
default:
{
CCRT("%s: parameter error!\n", __func__);
rc = -EFAULT;
}
}
mdelay(100);
return rc;
}
static int32_t <API key>(int8_t sharpness)
{
int32_t rc = 0;
CDBG("%s: entry: sharpness=%d\n", __func__, sharpness);
switch (sharpness)
{
case CAMERA_SHARPNESS_0:
{
rc = <API key>(mt9d113_regs.sharpness_tbl[0],
mt9d113_regs.sharpness_tbl_sz[0]);
}
break;
case CAMERA_SHARPNESS_1:
{
rc = <API key>(mt9d113_regs.sharpness_tbl[1],
mt9d113_regs.sharpness_tbl_sz[1]);
}
break;
case CAMERA_SHARPNESS_2:
{
rc = <API key>(mt9d113_regs.sharpness_tbl[2],
mt9d113_regs.sharpness_tbl_sz[2]);
}
break;
case CAMERA_SHARPNESS_3:
{
rc = <API key>(mt9d113_regs.sharpness_tbl[3],
mt9d113_regs.sharpness_tbl_sz[3]);
}
break;
case CAMERA_SHARPNESS_4:
{
rc = <API key>(mt9d113_regs.sharpness_tbl[4],
mt9d113_regs.sharpness_tbl_sz[4]);
}
break;
default:
{
CCRT("%s: parameter error!\n", __func__);
rc = -EFAULT;
}
}
return rc;
}
static int32_t mt9d113_set_iso(int8_t iso_val)
{
int32_t rc = 0;
CDBG("%s: entry: iso_val=%d\n", __func__, iso_val);
switch (iso_val)
{
case CAMERA_ISO_SET_AUTO:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20D, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0020, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20E, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0090, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0006, WORD_LEN);
if (rc < 0)
{
return rc;
}
mdelay(200);
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20D, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0020, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20E, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0090, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
case CAMERA_ISO_SET_HJR:
{
CCRT("%s: not supported!\n", __func__);
rc = -EFAULT;
}
break;
case CAMERA_ISO_SET_100:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20D, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0020, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20E, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0028, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
case CAMERA_ISO_SET_200:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20D, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0040, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20E, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0048, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
case CAMERA_ISO_SET_400:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20D, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0050, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA20E, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0080, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
case CAMERA_ISO_SET_800:
{
CCRT("%s: not supported!\n", __func__);
rc = -EFAULT;
}
break;
default:
{
CCRT("%s: parameter error!\n", __func__);
rc = -EFAULT;
}
}
mdelay(100);
return rc;
}
static int32_t <API key>(int8_t antibanding)
{
int32_t rc = 0;
CDBG("%s: entry: antibanding=%d\n", __func__, antibanding);
switch (antibanding)
{
case <API key>:
{
CCRT("%s: <API key> NOT supported!\n", __func__);
}
break;
case <API key>:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA118, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA11E, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA124, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA12A, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA404, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x00A0, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
case <API key>:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA118, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA11E, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA124, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA12A, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA404, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x00E0, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
case <API key>:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA118, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0001, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA11E, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0001, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA124, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0000, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA12A, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0001, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
default:
{
CCRT("%s: parameter error!\n", __func__);
rc = -EFAULT;
}
}
mdelay(100);
return rc;
}
static int32_t __attribute__((unused))<API key>(int8_t lensshading)
{
#if 0
int32_t rc = 0;
uint16_t brightness_lev = 0;
CDBG("%s: entry: lensshading=%d\n", __func__, lensshading);
if (0 == lensshading)
{
CCRT("%s: lens shading is disabled!\n", __func__);
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098E, 0x3835, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_read(mt9d113_client->addr, 0x0990, &brightness_lev, WORD_LEN);
if (rc < 0)
{
return rc;
}
if (brightness_lev < 5)
{
rc = <API key>(mt9d113_regs.<API key>, mt9d113_regs.<API key>);
if (rc < 0)
{
return rc;
}
}
else
{
rc = <API key>(mt9d113_regs.lens_for_indoor_tbl, mt9d113_regs.<API key>);
if (rc < 0)
{
return rc;
}
}
return rc;
#else
return 0;
#endif
}
static long <API key>(int8_t exposure)
{
long rc = 0;
CDBG("%s: entry: exposure=%d\n", __func__, exposure);
switch(exposure)
{
case CAMERA_EXPOSURE_0:
{
}
break;
case CAMERA_EXPOSURE_1:
{
}
break;
case CAMERA_EXPOSURE_2:
{
}
break;
case CAMERA_EXPOSURE_3:
{
}
break;
case CAMERA_EXPOSURE_4:
{
}
break;
default:
{
CCRT("%s: parameter error!\n", __func__);
return -EFAULT;
}
}
return rc;
}
static long mt9d113_reg_init(void)
{
long rc;
CDBG("%s: entry\n", __func__);
rc = <API key>(mt9d113_regs.prevsnap_tbl, mt9d113_regs.prevsnap_tbl_sz);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, <API key>, 0x0028, WORD_LEN);
if (rc < 0)
{
return rc;
}
mdelay(10);
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0006, WORD_LEN);
if (rc < 0)
{
return rc;
}
mdelay(300);
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
return 0;
}
static long <API key>(int32_t mode)
{
long rc = 0;
CDBG("%s: entry\n", __func__);
switch (mode)
{
case SENSOR_PREVIEW_MODE:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA115, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0000, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0001, WORD_LEN);
if (rc < 0)
{
return rc;
}
mdelay(80);
}
break;
case <API key>:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA115, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0002, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
default:
{
return -EFAULT;
}
}
return 0;
}
static long mt9d113_set_effect(int32_t mode, int32_t effect)
{
uint16_t __attribute__((unused)) reg_addr;
uint16_t __attribute__((unused)) reg_val;
long rc = 0;
switch (mode)
{
case SENSOR_PREVIEW_MODE:
{
}
break;
case <API key>:
{
}
break;
default:
{
}
break;
}
switch (effect)
{
case CAMERA_EFFECT_OFF:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2759, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6440, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x275B, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6440, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
case CAMERA_EFFECT_MONO:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2759, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6441, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x275B, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6441, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
case <API key>:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2759, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6443, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x275B, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6443, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
case <API key>:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2759, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6444, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x275B, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6444, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
case CAMERA_EFFECT_SEPIA:
{
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2763, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0xB023, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x2759, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6442, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x275B, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x6442, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN);
if (rc < 0)
{
return rc;
}
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0005, WORD_LEN);
if (rc < 0)
{
return rc;
}
}
break;
default:
{
return -EFAULT;
}
}
mdelay(100);
return rc;
}
static long mt9d113_power_up(void)
{
CDBG("%s: not supported!\n", __func__);
return 0;
}
static long mt9d113_power_down(void)
{
CDBG("%s: not supported!\n", __func__);
return 0;
}
#if 0
static int <API key>(uint32_t on)
{
int rc;
CDBG("%s: entry\n", __func__);
rc = gpio_request(<API key>, "mt9d113");
if (0 == rc)
{
rc = <API key>(<API key>, on);
mdelay(1);
}
gpio_free(<API key>);
return rc;
}
#endif
#if !defined(<API key>)
static int <API key>(const struct <API key> *data)
{
uint32_t switch_on;
int rc = 0;
CDBG("%s: entry\n", __func__);
#if 0
switch_on = 0;
rc = <API key>(switch_on);
if (rc < 0)
{
CCRT("enter/quit lowest-power mode failed!\n");
goto init_probe_fail;
}
#endif
switch_on = 0;
rc = <API key>(data, switch_on);
if (rc < 0)
{
CCRT("set standby failed!\n");
goto init_probe_fail;
}
rc = mt9d113_hard_reset(data);
if (rc < 0)
{
CCRT("hard reset failed!\n");
goto init_probe_fail;
}
model_id = 0x0000;
rc = mt9d113_i2c_read(mt9d113_client->addr, <API key>, &model_id, WORD_LEN);
if (rc < 0)
{
goto init_probe_fail;
}
CDBG("%s: model_id = 0x%x\n", __func__, model_id);
#ifdef CONFIG_SENSOR_INFO
<API key>(model_id);
#else
#endif
if (model_id != MT9D113_MODEL_ID)
{
rc = -EFAULT;
goto init_probe_fail;
}
rc = <API key>(mt9d113_regs.pll_tbl, mt9d113_regs.pll_tbl_sz);
if (rc < 0)
{
return rc;
}
model_id = 0x0000;
rc = mt9d113_i2c_read(mt9d113_client->addr, <API key>, &model_id, WORD_LEN);
if (rc < 0)
{
goto init_probe_fail;
}
CDBG("%s: model_id_sub = 0x%x\n", __func__, model_id);
#ifdef CONFIG_SENSOR_INFO
<API key>(model_id);
#else
#endif
if (model_id != <API key>)
{
rc = -EFAULT;
goto init_probe_fail;
}
rc = mt9d113_reg_init();
if (rc < 0)
{
goto init_probe_fail;
}
return rc;
init_probe_fail:
CCRT("%s: rc = %d, failed!\n", __func__, rc);
return rc;
}
#else
static int <API key>(void)
{
int rc;
struct i2c_board_info info;
struct i2c_adapter *adapter;
struct i2c_client *client;
rc = <API key>();
if (rc < 0)
{
CCRT("%s: add i2c driver failed!\n", __func__);
return rc;
}
memset(&info, 0, sizeof(struct i2c_board_info));
info.addr = <API key> >> 1;
strlcpy(info.type, <API key>, I2C_NAME_SIZE);
adapter = i2c_get_adapter(MT9D113_I2C_BUS_ID);
if (!adapter)
{
CCRT("%s: get i2c adapter failed!\n", __func__);
goto i2c_probe_failed;
}
client = i2c_new_device(adapter, &info);
i2c_put_adapter(adapter);
if (!client)
{
CCRT("%s: add i2c device failed!\n", __func__);
goto i2c_probe_failed;
}
mt9d113_client = client;
return 0;
i2c_probe_failed:
<API key>();
return -ENODEV;
}
static void <API key>(void)
{
<API key>(mt9d113_client);
<API key>();
}
static int <API key>(const struct <API key> *pinfo)
{
int rc;
rc = <API key>(<API key>);
if (rc < 0)
{
CCRT("%s: <API key> failed!\n", __func__);
return rc;
}
#if defined(CONFIG_MACH_R750) || defined(CONFIG_MACH_JOE)
rc = <API key>(pinfo, <API key>, <API key>);
if (rc < 0)
{
CCRT("%s: camera_clk_switch failed!\n", __func__);
return rc;;
}
#else
#endif
<API key>(MT9D113_CAMIO_MCLK);
mdelay(5);
rc = <API key>(pinfo, 0);
if (rc < 0)
{
CCRT("set standby failed!\n");
return rc;
}
rc = mt9d113_hard_reset(pinfo);
if (rc < 0)
{
CCRT("hard reset failed!\n");
return rc;
}
model_id = 0x0000;
rc = mt9d113_i2c_read(mt9d113_client->addr, <API key>, &model_id, WORD_LEN);
if (rc < 0)
{
return rc;
}
CDBG("%s: model_id = 0x%x\n", __func__, model_id);
#ifdef CONFIG_SENSOR_INFO
<API key>(model_id);
#else
#endif
if (model_id != MT9D113_MODEL_ID)
{
return -EFAULT;
}
rc = <API key>(mt9d113_regs.pll_tbl, mt9d113_regs.pll_tbl_sz);
if (rc < 0)
{
return rc;
}
model_id = 0x0000;
rc = mt9d113_i2c_read(mt9d113_client->addr, <API key>, &model_id, WORD_LEN);
if (rc < 0)
{
return rc;
}
CDBG("%s: model_id_sub = 0x%x\n", __func__, model_id);
#ifdef CONFIG_SENSOR_INFO
<API key>(model_id);
#else
#endif
if (model_id != <API key>)
{
return -EFAULT;
}
return 0;
}
#endif
static int <API key>(const struct <API key> *data)
{
int rc;
CDBG("%s: entry\n", __func__);
if (!data || strcmp(data->sensor_name, "mt9d113"))
{
CCRT("%s: invalid parameters!\n", __func__);
rc = -ENODEV;
goto probe_init_fail;
}
mt9d113_ctrl = kzalloc(sizeof(struct mt9d113_ctrl_t), GFP_KERNEL);
if (!mt9d113_ctrl)
{
CCRT("%s: kzalloc failed!\n", __func__);
rc = -ENOMEM;
goto probe_init_fail;
}
mt9d113_ctrl->sensordata = data;
#if !defined(<API key>)
rc = <API key>(<API key>);
if (rc < 0)
{
CCRT("%s: <API key> failed!\n", __func__);
goto probe_init_fail;
}
#if defined(CONFIG_MACH_R750) || defined(CONFIG_MACH_JOE)
rc = <API key>(mt9d113_ctrl->sensordata, <API key>, <API key>);
if (rc < 0)
{
CCRT("%s: camera_clk_switch failed!\n", __func__);
goto probe_init_fail;
}
#else
#endif
<API key>(MT9D113_CAMIO_MCLK);
mdelay(5);
rc = <API key>(mt9d113_ctrl->sensordata);
if (rc < 0)
{
CCRT("%s: sensor_init_probe failed!\n", __func__);
goto probe_init_fail;
}
#else
rc = <API key>(mt9d113_ctrl->sensordata);
if (rc < 0)
{
CCRT("%s: <API key> failed!\n", __func__);
goto probe_init_fail;
}
rc = mt9d113_reg_init();
if (rc < 0)
{
CCRT("%s: mt9d113_reg_init failed!\n", __func__);
goto probe_init_fail;
}
#endif
return 0;
probe_init_fail:
<API key>(<API key>);
if(mt9d113_ctrl)
{
kfree(mt9d113_ctrl);
}
return rc;
}
#ifdef <API key>
static int mt9d113_sensor_init(const struct <API key> *data)
{
uint32_t switch_on;
int rc;
CDBG("%s: entry\n", __func__);
if ((NULL == data)
|| strcmp(data->sensor_name, "mt9d113")
|| strcmp(mt9d113_ctrl->sensordata->sensor_name, "mt9d113"))
{
CCRT("%s: data is NULL, or sensor_name is not equal to mt9d113!\n", __func__);
rc = -ENODEV;
goto sensor_init_fail;
}
rc = <API key>(<API key>);
if (rc < 0)
{
CCRT("%s: <API key> failed!\n", __func__);
goto sensor_init_fail;
}
<API key>(MT9D113_CAMIO_MCLK);
mdelay(5);
<API key>();
mdelay(10);
switch_on = 0;
rc = <API key>(mt9d113_ctrl->sensordata, switch_on);
if (rc < 0)
{
CCRT("set standby failed!\n");
goto sensor_init_fail;
}
mdelay(10);
return 0;
sensor_init_fail:
return rc;
}
#else
static int mt9d113_sensor_init(const struct <API key> *data)
{
int rc;
rc = <API key>(data);
return rc;
}
#endif
static int <API key>(void __user *argp)
{
struct sensor_cfg_data cfg_data;
long rc = 0;
CDBG("%s: entry\n", __func__);
if (copy_from_user(&cfg_data, (void *)argp, sizeof(struct sensor_cfg_data)))
{
CCRT("%s: copy_from_user failed!\n", __func__);
return -EFAULT;
}
CDBG("%s: cfgtype = %d, mode = %d\n", __func__, cfg_data.cfgtype, cfg_data.mode);
switch (cfg_data.cfgtype)
{
case CFG_SET_MODE:
{
rc = <API key>(cfg_data.mode);
}
break;
case CFG_SET_EFFECT:
{
rc = mt9d113_set_effect(cfg_data.mode, cfg_data.cfg.effect);
}
break;
case CFG_PWR_UP:
{
rc = mt9d113_power_up();
}
break;
case CFG_PWR_DOWN:
{
rc = mt9d113_power_down();
}
break;
case CFG_SET_WB:
{
rc = mt9d113_set_wb(cfg_data.cfg.wb_mode);
}
break;
case CFG_SET_AF:
{
rc = 0;
}
break;
case CFG_SET_ISO:
{
rc = mt9d113_set_iso(cfg_data.cfg.iso_val);
}
break;
case CFG_SET_ANTIBANDING:
{
rc = <API key>(cfg_data.cfg.antibanding);
}
break;
case CFG_SET_BRIGHTNESS:
{
rc = <API key>(cfg_data.cfg.brightness);
}
break;
case CFG_SET_SATURATION:
{
rc = <API key>(cfg_data.cfg.saturation);
}
break;
case CFG_SET_CONTRAST:
{
rc = <API key>(cfg_data.cfg.contrast);
}
break;
case CFG_SET_SHARPNESS:
{
rc = <API key>(cfg_data.cfg.sharpness);
}
break;
case <API key>:
{
rc = 0;
}
break;
case <API key>:
{
rc = <API key>(cfg_data.cfg.exposure);
}
break;
default:
{
rc = -EFAULT;
}
break;
}
<API key>();
return rc;
}
#ifdef <API key>
static int <API key>(void)
{
int rc;
uint32_t switch_on;
CDBG("%s: entry\n", __func__);
rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0028, 0x0000, WORD_LEN);
if (rc < 0)
{
return rc;
}
mdelay(1);
switch_on = 1;
rc = <API key>(mt9d113_ctrl->sensordata, switch_on);
if (rc < 0)
{
return rc;
}
mdelay(200);
rc = <API key>(<API key>);
if (rc < 0)
{
return rc;
}
return 0;
}
#else
static int <API key>(void)
{
int rc;
rc = <API key>(<API key>);
kfree(mt9d113_ctrl);
return rc;
}
#endif
static int <API key>(void)
{
int rc;
rc = <API key>();
<API key>();
return rc;
}
static int mt9d113_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
int rc = 0;
CDBG("%s: entry\n", __func__);
if (!<API key>(client->adapter, I2C_FUNC_I2C))
{
rc = -ENOTSUPP;
goto probe_failure;
}
mt9d113_sensorw = kzalloc(sizeof(struct mt9d113_work_t), GFP_KERNEL);
if (!mt9d113_sensorw)
{
rc = -ENOMEM;
goto probe_failure;
}
i2c_set_clientdata(client, mt9d113_sensorw);
mt9d113_client = client;
return 0;
probe_failure:
kfree(mt9d113_sensorw);
mt9d113_sensorw = NULL;
CCRT("%s: rc = %d, failed!\n", __func__, rc);
return rc;
}
static int __exit mt9d113_i2c_remove(struct i2c_client *client)
{
struct mt9d113_work_t *sensorw = i2c_get_clientdata(client);
CDBG("%s: entry\n", __func__);
free_irq(client->irq, sensorw);
kfree(sensorw);
<API key>();
mt9d113_client = NULL;
mt9d113_sensorw = NULL;
return 0;
}
static const struct i2c_device_id mt9d113_id[] = {
{ "mt9d113", 0},
{ },
};
static struct i2c_driver mt9d113_driver = {
.id_table = mt9d113_id,
.probe = mt9d113_i2c_probe,
.remove = __exit_p(mt9d113_i2c_remove),
.driver = {
.name = <API key>,
},
};
static int32_t <API key>(void)
{
int32_t rc = 0;
rc = i2c_add_driver(&mt9d113_driver);
if (IS_ERR_VALUE(rc))
{
goto init_failure;
}
return rc;
init_failure:
CCRT("%s: rc = %d, failed!\n", __func__, rc);
return rc;
}
static void <API key>(void)
{
i2c_del_driver(&mt9d113_driver);
}
void mt9d113_exit(void)
{
CDBG("%s: entry\n", __func__);
<API key>();
}
int <API key>(const struct <API key> *info,
struct msm_sensor_ctrl *s)
{
int rc;
CDBG("%s: entry\n", __func__);
#if !defined(<API key>)
rc = <API key>();
if (rc < 0)
{
goto probe_failed;
}
#else
#endif
#ifdef <API key>
rc = <API key>(info);
if (rc < 0)
{
CCRT("%s: <API key> failed!\n", __func__);
goto probe_failed;
}
rc = <API key>();
if (rc < 0)
{
CCRT("%s: <API key> failed!\n", __func__);
goto probe_failed;
}
#endif
<API key>();
s->s_init = mt9d113_sensor_init;
s->s_config = <API key>;
s->s_release = <API key>;
return 0;
probe_failed:
CCRT("%s: rc = %d, failed!\n", __func__, rc);
#if !defined(<API key>)
<API key>();
#else
#endif
return rc;
}
#if defined(<API key>)
static void mt9d113_workqueue(struct work_struct *work)
{
int32_t rc;
#ifdef CONFIG_ZTE_PLATFORM
#ifdef <API key>
if(zte_get_ftm_flag())
{
return;
}
#endif
#endif
if (!pdev_wq)
{
CCRT("%s: pdev_wq is NULL!\n", __func__);
return;
}
#if !defined(<API key>)
rc = <API key>(pdev_wq, <API key>);
#else
rc = <API key>(pdev_wq,
<API key>,
<API key>,
<API key>);
if (rc < 0)
{
CCRT("%s: <API key> failed!\n", __func__);
goto probe_failed;
}
rc = <API key>(pdev_wq, <API key>);
if (rc < 0)
{
goto probe_failed;
}
return;
probe_failed:
CCRT("%s: rc = %d, failed!\n", __func__, rc);
<API key>(<API key>);
return;
#endif
}
static int32_t <API key>(void)
{
int32_t rc;
mt9d113_wq = <API key>("mt9d113_wq");
if (!mt9d113_wq)
{
CCRT("%s: mt9d113_wq is NULL!\n", __func__);
return -EFAULT;
}
rc = queue_work(mt9d113_wq, &mt9d113_cb_work);
return 0;
}
static int __mt9d113_probe(struct platform_device *pdev)
{
int32_t rc;
pdev_wq = pdev;
rc = <API key>();
return rc;
}
#else
static int __mt9d113_probe(struct platform_device *pdev)
{
#ifdef CONFIG_ZTE_PLATFORM
#ifdef <API key>
if(zte_get_ftm_flag())
{
return 0;
}
#endif
#endif
return <API key>(pdev, <API key>);
}
#endif
static struct platform_driver msm_camera_driver = {
.probe = __mt9d113_probe,
.driver = {
.name = "msm_camera_mt9d113",
.owner = THIS_MODULE,
},
};
static int __init mt9d113_init(void)
{
return <API key>(&msm_camera_driver);
}
module_init(mt9d113_init);
|
#include <bsp.h>
#include <libchip/rtc.h>
#include <ds1307.h>
/* Forward function declaration */
bool <API key>(int minor);
extern rtc_fns ds1307_fns;
/* The following table configures the RTC drivers used in this BSP */
rtc_tbl RTC_Table[] = {
{
"/dev/rtc", /* sDeviceName */
RTC_CUSTOM, /* deviceType */
&ds1307_fns, /* pDeviceFns */
<API key>, /* deviceProbe */
NULL, /* pDeviceParams */
0x00, /* ulCtrlPort1, for DS1307-I2C bus number */
DS1307_I2C_ADDRESS, /* ulDataPort, for DS1307-I2C device addr */
NULL, /* getRegister - not applicable to DS1307 */
NULL /* setRegister - not applicable to DS1307 */
}
};
/* Some information used by the RTC driver */
#define NUM_RTCS (sizeof(RTC_Table)/sizeof(rtc_tbl))
size_t RTC_Count = NUM_RTCS;
<API key> RTC_Minor;
/* <API key> --
* RTC presence probe function. Return TRUE, if device is present.
* Device presence checked by probe access to RTC device over I2C bus.
*
* PARAMETERS:
* minor - minor RTC device number
*
* RETURNS:
* TRUE, if RTC device is present
*/
bool
<API key>(int minor)
{
int try = 0;
i2c_message_status status;
rtc_tbl *rtc;
i2c_bus_number bus;
i2c_address addr;
if (minor >= NUM_RTCS)
return false;
rtc = RTC_Table + minor;
bus = rtc->ulCtrlPort1;
addr = rtc->ulDataPort;
do {
status = i2c_wrbyte(bus, addr, 0);
if (status == I2C_NO_DEVICE)
return false;
try++;
} while ((try < 15) && (status != I2C_SUCCESSFUL));
if (status == I2C_SUCCESSFUL)
return true;
else
return false;
}
|
/* { dg-do compile } */
/* { dg-options "-O2 -<API key>" } */
/* LLVM LOCAL test not applicable */
/* { dg-require-fdump "" } */
class YY { public:
YY(const YY &v) { e[0] = v.e[0]; e[1] = v.e[1]; e[2] = v.e[2]; }
double &y() { return e[1]; }
double e[3]; };
class XX { public:
YY direction() const { return v; }
YY v; };
int foo(XX& r) {
if (r.direction().y() < 0.000001) return 0;
return 1; }
/* { dg-final { <API key> "&this" 0 "forwprop2" } } */
/* { dg-final { <API key> "&r" 0 "forwprop2" } } */
/* { dg-final { cleanup-tree-dump "forwprop2" } } */
|
*//**
/** @addtogroup QEI
* @{
*/
#include "lpc18xx_qei.h"
#include "lpc18xx_cgu.h"
/* If this source file built with example, the LPC18xx FW library configuration
* file in each example directory ("lpc18xx_libcfg.h") must be included,
* otherwise the default FW library configuration file must be included instead
*/
#ifdef <API key>
#include "lpc18xx_libcfg.h"
#else
#include "<API key>.h"
#endif /* <API key> */
#ifdef _QEI
/** @defgroup QEI_Private_Types QEI Private Types
* @{
*/
/**
* @brief QEI configuration union type definition
*/
typedef union {
QEI_CFG_Type bmQEIConfig;
uint32_t ulQEIConfig;
} QEI_CFGOPT_Type;
LPC_QEI_Type* QEI_GetPointer(uint8_t qeiId);
/** @addtogroup <API key>
* @{
*/
/**
* @brief Get the point to typedef of QEI component
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @return None
**********************************************************************/
LPC_QEI_Type* QEI_GetPointer(uint8_t qeiId)
{
LPC_QEI_Type* pQei = NULL;
if(qeiId == 0)
{
pQei = LPC_QEI;
}
return pQei;
}
/**
* @brief Resets value for each type of QEI value, such as velocity,
* counter, position, etc..
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulResetType QEI Reset Type, should be one of the following:
* - QEI_RESET_POS :Reset Position Counter
* - QEI_RESET_POSOnIDX :Reset Position Counter on Index signal
* - QEI_RESET_VEL :Reset Velocity
* - QEI_RESET_IDX :Reset Index Counter
* @return None
**********************************************************************/
void QEI_Reset(uint8_t qeiId, uint32_t ulResetType)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
pQei->CON = ulResetType;
}
/**
* @brief Initializes the QEI peripheral according to the specified
* parameters in the QEI_ConfigStruct.
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] QEI_ConfigStruct Pointer to a QEI_CFG_Type structure
* that contains the configuration information for the
* specified QEI peripheral
* @return None
**********************************************************************/
void QEI_Init(uint8_t qeiId, QEI_CFG_Type *QEI_ConfigStruct)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
/* Set up clock and power for QEI module */
// Already enabled by BASE_M3_CLK
// Reset all remaining value in QEI peripheral
pQei->MAXPOS = 0x00;
pQei->CMPOS0 = 0x00;
pQei->CMPOS1 = 0x00;
pQei->CMPOS2 = 0x00;
pQei->INXCMP0 = 0x00;
pQei->VELCOMP = 0x00;
pQei->LOAD = 0x00;
pQei->CON = QEI_CON_RESP | QEI_CON_RESV | QEI_CON_RESI;
pQei->FILTERPHA = 0x00;
pQei->FILTERPHB = 0x00;
pQei->FILTERINX = 0x00;
// Disable all Interrupt
pQei->IEC = QEI_IECLR_BITMASK;
// Clear all Interrupt pending
pQei->CLR = QEI_INTCLR_BITMASK;
// Set QEI configuration value corresponding to its setting up value
pQei->CONF = ((QEI_CFGOPT_Type *)QEI_ConfigStruct)->ulQEIConfig;
}
/**
* @brief De-Initalize QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @return None
**********************************************************************/
void QEI_DeInit(uint8_t qeiId)
{
/* Turn off clock and power for QEI module */
}
/**
* @brief Fills each QIE_InitStruct member with its default value:
* - DirectionInvert = QEI_DIRINV_NONE
* - SignalMode = QEI_SIGNALMODE_QUAD
* - CaptureMode = QEI_CAPMODE_4X
* - InvertIndex = QEI_INVINX_NONE
* @param[in] QIE_InitStruct Pointer to a QEI_CFG_Type structure which will be
* initialized.
* @return None
*******************************************************************************/
void QEI_GetCfgDefault(QEI_CFG_Type *QIE_InitStruct)
{
QIE_InitStruct->CaptureMode = QEI_CAPMODE_4X;
QIE_InitStruct->DirectionInvert = QEI_DIRINV_NONE;
QIE_InitStruct->InvertIndex = QEI_INVINX_NONE;
QIE_InitStruct->SignalMode = QEI_SIGNALMODE_QUAD;
}
/**
* @brief Check whether if specified flag status is set or not
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulFlagType Status Flag Type, should be one of the following:
* - QEI_STATUS_DIR: Direction Status
* @return New Status of this status flag (SET or RESET)
**********************************************************************/
FlagStatus QEI_GetStatus(uint8_t qeiId, uint32_t ulFlagType)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
return ((pQei->STAT & ulFlagType) ? SET : RESET);
}
/**
* @brief Get current position value in QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @return Current position value of QEI peripheral
**********************************************************************/
uint32_t QEI_GetPosition(uint8_t qeiId)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
return (pQei->POS);
}
/**
* @brief Set max position value for QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulMaxPos Max position value to set
* @return None
**********************************************************************/
void QEI_SetMaxPosition(uint8_t qeiId, uint32_t ulMaxPos)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
pQei->MAXPOS = ulMaxPos;
}
/**
* @brief Set position compare value for QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] bPosCompCh Compare Position channel, should be:
* - QEI_COMPPOS_CH_0 :QEI compare position channel 0
* - QEI_COMPPOS_CH_1 :QEI compare position channel 1
* - QEI_COMPPOS_CH_2 :QEI compare position channel 2
* @param[in] ulPosComp Compare Position value to set
* @return None
**********************************************************************/
void QEI_SetPositionComp(uint8_t qeiId, uint8_t bPosCompCh, uint32_t ulPosComp)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
uint32_t *tmp;
tmp = (uint32_t *) (&(pQei->CMPOS0) + bPosCompCh * 4);
*tmp = ulPosComp;
}
/**
* @brief Get current index counter of QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @return Current value of QEI index counter
**********************************************************************/
uint32_t QEI_GetIndex(uint8_t qeiId)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
return (pQei->INXCNT);
}
/**
* @brief Set value for index compare in QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulIndexComp Compare Index Value to set
* @return None
**********************************************************************/
void QEI_SetIndexComp(uint8_t qeiId, uint32_t ulIndexComp)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
pQei->INXCMP0 = ulIndexComp;
}
/**
* @brief Set timer reload value for QEI peripheral. When the velocity timer is
* over-flow, the value that set for Timer Reload register will be loaded
* into the velocity timer for next period. The calculated velocity in RPM
* therefore will be affect by this value.
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] QEIReloadStruct QEI reload structure
* @return None
**********************************************************************/
void QEI_SetTimerReload(uint8_t qeiId, QEI_RELOADCFG_Type *QEIReloadStruct)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
uint64_t pclk;
if (QEIReloadStruct->ReloadOption == <API key>)
{
pQei->LOAD = QEIReloadStruct->ReloadValue - 1;
}
else
{
#if 1
pclk = <API key>(<API key>);
pclk = (pclk /(1000000/QEIReloadStruct->ReloadValue)) - 1;
pQei->LOAD = (uint32_t)pclk;
#else
ld = M3Frequency;
if (ld/1000000 > 0)
{
ld /= 1000000;
ld *= QEIReloadStruct->ReloadValue;
ld -= 1;
}
else
{
ld *= QEIReloadStruct->ReloadValue;
ld /= 1000000;
ld -= 1;
}
pQei->LOAD = ld;
#endif
}
}
/**
* @brief Get current timer counter in QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @return Current timer counter in QEI peripheral
**********************************************************************/
uint32_t QEI_GetTimer(uint8_t qeiId)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
return (pQei->TIME);
}
/**
* @brief Get current velocity pulse counter in current time period
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @return Current velocity pulse counter value
**********************************************************************/
uint32_t QEI_GetVelocity(uint8_t qeiId)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
return (pQei->VEL);
}
/**
* @brief Get the most recently measured velocity of the QEI. When
* the Velocity timer in QEI is over-flow, the current velocity
* value will be loaded into Velocity Capture register.
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @return The most recently measured velocity value
**********************************************************************/
uint32_t QEI_GetVelocityCap(uint8_t qeiId)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
return (pQei->CAP);
}
/**
* @brief Set Velocity Compare value for QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulVelComp Compare Velocity value to set
* @return None
**********************************************************************/
void QEI_SetVelocityComp(uint8_t qeiId, uint32_t ulVelComp)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
pQei->VELCOMP = ulVelComp;
}
/**
* @brief Set value of sampling count for the digital filter in
* QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulSamplingPulse Value of sampling count to set
* @return None
**********************************************************************/
void QEI_SetDigiFilter(uint8_t qeiId, st_Qei_FilterCfg FilterVal)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
pQei->FILTERPHA = FilterVal.PHA_FilterVal;
pQei->FILTERPHB = FilterVal.PHB_FilterVal;
pQei->FILTERINX = FilterVal.INX_FilterVal;
}
/**
* @brief Check whether if specified interrupt flag status in QEI
* peripheral is set or not
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulIntType Interrupt Flag Status type, should be:
* - QEI_INTFLAG_INX_Int : index pulse was detected interrupt
* - QEI_INTFLAG_TIM_Int : Velocity timer over flow interrupt
* - <API key> : Capture velocity is less than compare interrupt
* - QEI_INTFLAG_DIR_Int : Change of direction interrupt
* - QEI_INTFLAG_ERR_Int : An encoder phase error interrupt
* - <API key> : An encoder clock pulse was detected interrupt
* - <API key> : position 0 compare value is equal to the current position interrupt
* - <API key> : position 1 compare value is equal to the current position interrupt
* - <API key> : position 2 compare value is equal to the current position interrupt
* - QEI_INTFLAG_REV_Int : Index compare value is equal to the current index count interrupt
* - <API key> : Combined position 0 and revolution count interrupt
* - <API key> : Combined position 1 and revolution count interrupt
* - <API key> : Combined position 2 and revolution count interrupt
* @return New State of specified interrupt flag status (SET or RESET)
**********************************************************************/
FlagStatus QEI_GetIntStatus(uint8_t qeiId, uint32_t ulIntType)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
return((pQei->INTSTAT & ulIntType) ? SET : RESET);
}
/**
* @brief Enable/Disable specified interrupt in QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulIntType Interrupt Flag Status type, should be:
* - QEI_INTFLAG_INX_Int : index pulse was detected interrupt
* - QEI_INTFLAG_TIM_Int : Velocity timer over flow interrupt
* - <API key> : Capture velocity is less than compare interrupt
* - QEI_INTFLAG_DIR_Int : Change of direction interrupt
* - QEI_INTFLAG_ERR_Int : An encoder phase error interrupt
* - <API key> : An encoder clock pulse was detected interrupt
* - <API key> : position 0 compare value is equal to the current position interrupt
* - <API key> : position 1 compare value is equal to the current position interrupt
* - <API key> : position 2 compare value is equal to the current position interrupt
* - QEI_INTFLAG_REV_Int : Index compare value is equal to the current index count interrupt
* - <API key> : Combined position 0 and revolution count interrupt
* - <API key> : Combined position 1 and revolution count interrupt
* - <API key> : Combined position 2 and revolution count interrupt
* @param[in] NewState New function state, should be:
* - DISABLE
* - ENABLE
* @return None
**********************************************************************/
void QEI_IntCmd(uint8_t qeiId, uint32_t ulIntType, FunctionalState NewState)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
if (NewState == ENABLE)
{
pQei->IES = ulIntType;
}
else
{
pQei->IEC = ulIntType;
}
}
/**
* @brief Sets (forces) specified interrupt in QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulIntType Interrupt Flag Status type, should be:
* - QEI_INTFLAG_INX_Int : index pulse was detected interrupt
* - QEI_INTFLAG_TIM_Int : Velocity timer over flow interrupt
* - <API key> : Capture velocity is less than compare interrupt
* - QEI_INTFLAG_DIR_Int : Change of direction interrupt
* - QEI_INTFLAG_ERR_Int : An encoder phase error interrupt
* - <API key> : An encoder clock pulse was detected interrupt
* - <API key> : position 0 compare value is equal to the current position interrupt
* - <API key> : position 1 compare value is equal to the current position interrupt
* - <API key> : position 2 compare value is equal to the current position interrupt
* - QEI_INTFLAG_REV_Int : Index compare value is equal to the current index count interrupt
* - <API key> : Combined position 0 and revolution count interrupt
* - <API key> : Combined position 1 and revolution count interrupt
* - <API key> : Combined position 2 and revolution count interrupt
* @return None
**********************************************************************/
void QEI_IntSet(uint8_t qeiId, uint32_t ulIntType)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
pQei->SET = ulIntType;
}
/**
* @brief Clear (force) specified interrupt (pending) in QEI peripheral
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulIntType Interrupt Flag Status type, should be:
* - QEI_INTFLAG_INX_Int : index pulse was detected interrupt
* - QEI_INTFLAG_TIM_Int : Velocity timer over flow interrupt
* - <API key> : Capture velocity is less than compare interrupt
* - QEI_INTFLAG_DIR_Int : Change of direction interrupt
* - QEI_INTFLAG_ERR_Int : An encoder phase error interrupt
* - <API key> : An encoder clock pulse was detected interrupt
* - <API key> : position 0 compare value is equal to the current position interrupt
* - <API key> : position 1 compare value is equal to the current position interrupt
* - <API key> : position 2 compare value is equal to the current position interrupt
* - QEI_INTFLAG_REV_Int : Index compare value is equal to the current index count interrupt
* - <API key> : Combined position 0 and revolution count interrupt
* - <API key> : Combined position 1 and revolution count interrupt
* - <API key> : Combined position 2 and revolution count interrupt
* @return None
**********************************************************************/
void QEI_IntClear(uint8_t qeiId, uint32_t ulIntType)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
pQei->CLR = ulIntType;
}
/**
* @brief Calculates the actual velocity in RPM passed via velocity
* capture value and Pulse Per Round (of the encoder) value
* parameter input.
* @param[in] qeiId The Id of the expected QEI component, should be: 0
* @param[in] ulVelCapValue Velocity capture input value that can be
* got from QEI_GetVelocityCap() function
* @param[in] ulPPR Pulse per round of encoder
* @return The actual value of velocity in RPM (Round per minute)
**********************************************************************/
uint32_t QEI_CalculateRPM(uint8_t qeiId, uint32_t ulVelCapValue, uint32_t ulPPR)
{
LPC_QEI_Type* pQei = QEI_GetPointer(qeiId);
uint64_t rpm, clock, Load, edges;
// Get current Clock rate for timer input
clock = <API key>(<API key>);
// Get Timer load value (velocity capture period)
Load = (uint64_t)(pQei->LOAD + 1);
// Get Edge
edges = (uint64_t)((pQei->CONF & QEI_CONF_CAPMODE) ? 4 : 2);
// Calculate RPM
rpm = ((clock * ulVelCapValue * 60) / (Load * ulPPR * edges));
return (uint32_t)(rpm);
}
#endif /* _QEI */
|
#ifndef __SDCPP_H
#define __SDCPP_H
#ifdef _WIN32
/* declaration of alloca */
#include <malloc.h>
#include <string.h>
#ifdef __BORLANDC__
#define strcasecmp stricmp
#else
#define strcasecmp _stricmp
#endif
#endif
#define BYTES_BIG_ENDIAN 0
/*
* From defaults.h
*/
#ifndef GET_ENVIRONMENT
#define GET_ENVIRONMENT(VALUE, NAME) do { (VALUE) = getenv (NAME); } while (0)
#endif
/* Define results of standard character escape sequences. */
#define TARGET_BELL 007
#define TARGET_BS 010
#define TARGET_TAB 011
#define TARGET_NEWLINE 012
#define TARGET_VT 013
#define TARGET_FF 014
#define TARGET_CR 015
#define TARGET_ESC 033
#define CHAR_TYPE_SIZE 8
#define WCHAR_TYPE_SIZE 32 /* ? maybe ? */
#define SUPPORTS_ONE_ONLY 0
#define <API key> ".rel"
#ifndef WCHAR_UNSIGNED
#define WCHAR_UNSIGNED 0
#endif
/*
* From langhooks.h
*/
struct diagnostic_context;
struct lang_hooks
{
/* The first callback made to the front end, for simple
initialization needed before any calls to handle_option. Return
the language mask to filter the switch array with. */
unsigned int (*init_options) (unsigned int argc, const char **argv);
/* Handle the switch CODE, which has real type enum opt_code from
options.h. If the switch takes an argument, it is passed in ARG
which points to permanent storage. The handler is responsible for
checking whether ARG is NULL, which indicates that no argument
was in fact supplied. For -f and -W switches, VALUE is 1 or 0
for the positive and negative forms respectively.
Return 1 if the switch is valid, 0 if invalid, and -1 if it's
valid and should not be treated as <API key> too. */
int (*handle_option) (size_t code, const char *arg, int value);
/* Return false to use the default complaint about a missing
argument, otherwise output a complaint and return true. */
bool (*missing_argument) (const char *opt, size_t code);
/* Called when all command line options have been parsed to allow
further processing and initialization
Should return true to indicate that a compiler back-end is
not required, such as with the -E option.
If errorcount is nonzero after this call the compiler exits
immediately and the finish hook is not called. */
bool (*post_options) (const char **);
/* Called after post_options to initialize the front end. Return
false to indicate that no further compilation be performed, in
which case the finish hook is called immediately. */
bool (*init) (void);
/* Called at the end of compilation, as a finalizer. */
void (*finish) (void);
};
/* Each front end provides its own. */
extern const struct lang_hooks lang_hooks;
/*
* From toplev.h
*/
/* If we haven't already defined a frontend specific diagnostics
style, use the generic one. */
#ifndef GCC_DIAG_STYLE
#define GCC_DIAG_STYLE __gcc_tdiag__
#endif
extern void internal_error (const char *, ...) ATTRIBUTE_PRINTF_1
ATTRIBUTE_NORETURN;
/* Pass one of the OPT_W* from options.h as the first parameter. */
extern void warning (int, const char *, ...) ATTRIBUTE_PRINTF_2;
extern void error (const char *, ...) ATTRIBUTE_PRINTF_1;
extern void fatal_error (const char *, ...) ATTRIBUTE_PRINTF_1
ATTRIBUTE_NORETURN;
extern void inform (const char *, ...) ATTRIBUTE_PRINTF_1;
extern const char *progname;
extern bool exit_after_options;
extern void print_version (FILE *, const char *);
/* Handle -d switch. */
extern void decode_d_option (const char *);
/* Functions used to get and set GCC's notion of in what directory
compilation was started. */
extern const char *get_src_pwd (void);
extern bool set_src_pwd (const char *);
/*
* From flags.h
*/
/* Don't suppress warnings from system headers. -Wsystem-headers. */
extern bool warn_system_headers;
/* If -Werror. */
extern bool warnings_are_errors;
/* Nonzero for -pedantic switch: warn about anything
that standard C forbids. */
/* Temporarily suppress certain warnings.
This is set while reading code from a system header file. */
extern int in_system_header;
/* Nonzero means `char' should be signed. */
extern int flag_signed_char;
/* Nonzero means change certain warnings into errors.
Usually these are warnings about failure to conform to some standard. */
extern int <API key>;
/*
* From options.h
*/
extern int inhibit_warnings;
/*
* From c-common.h
*/
#include "hwint.h"
#include "cpplib.h"
/* Nonzero means don't output line number information. */
extern char <API key>;
/* Nonzero causes -E output not to be done, but directives such as
#define that have side effects are still obeyed. */
extern char flag_no_output;
/* Nonzero means dump macros in some fashion; contains the 'D', 'M' or
'N' of the command line switch. */
extern char flag_dump_macros;
/* 0 means we want the preprocessor to not emit line directives for
the current working directory. 1 means we want it to do it. -1
means we should decide depending on whether debugging information
is being emitted or not. */
extern int <API key>;
/* Nonzero means warn about usage of long long when `-pedantic'. */
extern int warn_long_long;
extern int <API key> (size_t code, const char *arg, int value);
extern bool <API key> (const char *opt, size_t code);
extern unsigned int <API key> (unsigned int, const char **);
extern bool <API key> (const char **);
extern bool sdcpp_common_init (void);
extern void sdcpp_common_finish (void);
/* Nonzero means pass #include lines through to the output. */
extern char flag_dump_includes;
/* In c-ppoutput.c */
extern void init_pp_output (FILE *);
extern void preprocess_file (cpp_reader *);
extern void pp_file_change (const struct line_map *);
extern void pp_dir_change (cpp_reader *, const char *);
/*
* From c-pragma.h
*/
extern struct cpp_reader* parse_in;
/*
* From input.h
*/
extern struct line_maps *line_table;
typedef source_location location_t; /* deprecated typedef */
/* Top-level source file. */
extern const char *main_input_filename;
/*
* From tree.h
*/
/* Define the overall contents of a tree node.
just to make diagnostic.c happy */
union tree_node
{
struct tree_decl
{
location_t locus;
} decl;
};
#define <API key>(NODE) ((NODE)->decl.locus)
/*
* From diagnostic.h
*/
extern int errorcount;
/*
* From c-tree.h
*/
/* In order for the format checking to accept the C frontend
diagnostic framework extensions, you must include this file before
toplev.h, not after. */
#if GCC_VERSION >= 4001
#define ATTRIBUTE_GCC_CDIAG(m, n) __attribute__ ((__format__ (GCC_DIAG_STYLE, m ,n))) ATTRIBUTE_NONNULL(m)
#else
#define ATTRIBUTE_GCC_CDIAG(m, n) ATTRIBUTE_NONNULL(m)
#endif
extern bool c_cpp_error (cpp_reader *, int, int, location_t, unsigned int,
const char *, va_list *)
ATTRIBUTE_GCC_CDIAG(6,0);
#endif /* __SDCPP_H */
|
#ifndef <API key>
#define <API key>
#include "LETypes.h"
#include "LEGlyphFilter.h"
#include "LEFontInstance.h"
#include "LayoutEngine.h"
#include "LETableReference.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
U_NAMESPACE_BEGIN
/**
* <API key> implements complex text layout for OpenType fonts - that is
* fonts which have GSUB and GPOS tables associated with them. In order to do this,
* the glyph processsing step described for LayoutEngine is further broken into three
* steps:
*
* 1) Character processing - this step analyses the characters and assigns a list of OpenType
* feature tags to each one. It may also change, remove or add characters, and change
* their order.
*
* 2) Glyph processing - This step performs character to glyph mapping,and uses the GSUB
* table associated with the font to perform glyph substitutions, such as ligature substitution.
*
* 3) Glyph post processing - in cases where the font doesn't directly contain a GSUB table,
* the previous two steps may have generated "fake" glyph indices to use with a "canned" GSUB
* table. This step turns those glyph indices into actual font-specific glyph indices, and may
* perform any other adjustments requried by the previous steps.
*
* <API key> will also use the font's GPOS table to apply position adjustments
* such as kerning and accent positioning.
*
* @see LayoutEngine
*
* @internal
*/
class U_LAYOUT_API <API key> : public LayoutEngine
{
public:
/**
* This is the main constructor. It constructs an instance of <API key> for
* a particular font, script and language. It takes the GSUB table as a parameter since
* LayoutEngine::layoutEngineFactory has to read the GSUB table to know that it has an
* OpenType font.
*
* @param fontInstance - the font
* @param scriptCode - the script
* @param langaugeCode - the language
* @param gsubTable - the GSUB table
* @param success - set to an error code if the operation fails
*
* @see LayoutEngine::layoutEngineFactory
* @see <API key>.h for script and language codes
*
* @internal
*/
<API key>(const LEFontInstance *fontInstance, le_int32 scriptCode, le_int32 languageCode,
le_int32 typoFlags, const LEReferenceTo<<API key>> &gsubTable, LEErrorCode &success);
/**
* This constructor is used when the font requires a "canned" GSUB table which can't be known
* until after this constructor has been invoked.
*
* @param fontInstance - the font
* @param scriptCode - the script
* @param langaugeCode - the language
* @param success - set to an error code if the operation fails
*
* @internal
*/
<API key>(const LEFontInstance *fontInstance, le_int32 scriptCode, le_int32 languageCode,
le_int32 typoFlags, LEErrorCode &success);
/**
* The destructor, virtual for correct polymorphic invocation.
*
* @internal
*/
virtual ~<API key>();
/**
* A convenience method used to convert the script code into
* the four byte script tag required by OpenType.
* For Indic languages where multiple script tags exist,
* the version 1 (old style) tag is returned.
*
* @param scriptCode - the script code
*
* @return the four byte script tag
*
* @internal
*/
static LETag getScriptTag(le_int32 scriptCode);
/**
* A convenience method used to convert the script code into
* the four byte script tag required by OpenType.
* For Indic languages where multiple script tags exist,
* the version 2 tag is returned.
*
* @param scriptCode - the script code
*
* @return the four byte script tag
*
* @internal
*/
static LETag getV2ScriptTag(le_int32 scriptCode);
/**
* A convenience method used to convert the langauge code into
* the four byte langauge tag required by OpenType.
*
* @param languageCode - the language code
*
* @return the four byte language tag
*
* @internal
*/
static LETag getLangSysTag(le_int32 languageCode);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.8
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.8
*/
static UClassID getStaticClassID();
/**
* The array of language tags, indexed by language code.
*
* @internal
*/
static const LETag languageTags[];
private:
/**
* This method is used by the constructors to convert the script
* and language codes to four byte tags and save them.
*/
void <API key>();
/**
* The array of script tags, indexed by script code.
*/
static const LETag scriptTags[];
/**
* apply the typoflags. Only called by the c'tors.
*/
void applyTypoFlags();
protected:
/**
* A set of "default" features. The default characterProcessing method
* will apply all of these features to every glyph.
*
* @internal
*/
FeatureMask fFeatureMask;
/**
* A set of mappings from feature tags to feature masks. These may
* be in the order in which the featues should be applied, but they
* don't need to be.
*
* @internal
*/
const FeatureMap *fFeatureMap;
/**
* The length of the feature map.
*
* @internal
*/
le_int32 fFeatureMapCount;
/**
* <code>TRUE</code> if the features in the
* feature map are in the order in which they
* must be applied.
*
* @internal
*/
le_bool fFeatureOrder;
/**
* The address of the GSUB table.
*
* @internal
*/
LEReferenceTo<<API key>> fGSUBTable;
/**
* The address of the GDEF table.
*
* @internal
*/
LEReferenceTo<<API key>> fGDEFTable;
/**
* The address of the GPOS table.
*
* @internal
*/
LEReferenceTo<<API key>> fGPOSTable;
/**
* An optional filter used to inhibit substitutions
* preformed by the GSUB table. This is used for some
* "canned" GSUB tables to restrict substitutions to
* glyphs that are in the font.
*
* @internal
*/
LEGlyphFilter *fSubstitutionFilter;
/**
* The four byte script tag.
*
* @internal
*/
LETag fScriptTag;
/**
* The four byte script tag for V2 fonts.
*
* @internal
*/
LETag fScriptTagV2;
/**
* The four byte language tag
*
* @internal
*/
LETag fLangSysTag;
/**
* This method does the OpenType character processing. It assigns the OpenType feature
* tags to the characters, and may generate output characters that differ from the input
* charcters due to insertions, deletions, or reorderings. In such cases, it will also
* generate an output character index array reflecting these changes.
*
* Subclasses must override this method.
*
* Input parameters:
* @param chars - the input character context
* @param offset - the index of the first character to process
* @param count - the number of characters to process
* @param max - the number of characters in the input context
* @param rightToLeft - TRUE if the characters are in a right to left directional run
*
* Output parameters:
* @param outChars - the output character array, if different from the input
* @param charIndices - the output character index array
* @param featureTags - the output feature tag array
* @param success - set to an error code if the operation fails
*
* @return the output character count (input character count if no change)
*
* @internal
*/
virtual le_int32 characterProcessing(const LEUnicode /*chars*/[], le_int32 offset, le_int32 count, le_int32 max, le_bool /*rightToLeft*/,
LEUnicode *&/*outChars*/, LEGlyphStorage &glyphStorage, LEErrorCode &success);
/**
* This method does character to glyph mapping, and applies the GSUB table. The
* default implementation calls mapCharsToGlyphs and then applies the GSUB table,
* if there is one.
*
* Note that in the case of "canned" GSUB tables, the output glyph indices may be
* "fake" glyph indices that need to be converted to "real" glyph indices by the
* glyphPostProcessing method.
*
* Input parameters:
* @param chars - the input character context
* @param offset - the index of the first character to process
* @param count - the number of characters to process
* @param max - the number of characters in the input context
* @param rightToLeft - TRUE if the characters are in a right to left directional run
* @param featureTags - the feature tag array
*
* Output parameters:
* @param glyphs - the output glyph index array
* @param charIndices - the output character index array
* @param success - set to an error code if the operation fails
*
* @return the number of glyphs in the output glyph index array
*
* Note: if the character index array was already set by the characterProcessing
* method, this method won't change it.
*
* @internal
*/
virtual le_int32 glyphProcessing(const LEUnicode chars[], le_int32 offset, le_int32 count, le_int32 max, le_bool rightToLeft,
LEGlyphStorage &glyphStorage, LEErrorCode &success);
virtual le_int32 glyphSubstitution(le_int32 count, le_int32 max, le_bool rightToLeft, LEGlyphStorage &glyphStorage, LEErrorCode &success);
/**
* This method does any processing necessary to convert "fake"
* glyph indices used by the glyphProcessing method into "real" glyph
* indices which can be used to render the text. Note that in some
* cases, such as CDAC Indic fonts, several "real" glyphs may be needed
* to render one "fake" glyph.
*
* The default implementation of this method just returns the input glyph
* index and character index arrays, assuming that no "fake" glyph indices
* were needed to do GSUB processing.
*
* Input paramters:
* @param tempGlyphs - the input "fake" glyph index array
* @param tempCharIndices - the input "fake" character index array
* @param tempGlyphCount - the number of "fake" glyph indices
*
* Output parameters:
* @param glyphs - the output glyph index array
* @param charIndices - the output character index array
* @param success - set to an error code if the operation fails
*
* @return the number of glyph indices in the output glyph index array
*
* @internal
*/
virtual le_int32 glyphPostProcessing(LEGlyphStorage &tempGlyphStorage, LEGlyphStorage &glyphStorage, LEErrorCode &success);
/**
* This method applies the characterProcessing, glyphProcessing and glyphPostProcessing
* methods. Most subclasses will not need to override this method.
*
* Input parameters:
* @param chars - the input character context
* @param offset - the index of the first character to process
* @param count - the number of characters to process
* @param max - the number of characters in the input context
* @param rightToLeft - TRUE if the text is in a right to left directional run
*
* Output parameters:
* @param glyphs - the glyph index array
* @param charIndices - the character index array
* @param success - set to an error code if the operation fails
*
* @return the number of glyphs in the glyph index array
*
* @see LayoutEngine::computeGlyphs
*
* @internal
*/
virtual le_int32 computeGlyphs(const LEUnicode chars[], le_int32 offset, le_int32 count, le_int32 max, le_bool rightToLeft, LEGlyphStorage &glyphStorage, LEErrorCode &success);
/**
* This method uses the GPOS table, if there is one, to adjust the glyph positions.
*
* Input parameters:
* @param glyphs - the input glyph array
* @param glyphCount - the number of glyphs in the glyph array
* @param x - the starting X position
* @param y - the starting Y position
*
* Output parameters:
* @param positions - the output X and Y positions (two entries per glyph)
* @param success - set to an error code if the operation fails
*
* @internal
*/
virtual void <API key>(const LEUnicode chars[], le_int32 offset, le_int32 count, le_bool reverse, LEGlyphStorage &glyphStorage, LEErrorCode &success);
/**
* This method frees the feature tag array so that the
* <API key> can be reused for different text.
* It is also called from our destructor.
*
* @internal
*/
virtual void reset();
};
U_NAMESPACE_END
#endif
|
// methods (functions of objects)
// http://www.ecma-international.org/ecma-262/6.0/#<API key>
var Obj = {
myMethod(a, b) {
},
*myGenerator(a, b) {
}
}
|
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/iopoll.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include "mdss_fb.h"
#include "mdss_mdp.h"
#include "mdss_timeout.h"
/* wait for at least 2 vsyncs for lowest refresh rate (24hz) */
#define VSYNC_TIMEOUT_US 100000
#define <API key>(intf_num) \
(1 << (2 * (intf_num - MDSS_MDP_INTF0) + <API key>))
/* intf timing settings */
struct intf_timing_params {
u32 width;
u32 height;
u32 xres;
u32 yres;
u32 h_back_porch;
u32 h_front_porch;
u32 v_back_porch;
u32 v_front_porch;
u32 hsync_pulse_width;
u32 vsync_pulse_width;
u32 border_clr;
u32 underflow_clr;
u32 hsync_skew;
};
struct mdss_mdp_video_ctx {
u32 intf_num;
char __iomem *base;
u32 intf_type;
u8 ref_cnt;
u8 timegen_en;
bool polling_en;
u32 poll_cnt;
struct completion vsync_comp;
int wait_pending;
atomic_t vsync_ref;
spinlock_t vsync_lock;
struct list_head vsync_handlers;
};
static inline void mdp_video_write(struct mdss_mdp_video_ctx *ctx,
u32 reg, u32 val)
{
writel_relaxed(val, ctx->base + reg);
}
static inline u32 mdp_video_read(struct mdss_mdp_video_ctx *ctx,
u32 reg)
{
return readl_relaxed(ctx->base + reg);
}
static inline u32 <API key>(struct mdss_mdp_ctl *ctl)
{
struct mdss_mdp_video_ctx *ctx = ctl->priv_data;
u32 line_cnt = 0;
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false);
line_cnt = mdp_video_read(ctx, <API key>);
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false);
return line_cnt;
}
int <API key>(struct mdss_data_type *mdata,
u32 *offsets, u32 count)
{
struct mdss_mdp_video_ctx *head;
u32 i;
head = devm_kzalloc(&mdata->pdev->dev,
sizeof(struct mdss_mdp_video_ctx) * count, GFP_KERNEL);
if (!head)
return -ENOMEM;
for (i = 0; i < count; i++) {
head[i].base = mdata->mdp_base + offsets[i];
pr_debug("adding Video Intf #%d offset=0x%x virt=%p\n", i,
offsets[i], head[i].base);
head[i].ref_cnt = 0;
head[i].intf_num = i + MDSS_MDP_INTF0;
INIT_LIST_HEAD(&head[i].vsync_handlers);
}
mdata->video_intf = head;
mdata->nintf = count;
return 0;
}
static int <API key>(struct mdss_mdp_video_ctx *ctx,
struct intf_timing_params *p)
{
u32 hsync_period, vsync_period;
u32 hsync_start_x, hsync_end_x, display_v_start, display_v_end;
u32 active_h_start, active_h_end, active_v_start, active_v_end;
u32 den_polarity, hsync_polarity, vsync_polarity;
u32 display_hctl, active_hctl, hsync_ctl, polarity_ctl;
hsync_period = p->hsync_pulse_width + p->h_back_porch +
p->width + p->h_front_porch;
vsync_period = p->vsync_pulse_width + p->v_back_porch +
p->height + p->v_front_porch;
display_v_start = ((p->vsync_pulse_width + p->v_back_porch) *
hsync_period) + p->hsync_skew;
display_v_end = ((vsync_period - p->v_front_porch) * hsync_period) +
p->hsync_skew - 1;
if (ctx->intf_type == MDSS_INTF_EDP) {
display_v_start += p->hsync_pulse_width + p->h_back_porch;
display_v_end -= p->h_front_porch;
}
hsync_start_x = p->h_back_porch + p->hsync_pulse_width;
hsync_end_x = hsync_period - p->h_front_porch - 1;
if (p->width != p->xres) {
active_h_start = hsync_start_x;
active_h_end = active_h_start + p->xres - 1;
} else {
active_h_start = 0;
active_h_end = 0;
}
if (p->height != p->yres) {
active_v_start = display_v_start;
active_v_end = active_v_start + (p->yres * hsync_period) - 1;
} else {
active_v_start = 0;
active_v_end = 0;
}
if (active_h_end) {
active_hctl = (active_h_end << 16) | active_h_start;
active_hctl |= BIT(31); /* ACTIVE_H_ENABLE */
} else {
active_hctl = 0;
}
if (active_v_end)
active_v_start |= BIT(31); /* ACTIVE_V_ENABLE */
hsync_ctl = (hsync_period << 16) | p->hsync_pulse_width;
display_hctl = (hsync_end_x << 16) | hsync_start_x;
den_polarity = 0;
if (MDSS_INTF_HDMI == ctx->intf_type) {
hsync_polarity = p->yres >= 720 ? 0 : 1;
vsync_polarity = p->yres >= 720 ? 0 : 1;
} else {
hsync_polarity = 0;
vsync_polarity = 0;
}
polarity_ctl = (den_polarity << 2) | /* DEN Polarity */
(vsync_polarity << 1) | /* VSYNC Polarity */
(hsync_polarity << 0); /* HSYNC Polarity */
mdp_video_write(ctx, <API key>, hsync_ctl);
mdp_video_write(ctx, <API key>,
vsync_period * hsync_period);
mdp_video_write(ctx, <API key>,
p->vsync_pulse_width * hsync_period);
mdp_video_write(ctx, <API key>, display_hctl);
mdp_video_write(ctx, <API key>,
display_v_start);
mdp_video_write(ctx, <API key>, display_v_end);
mdp_video_write(ctx, <API key>, active_hctl);
mdp_video_write(ctx, <API key>,
active_v_start);
mdp_video_write(ctx, <API key>, active_v_end);
mdp_video_write(ctx, <API key>, p->border_clr);
mdp_video_write(ctx, <API key>,
p->underflow_clr);
mdp_video_write(ctx, <API key>, p->hsync_skew);
mdp_video_write(ctx, <API key>, polarity_ctl);
mdp_video_write(ctx, <API key>, 0x3);
return 0;
}
static inline void <API key>(struct mdss_mdp_ctl *ctl, bool clear)
{
struct mdss_mdp_video_ctx *ctx = ctl->priv_data;
if (atomic_inc_return(&ctx->vsync_ref) == 1)
mdss_mdp_irq_enable(<API key>, ctl->intf_num);
else if (clear)
mdss_mdp_irq_clear(ctl->mdata, <API key>,
ctl->intf_num);
}
static inline void <API key>(struct mdss_mdp_ctl *ctl)
{
struct mdss_mdp_video_ctx *ctx = ctl->priv_data;
if (atomic_dec_return(&ctx->vsync_ref) == 0)
<API key>(<API key>, ctl->intf_num);
}
static int <API key>(struct mdss_mdp_ctl *ctl,
struct <API key> *handle)
{
struct mdss_mdp_video_ctx *ctx;
unsigned long flags;
int ret = 0;
bool irq_en = false;
if (!handle || !(handle->vsync_handler)) {
ret = -EINVAL;
goto exit;
}
ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data;
if (!ctx) {
pr_err("invalid ctx for ctl=%d\n", ctl->num);
ret = -ENODEV;
goto exit;
}
spin_lock_irqsave(&ctx->vsync_lock, flags);
if (!handle->enabled) {
handle->enabled = true;
list_add(&handle->list, &ctx->vsync_handlers);
irq_en = true;
}
<API key>(&ctx->vsync_lock, flags);
if (irq_en)
<API key>(ctl, false);
exit:
return ret;
}
static int <API key>(struct mdss_mdp_ctl *ctl,
struct <API key> *handle)
{
struct mdss_mdp_video_ctx *ctx;
unsigned long flags;
bool irq_dis = false;
ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data;
if (!ctx) {
pr_err("invalid ctx for ctl=%d\n", ctl->num);
return -ENODEV;
}
spin_lock_irqsave(&ctx->vsync_lock, flags);
if (handle->enabled) {
handle->enabled = false;
list_del_init(&handle->list);
irq_dis = true;
}
<API key>(&ctx->vsync_lock, flags);
if (irq_dis)
<API key>(ctl);
return 0;
}
static int mdss_mdp_video_stop(struct mdss_mdp_ctl *ctl)
{
struct mdss_mdp_video_ctx *ctx;
struct <API key> *tmp, *handle;
int rc;
pr_debug("stop ctl=%d\n", ctl->num);
ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data;
if (!ctx) {
pr_err("invalid ctx for ctl=%d\n", ctl->num);
return -ENODEV;
}
if (ctx->timegen_en) {
rc = <API key>(ctl, MDSS_EVENT_BLANK, NULL);
if (rc == -EBUSY) {
pr_debug("intf #%d busy don't turn off\n",
ctl->intf_num);
return rc;
}
WARN(rc, "intf %d blank error (%d)\n", ctl->intf_num, rc);
mdp_video_write(ctx, <API key>, 0);
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false);
ctx->timegen_en = false;
rc = <API key>(ctl, <API key>, NULL);
WARN(rc, "intf %d timegen off error (%d)\n", ctl->intf_num, rc);
<API key>(<API key>,
ctl->intf_num);
}
<API key>(handle, tmp, &ctx->vsync_handlers, list)
<API key>(ctl, handle);
<API key>(<API key>, ctl->intf_num,
NULL, NULL);
<API key>(<API key>, ctl->intf_num,
NULL, NULL);
ctx->ref_cnt
ctl->priv_data = NULL;
return 0;
}
static void <API key>(void *arg)
{
struct mdss_mdp_ctl *ctl = arg;
struct mdss_mdp_video_ctx *ctx = ctl->priv_data;
struct <API key> *tmp;
ktime_t vsync_time;
if (!ctx) {
pr_err("invalid ctx\n");
return;
}
vsync_time = ktime_get();
ctl->vsync_cnt++;
pr_debug("intr ctl=%d vsync cnt=%u vsync_time=%d\n",
ctl->num, ctl->vsync_cnt, (int)ktime_to_ms(vsync_time));
ctx->polling_en = false;
complete_all(&ctx->vsync_comp);
spin_lock(&ctx->vsync_lock);
list_for_each_entry(tmp, &ctx->vsync_handlers, list) {
tmp->vsync_handler(ctl, vsync_time);
}
spin_unlock(&ctx->vsync_lock);
}
static int <API key>(struct mdss_mdp_ctl *ctl)
{
struct mdss_mdp_video_ctx *ctx = ctl->priv_data;
u32 mask, status;
int rc;
mask = <API key>(ctl->intf_num);
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false);
rc = readl_poll_timeout(ctl->mdata->mdp_base + <API key>,
status,
(status & mask) || <API key>(&ctx->vsync_comp),
1000,
VSYNC_TIMEOUT_US);
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false);
if (rc == 0) {
pr_debug("vsync poll successful! rc=%d status=0x%x\n",
rc, status);
ctx->poll_cnt++;
if (status) {
struct <API key> *tmp;
unsigned long flags;
ktime_t vsync_time = ktime_get();
spin_lock_irqsave(&ctx->vsync_lock, flags);
list_for_each_entry(tmp, &ctx->vsync_handlers, list)
tmp->vsync_handler(ctl, vsync_time);
<API key>(&ctx->vsync_lock, flags);
}
} else {
pr_warn("vsync poll timed out! rc=%d status=0x%x mask=0x%x\n",
rc, status, mask);
}
return rc;
}
static int <API key>(struct mdss_mdp_ctl *ctl, void *arg)
{
struct mdss_mdp_video_ctx *ctx;
int rc;
static int timeout_occurred;
u32 prev_vsync_cnt;
ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data;
if (!ctx) {
pr_err("invalid ctx\n");
return -ENODEV;
}
WARN(!ctx->wait_pending, "waiting without commit! ctl=%d", ctl->num);
if (ctx->polling_en) {
rc = <API key>(ctl);
} else {
prev_vsync_cnt = ctl->vsync_cnt;
rc = <API key>(&ctx->vsync_comp,
usecs_to_jiffies(VSYNC_TIMEOUT_US));
if (rc == 0) {
pr_err("%s: TIMEOUT (vsync_cnt: prev: %u cur: %u)\n",
__func__, prev_vsync_cnt, ctl->vsync_cnt);
timeout_occurred = 1;
mdss_timeout_dump(ctl->mfd, __func__);
pr_warn("vsync wait timeout %d, fallback to poll mode\n",
ctl->num);
ctx->polling_en++;
rc = <API key>(ctl);
} else {
if (timeout_occurred)
pr_info("%s: recovered from previous timeout\n",
__func__);
timeout_occurred = 0;
rc = 0;
}
}
if (ctx->wait_pending) {
ctx->wait_pending = 0;
<API key>(ctl);
}
return rc;
}
static void <API key>(void *arg)
{
struct mdss_mdp_ctl *ctl = arg;
if (unlikely(!ctl))
return;
ctl->underrun_cnt++;
pr_debug("display underrun detected for ctl=%d count=%d\n", ctl->num,
ctl->underrun_cnt);
}
static int <API key>(struct mdss_mdp_ctl *ctl, void *arg)
{
struct mdss_mdp_video_ctx *ctx;
int rc;
pr_debug("kickoff ctl=%d\n", ctl->num);
ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data;
if (!ctx) {
pr_err("invalid ctx\n");
return -ENODEV;
}
if (!ctx->wait_pending) {
ctx->wait_pending++;
<API key>(ctl, true);
INIT_COMPLETION(ctx->vsync_comp);
} else {
WARN(1, "commit without wait! ctl=%d", ctl->num);
}
if (!ctx->timegen_en) {
rc = <API key>(ctl, MDSS_EVENT_UNBLANK, NULL);
if (rc) {
pr_warn("intf #%d unblank error (%d)\n",
ctl->intf_num, rc);
<API key>(ctl);
ctx->wait_pending = 0;
return rc;
}
pr_debug("enabling timing gen for intf=%d\n", ctl->intf_num);
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false);
mdss_mdp_irq_enable(<API key>, ctl->intf_num);
mdp_video_write(ctx, <API key>, 1);
wmb();
rc = <API key>(&ctx->vsync_comp,
usecs_to_jiffies(VSYNC_TIMEOUT_US));
WARN(rc == 0, "timeout (%d) enabling timegen on ctl=%d\n",
rc, ctl->num);
ctx->timegen_en = true;
rc = <API key>(ctl, MDSS_EVENT_PANEL_ON, NULL);
WARN(rc, "intf %d panel on error (%d)\n", ctl->intf_num, rc);
}
return 0;
}
void <API key>(struct mdss_mdp_ctl *ctl)
{
<API key>(ctl, <API key>, NULL);
}
void <API key>(struct mdss_mdp_ctl *ctl)
{
<API key>(ctl, <API key>, NULL);
}
int <API key>(struct mdss_panel_data *pdata)
{
void *virt = NULL;
unsigned long bl_fb_addr = 0;
unsigned long *bl_fb_addr_va;
unsigned long pipe_addr, pipe_src_size;
u32 height, width, rgb_size, bpp;
size_t size;
static struct ion_handle *ihdl;
struct ion_client *iclient = mdss_get_ionclient();
static ion_phys_addr_t phys;
pipe_addr = <API key>(3) +
<API key>;
pipe_src_size =
<API key>(3) + <API key>;
bpp = 3;
rgb_size = MDSS_MDP_REG_READ(pipe_src_size);
bl_fb_addr = MDSS_MDP_REG_READ(pipe_addr);
height = (rgb_size >> 16) & 0xffff;
width = rgb_size & 0xffff;
size = PAGE_ALIGN(height * width * bpp);
pr_debug("%s:%d splash_height=%d splash_width=%d Buffer size=%d\n",
__func__, __LINE__, height, width, size);
ihdl = ion_alloc(iclient, size, SZ_1M,
ION_HEAP(ION_QSECOM_HEAP_ID), 0);
if (IS_ERR_OR_NULL(ihdl)) {
pr_err("unable to alloc fbmem from ion (%p)\n", ihdl);
return -ENOMEM;
}
pdata->panel_info.splash_ihdl = ihdl;
virt = ion_map_kernel(iclient, ihdl);
ion_phys(iclient, ihdl, &phys, &size);
pr_debug("%s %d Allocating %u bytes at 0x%lx (%pa phys)\n",
__func__, __LINE__, size,
(unsigned long int)virt, &phys);
bl_fb_addr_va = (unsigned long *)ioremap(bl_fb_addr, size);
memcpy(virt, bl_fb_addr_va, size);
iounmap(bl_fb_addr_va);
MDSS_MDP_REG_WRITE(pipe_addr, phys);
MDSS_MDP_REG_WRITE(<API key> + <API key>(0),
0x48);
return 0;
}
int <API key>(struct mdss_mdp_ctl *ctl)
{
struct ion_client *iclient = mdss_get_ionclient();
struct mdss_panel_data *pdata;
int ret = 0, off;
int mdss_mdp_rev = MDSS_MDP_REG_READ(<API key>);
int mdss_v2_intf_off = 0;
off = 0;
pdata = ctl->panel_data;
pdata->panel_info.cont_splash_enabled = 0;
ret = <API key>(ctl, <API key>,
NULL);
if (ret) {
pr_err("%s: Failed to handle 'CONT_SPLASH_BEGIN' event\n",
__func__);
return ret;
}
mdss_mdp_ctl_write(ctl, 0, <API key>);
off = <API key>(ctl->intf_num);
if (mdss_mdp_rev >= MDSS_MDP_HW_REV_102)
mdss_v2_intf_off = 0xEC00;
MDSS_MDP_REG_WRITE(off + <API key> -
mdss_v2_intf_off, 0);
/* wait for 1 VSYNC for the pipe to be unstaged */
msleep(20);
ion_free(iclient, pdata->panel_info.splash_ihdl);
ret = <API key>(ctl, <API key>,
NULL);
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false);
return ret;
}
void <API key>(struct mdss_mdp_ctl *ctl)
{
struct mdss_mdp_video_ctx *ctx = ctl->priv_data;
MDSS_TIMEOUT_LOG("timegen_en=%u\n", ctx->timegen_en);
MDSS_TIMEOUT_LOG("polling_en=%u\n", ctx->polling_en);
MDSS_TIMEOUT_LOG("poll_cnt=%u\n", ctx->poll_cnt);
MDSS_TIMEOUT_LOG("wait_pending=%d\n", ctx->wait_pending);
}
int <API key>(struct mdss_mdp_ctl *ctl)
{
struct mdss_data_type *mdata;
struct mdss_panel_info *pinfo;
struct mdss_mdp_video_ctx *ctx;
struct mdss_mdp_mixer *mixer;
struct intf_timing_params itp = {0};
u32 dst_bpp;
int i;
mdata = ctl->mdata;
pinfo = &ctl->panel_data->panel_info;
mixer = mdss_mdp_mixer_get(ctl, <API key>);
if (!mixer) {
pr_err("mixer not setup correctly\n");
return -ENODEV;
}
i = ctl->intf_num - MDSS_MDP_INTF0;
if (i < mdata->nintf) {
ctx = ((struct mdss_mdp_video_ctx *) mdata->video_intf) + i;
if (ctx->ref_cnt) {
pr_err("Intf %d already in use\n", ctl->intf_num);
return -EBUSY;
}
pr_debug("video Intf #%d base=%p", ctx->intf_num, ctx->base);
ctx->ref_cnt++;
} else {
pr_err("Invalid intf number: %d\n", ctl->intf_num);
return -EINVAL;
}
pr_debug("start ctl=%u\n", ctl->num);
ctl->priv_data = ctx;
ctx->intf_type = ctl->intf_type;
init_completion(&ctx->vsync_comp);
spin_lock_init(&ctx->vsync_lock);
atomic_set(&ctx->vsync_ref, 0);
<API key>(<API key>, ctl->intf_num,
<API key>, ctl);
<API key>(<API key>, ctl->intf_num,
<API key>, ctl);
dst_bpp = pinfo->fbc.enabled ? (pinfo->fbc.target_bpp) : (pinfo->bpp);
itp.width = mult_frac((pinfo->xres + pinfo->lcdc.xres_pad),
dst_bpp, pinfo->bpp);
itp.height = pinfo->yres + pinfo->lcdc.yres_pad;
itp.border_clr = pinfo->lcdc.border_clr;
itp.underflow_clr = pinfo->lcdc.underflow_clr;
itp.hsync_skew = pinfo->lcdc.hsync_skew;
itp.xres = mult_frac(pinfo->xres, dst_bpp, pinfo->bpp);
itp.yres = pinfo->yres;
itp.h_back_porch = mult_frac(pinfo->lcdc.h_back_porch, dst_bpp,
pinfo->bpp);
itp.h_front_porch = mult_frac(pinfo->lcdc.h_front_porch, dst_bpp,
pinfo->bpp);
itp.v_back_porch = mult_frac(pinfo->lcdc.v_back_porch, dst_bpp,
pinfo->bpp);
itp.v_front_porch = mult_frac(pinfo->lcdc.v_front_porch, dst_bpp,
pinfo->bpp);
itp.hsync_pulse_width = mult_frac(pinfo->lcdc.h_pulse_width, dst_bpp,
pinfo->bpp);
itp.vsync_pulse_width = pinfo->lcdc.v_pulse_width;
if (<API key>(ctx, &itp)) {
pr_err("unable to get timing parameters\n");
return -EINVAL;
}
mdp_video_write(ctx, <API key>, ctl->dst_format);
ctl->stop_fnc = mdss_mdp_video_stop;
ctl->display_fnc = <API key>;
ctl->wait_fnc = <API key>;
ctl->read_line_cnt_fnc = <API key>;
ctl->add_vsync_handler = <API key>;
ctl-><API key> = <API key>;
ctl->ctx_dump_fnc = <API key>;
return 0;
}
|
package org.openmicroscopy.shoola.keywords;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.util.<API key>;
import javax.swing.JPanel;
import org.robotframework.abbot.finder.BasicFinder;
import org.robotframework.abbot.finder.<API key>;
import org.robotframework.abbot.finder.Matcher;
import org.robotframework.abbot.finder.<API key>;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
/**
* Robot Framework SwingLibrary keyword library offering methods for checking thumbnails.
* @author m.t.b.carroll@dundee.ac.uk
* @since 4.4.9
*/
public class <API key>
{
/** Allow Robot Framework to instantiate this library only once. */
public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL";
/**
* An iterator over the integer pixel values of a rendered image,
* first increasing <em>x</em>, then <em>y</em> when <em>x</em> wraps back to 0.
* This is written so as to be scalable over arbitrary image sizes
* and to not cause heap allocations during the iteration.
* @author m.t.b.carroll@dundee.ac.uk
* @since 4.4.9
*/
private static class IteratorIntPixel {
final Raster raster;
final int width;
final int height;
final int[] pixel = new int[1];
int x = 0;
int y = 0;
/**
* Create a new pixel iterator for the given image.
* The image is assumed to be of a type that packs data for each pixel into an <code>int</code>.
* @param image the image over whose pixels to iterate
*/
IteratorIntPixel(RenderedImage image) {
this.raster = image.getData();
this.width = image.getWidth();
this.height = image.getHeight();
}
/**
* @return if any pixels remain to be read with {@link #next()}
*/
boolean hasNext() {
return y < height;
}
/**
* @return the next pixel
* @throws <API key> if no more pixels remain
*/
int next() {
if (!hasNext()) {
throw new <API key>();
}
raster.getDataElements(x, y, pixel);
if (++x == width) {
x = 0;
++y;
}
return pixel[0];
}
}
/**
* Find the thumbnail <code>Component</code> in the AWT hierarchy.
* @param panelType if the thumbnail should be the whole <code>"image node"</code> or just its <code>"thumbnail"</code> canvas
* @param imageFilename the name of the image whose thumbnail is to be rasterized
* @return the AWT <code>Component</code> for the thumbnail
* @throws <API key> if multiple thumbnails are for the given image name
* @throws <API key> if no thumbnails are for the given image name
*/
private static Component componentFinder(final String panelType, final String imageFilename)
throws <API key>, <API key> {
return new BasicFinder().find(new Matcher() {
private final String soughtName = panelType + " for " + imageFilename;
public boolean matches(Component component) {
return component instanceof JPanel && this.soughtName.equals(component.getName());
}});
}
/**
* Convert the thumbnail for the image of the given filename into rasterized pixel data.
* Each pixel is represented by an <code>int</code>.
* @param panelType if the thumbnail should be the whole <code>"image node"</code> or just its <code>"thumbnail"</code> canvas
* @param imageFilename the name of the image whose thumbnail is to be rasterized
* @return the image on the thumbnail
* @throws <API key> if multiple thumbnails are for the given image name
* @throws <API key> if no thumbnails are for the given image name
*/
private static RenderedImage captureImage(final String panelType, final String imageFilename)
throws <API key>, <API key> {
final JPanel thumbnail = (JPanel) componentFinder(panelType, imageFilename);
final int width = thumbnail.getWidth();
final int height = thumbnail.getHeight();
final BufferedImage image = new BufferedImage(width, height, StaticFieldLibrary.IMAGE_TYPE);
final Graphics2D graphics = image.createGraphics();
if (graphics == null) {
throw new RuntimeException("thumbnail is not displayable");
}
thumbnail.paint(graphics);
graphics.dispose();
return image;
}
/**
* <table>
* <td>Get Thumbnail Border Color</td>
* <td>name of image whose thumbnail is queried</td>
* </table>
* @param imageFilename the name of the image
* @return the color of the thumbnail's corner pixel
* @throws <API key> if multiple thumbnails exist for the given name
* @throws <API key> if no thumbnails exist for the given name
*/
public String <API key>(String imageFilename)
throws <API key>, <API key> {
final RenderedImage image = captureImage("image node", imageFilename);
final IteratorIntPixel pixels = new IteratorIntPixel(image);
if (!pixels.hasNext()) {
throw new RuntimeException("image node has no pixels");
}
return Integer.toHexString(pixels.next());
}
/**
* <table>
* <td>Is Thumbnail Monochromatic</td>
* <td>name of image whose thumbnail is queried</td>
* </table>
* @param imageFilename the name of the image
* @return if the image's thumbnail canvas is solidly one color
* @throws <API key> if multiple thumbnails exist for the given name
* @throws <API key> if no thumbnails exist for the given name
*/
public boolean <API key>(String imageFilename)
throws <API key>, <API key> {
final RenderedImage image = captureImage("thumbnail", imageFilename);
final IteratorIntPixel pixels = new IteratorIntPixel(image);
if (!pixels.hasNext()) {
throw new RuntimeException("thumbnail image has no pixels");
}
final int oneColor = pixels.next();
while (pixels.hasNext()) {
if (pixels.next() != oneColor) {
return false;
}
}
return true;
}
/**
* <table>
* <td>Get Thumbnail Hash</td>
* <td>name of image whose thumbnail is queried</td>
* </table>
* @param imageFilename the name of the image
* @return the hash of the thumbnail canvas image
* @throws <API key> if multiple thumbnails exist for the given name
* @throws <API key> if no thumbnails exist for the given name
*/
public String getThumbnailHash(String imageFilename)
throws <API key>, <API key> {
final RenderedImage image = captureImage("thumbnail", imageFilename);
final IteratorIntPixel pixels = new IteratorIntPixel(image);
final Hasher hasher = Hashing.goodFastHash(128).newHasher();
while (pixels.hasNext()) {
hasher.putInt(pixels.next());
}
return hasher.hash().toString();
}
/**
* <table>
* <td>Get Name Of Thumbnail For Image</td>
* <td>name of image whose thumbnail is queried</td>
* </table>
* @param imageFilename the name of the image
* @return the return value of the corresponding <code>ThumbnailCanvas.getName()</code>
* @throws <API key> if multiple thumbnails exist for the given name
* @throws <API key> if no thumbnails exist for the given name
*/
public String <API key>(final String imageFilename)
throws <API key>, <API key> {
return componentFinder("thumbnail", imageFilename).getName();
}
}
|
<?php
// Protection against direct access
defined('AKEEBAENGINE') or die();
/**
* Database interface class.
*
* Based on Joomla! Platform 11.2
*/
interface <API key>
{
/**
* Test to see if the connector is available.
*
* @return boolean True on success, false otherwise.
*/
public static function test();
/**
* Test to see if the connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 11.2
*/
public static function isSupported();
}
/**
* Database driver superclass. Used as the base of all Akeeba Engine database drivers.
* Strongly based on Joomla Platform's JDatabase class.
*/
abstract class AEAbstractDriver extends AEAbstractObject implements <API key>
{
/** @var string The name of the database. */
private $_database;
/** @var string The name of the database driver. */
public $name;
/** @var resource The db conenction resource */
protected $connection = '';
/** @var integer The number of SQL statements executed by the database driver. */
protected $count = 0;
/** @var resource The database connection cursor from the last query. */
protected $cursor;
/** @var boolean The database driver debugging state. */
protected $debug = false;
/** @var int Query's limit */
protected $limit = 0;
/** @var array The log of executed SQL statements by the database driver. */
protected $log = array();
/** @var string Quote for named objects */
protected $nameQuote = '';
/** @var string The null or zero representation of a timestamp for the database driver. */
protected $nullDate;
/** @var int Query's offset */
protected $offset = 0;
/** @var array Passed in upon instantiation and saved. */
protected $options;
/** @var mixed The SQL query string */
protected $sql = '';
/** @var string The prefix used in the database, if any */
protected $tablePrefix = '';
/** @var bool Support for UTF-8 */
protected $utf = true;
/** @var int The db server's error number */
protected $errorNum = 0;
/** @var string The db server's error string */
protected $errorMsg = '';
/** @var array JDatabaseDriver instances container. */
protected static $instances = array();
/** @var string The minimum supported database version. */
protected static $dbMinimum;
/** @var string Driver type, e.g. mysql, mssql, pgsql and so on */
protected $driverType = '';
/**
* Splits a string of multiple queries into an array of individual queries.
*
* @param string $query Input SQL string with which to split into individual queries.
*
* @return array The queries from the input string separated into an array.
*/
public static function splitSql($query)
{
$start = 0;
$open = false;
$char = '';
$end = strlen($query);
$queries = array();
for ($i = 0; $i < $end; $i++)
{
$current = substr($query, $i, 1);
if (($current == '"' || $current == '\''))
{
$n = 2;
while (substr($query, $i - $n + 1, 1) == '\\' && $n < $i)
{
$n++;
}
if ($n % 2 == 0)
{
if ($open)
{
if ($current == $char)
{
$open = false;
$char = '';
}
}
else
{
$open = true;
$char = $current;
}
}
}
if (($current == ';' && !$open) || $i == $end - 1)
{
$queries[] = substr($query, $start, ($i - $start + 1));
$start = $i + 1;
}
}
return $queries;
}
/**
* Magic method to provide method alias support for quote() and quoteName().
*
* @param string $method The called method.
* @param array $args The array of arguments passed to the method.
*
* @return string The aliased method's return value or null.
*/
public function __call($method, $args)
{
if (empty($args))
{
return;
}
switch ($method)
{
case 'q':
return $this->quote($args[0], isset($args[1]) ? $args[1] : true);
break;
case 'nq':
case 'qn':
return $this->quoteName($args[0]);
break;
}
}
/**
* Database object constructor
* @param array List of options used to configure the connection
*/
public function __construct( $options )
{
$prefix = array_key_exists('prefix', $options) ? $options['prefix'] : '';
$database = array_key_exists('database', $options) ? $options['database'] : '';
$connection = array_key_exists('connection', $options) ? $options['connection']: null;
$this->tablePrefix = $prefix;
$this->_database = $database;
$this->connection = $connection;
$this->errorNum = 0;
$this->count = 0;
$this->log = array();
$this->options = $options;
}
/**
* Database object destructor
* @return bool
*/
public function __destruct()
{
return $this->close();
}
/**
* By default, when the object is shutting down, the connection is closed
*/
public function _onSerialize()
{
$this->close();
}
public function __wakeup()
{
$this->open();
}
/**
* Alter database's character set, obtaining query string from protected member.
*
* @param string $dbName The database name that will be altered
*
* @return string The query that alter the database query string
*
* @throws RuntimeException
*/
public function alterDbCharacterSet($dbName)
{
if (is_null($dbName))
{
throw new RuntimeException('Database name must not be null.');
}
$this->setQuery($this-><API key>($dbName));
return $this->execute();
}
/**
* Opens a database connection. It MUST be overriden by children classes
* @return AEAbstractDriver
*/
public function open()
{
// Don't try to reconnect if we're already connected
if(is_resource($this->connection) && !is_null($this->connection)) return $this;
// Determine utf-8 support
$this->utf = $this->hasUTF();
// Set charactersets (needed for MySQL 4.1.2+)
if ($this->utf){
$this->setUTF();
}
// Select the current database
$this->select($this->_database);
return $this;
}
/**
* Closes the database connection
*/
abstract public function close();
/**
* Determines if the connection to the server is active.
*
* @return boolean True if connected to the database engine.
*/
abstract public function connected();
/**
* Create a new database using information from $options object, obtaining query string
* from protected member.
*
* @param stdClass $options Object used to pass user and database name to database driver.
* This object must have "db_name" and "db_user" set.
* @param boolean $utf True if the database supports the UTF-8 character set.
*
* @return string The query that creates database
*
* @throws RuntimeException
*/
public function createDatabase($options, $utf = true)
{
if (is_null($options))
{
throw new RuntimeException('$options object must not be null.');
}
elseif (empty($options->db_name))
{
throw new RuntimeException('$options object must have db_name set.');
}
elseif (empty($options->db_user))
{
throw new RuntimeException('$options object must have db_user set.');
}
$this->setQuery($this-><API key>($options, $utf));
return $this->execute();
}
/**
* Drops a table from the database.
*
* @param string $table The name of the database table to drop.
* @param boolean $ifExists Optionally specify that the table must exist before it is dropped.
*
* @return AEAbstractDriver Returns this object to support chaining.
*/
public abstract function dropTable($table, $ifExists = true);
/**
* Method to escape a string for usage in an SQL statement.
*
* @param string $text The string to be escaped.
* @param boolean $extra Optional parameter to provide extra escaping.
*
* @return string The escaped string.
*/
abstract public function escape($text, $extra = false);
/**
* Method to fetch a row from the result set cursor as an array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*/
abstract protected function fetchArray($cursor = null);
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*/
abstract public function fetchAssoc($cursor = null);
/**
* Method to fetch a row from the result set cursor as an object.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
* @param string $class The class name to use for the returned row object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*/
abstract protected function fetchObject($cursor = null, $class = 'stdClass');
/**
* Method to free up the memory used for the result set.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return void
*/
abstract public function freeResult($cursor = null);
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* @return integer The number of affected rows.
*/
abstract public function getAffectedRows();
/**
* Return the query string to alter the database character set.
*
* @param string $dbName The database name
*
* @return string The query that alter the database query string
*/
protected function <API key>($dbName)
{
$query = 'ALTER DATABASE ' . $this->quoteName($dbName) . ' CHARACTER SET `utf8`';
return $query;
}
/**
* Return the query string to create new Database.
* Each database driver, other than MySQL, need to override this member to return correct string.
*
* @param stdClass $options Object used to pass user and database name to database driver.
* This object must have "db_name" and "db_user" set.
* @param boolean $utf True if the database supports the UTF-8 character set.
*
* @return string The query that creates database
*/
protected function <API key>($options, $utf)
{
if ($utf)
{
$query = 'CREATE DATABASE ' . $this->quoteName($options->db_name) . ' CHARACTER SET `utf8`';
}
else
{
$query = 'CREATE DATABASE ' . $this->quoteName($options->db_name);
}
return $query;
}
/**
* Method to get the database collation in use by sampling a text field of a table in the database.
*
* @return mixed The collation in use by the database or boolean false if not supported.
*/
abstract public function getCollation();
public function getConnection()
{
return $this->connection;
}
/**
* Inherits the connection of another database driver. Useful for cloning
* the CMS database connection into an Akeeba Engine database driver.
*
* @param resource $connection
*/
public function setConnection($connection)
{
$this->connection = $connection;
}
/**
* Get the total number of SQL statements executed by the database driver.
*
* @return integer
*
* @since 11.1
*/
public function getCount()
{
return $this->count;
}
/**
* Gets the name of the database used by this conneciton.
*
* @return string
*/
protected function getDatabase()
{
return $this->_database;
}
/**
* Returns a PHP date() function compliant date format for the database driver.
*
* @return string The format string.
*/
public function getDateFormat()
{
return 'Y-m-d H:i:s';
}
/**
* Get the database driver SQL statement log.
*
* @return array SQL statements executed by the database driver.
*
* @since 11.1
*/
public function getLog()
{
return $this->log;
}
/**
* Get the minimum supported database version.
*
* @return string The minimum version number for the database driver.
*
* @since 12.1
*/
public function getMinimum()
{
return static::$dbMinimum;
}
/**
* Get the null or zero representation of a timestamp for the database driver.
*
* @return string Null or zero representation of a timestamp.
*/
public function getNullDate()
{
return $this->nullDate;
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* @param resource $cursor An optional database cursor resource to extract the row count from.
*
* @return integer The number of returned rows.
*/
abstract public function getNumRows($cursor = null);
/**
* Get the database table prefix
*
* @return string The database prefix
*/
public final function getPrefix()
{
return $this->tablePrefix;
}
/**
* Get the current query object or a new AEAbstractQuery object.
*
* @param boolean $new False to return the current query object, True to return a new AEAbstractQuery object.
*
* @return AEAbstractQuery The current query object or a new object extending the AEAbstractQuery class.
*/
abstract public function getQuery($new = false);
/**
* Retrieves field information about the given tables.
*
* @param string $table The name of the database table.
* @param boolean $typeOnly True (default) to only return field types.
*
* @return array An array of fields by table.
*/
abstract public function getTableColumns($table, $typeOnly = true);
/**
* Shows the table CREATE statement that creates the given tables.
*
* @param mixed $tables A table name or a list of table names.
*
* @return array A list of the create SQL for the tables.
*/
abstract public function getTableCreate($tables);
/**
* Retrieves field information about the given tables.
*
* @param mixed $tables A table name or a list of table names.
*
* @return array An array of keys for the table(s).
*/
abstract public function getTableKeys($tables);
/**
* Method to get an array of all tables in the database.
*
* @return array An array of all the tables in the database.
*/
abstract public function getTableList();
/**
* Determine whether or not the database engine supports UTF-8 character encoding.
*
* @return boolean True if the database engine supports UTF-8 character encoding.
*/
public function getUTFSupport()
{
return $this->utf;
}
/**
* Determine whether or not the database engine supports UTF-8 character encoding.
*
* @return boolean True if the database engine supports UTF-8 character encoding.
*/
public function hasUTFSupport()
{
return $this->utf;
}
/**
* Determines if the database engine supports UTF-8 character encoding.
*
* @return boolean True if supported.
*/
public function hasUTF()
{
return $this->utf;
}
/**
* Get the version of the database connector
*
* @return string The database connector version.
*/
abstract public function getVersion();
/**
* Method to get the auto-incremented value from the last INSERT statement.
*
* @return integer The value of the auto-increment field from the last inserted row.
*/
abstract public function insertid();
/**
* Inserts a row into a table based on an object's properties.
*
* @param string $table The name of the database table to insert into.
* @param object &$object A reference to an object whose public properties match the table fields.
* @param string $key The name of the primary key. If provided the object property is updated.
*
* @return boolean True on success.
*/
public function insertObject($table, &$object, $key = null)
{
$fields = array();
$values = array();
// Iterate over the object variables to build the query fields and values.
foreach (get_object_vars($object) as $k => $v)
{
// Only process non-null scalars.
if (is_array($v) or is_object($v) or $v === null)
{
continue;
}
// Ignore any internal fields.
if ($k[0] == '_')
{
continue;
}
// Prepare and sanitize the fields and values for the database query.
$fields[] = $this->quoteName($k);
$values[] = $this->quote($v);
}
// Create the base insert statement.
$query = $this->getQuery(true)
->insert($this->quoteName($table))
->columns($fields)
->values(implode(',', $values));
// Set the query and execute the insert.
$this->setQuery($query);
if (!$this->execute())
{
return false;
}
// Update the primary key if it exists.
$id = $this->insertid();
if ($key && $id && is_string($key))
{
$object->$key = $id;
}
return true;
}
/**
* Method to check whether the installed database version is supported by the database driver
*
* @return boolean True if the database version is supported
*
* @since 12.1
*/
public function isMinimumVersion()
{
return version_compare($this->getVersion(), static::$dbMinimum) >= 0;
}
/**
* Method to get the first row of the result set from the database query as an associative array
* of ['field_name' => 'row_value'].
*
* @return mixed The return value or null if the query failed.
*/
public function loadAssoc()
{
$ret = null;
// Execute the query and get the result set cursor.
if (!($cursor = $this->execute()))
{
return null;
}
// Get the first row from the result set as an associative array.
if ($array = $this->fetchAssoc($cursor))
{
$ret = $array;
}
// Free up system resources and return.
$this->freeResult($cursor);
return $ret;
}
/**
* Method to get an array of the result set rows from the database query where each row is an associative array
* of ['field_name' => 'row_value']. The array of rows can optionally be keyed by a field name, but defaults to
* a sequential numeric array.
*
* NOTE: Chosing to key the result array by a non-unique field name can result in unwanted
* behavior and should be avoided.
*
* @param string $key The name of a field on which to key the result array.
* @param string $column An optional column name. Instead of the whole row, only this column value will be in
* the result array.
*
* @return mixed The return value or null if the query failed.
*/
public function loadAssocList($key = null, $column = null)
{
$array = array();
// Execute the query and get the result set cursor.
if (!($cursor = $this->execute()))
{
return null;
}
// Get all of the rows from the result set.
while ($row = $this->fetchAssoc($cursor))
{
$value = ($column) ? (isset($row[$column]) ? $row[$column] : $row) : $row;
if ($key)
{
$array[$row[$key]] = $value;
}
else
{
$array[] = $value;
}
}
// Free up system resources and return.
$this->freeResult($cursor);
return $array;
}
/**
* Method to get an array of values from the <var>$offset</var> field in each row of the result set from
* the database query.
*
* @param integer $offset The row offset to use to build the result array.
*
* @return mixed The return value or null if the query failed.
*/
public function loadColumn($offset = 0)
{
$array = array();
// Execute the query and get the result set cursor.
if (!($cursor = $this->execute()))
{
return null;
}
// Get all of the rows from the result set as arrays.
while ($row = $this->fetchArray($cursor))
{
$array[] = $row[$offset];
}
// Free up system resources and return.
$this->freeResult($cursor);
return $array;
}
/**
* Method to get the next row in the result set from the database query as an object.
*
* @param string $class The class name to use for the returned row object.
*
* @return mixed The result of the query as an array, false if there are no more rows.
*/
public function loadNextObject($class = 'stdClass')
{
static $cursor = null;
// Execute the query and get the result set cursor.
if ( is_null($cursor) )
{
if (!($cursor = $this->execute()))
{
return $this->errorNum ? null : false;
}
}
// Get the next row from the result set as an object of type $class.
if ($row = $this->fetchObject($cursor, $class))
{
return $row;
}
// Free up system resources and return.
$this->freeResult($cursor);
$cursor = null;
return false;
}
/**
* Method to get the next row in the result set from the database query as an array.
*
* @return mixed The result of the query as an array, false if there are no more rows.
*/
public function loadNextRow()
{
static $cursor = null;
// Execute the query and get the result set cursor.
if ( is_null($cursor) )
{
if (!($cursor = $this->execute()))
{
return $this->errorNum ? null : false;
}
}
// Get the next row from the result set as an object of type $class.
if ($row = $this->fetchArray($cursor))
{
return $row;
}
// Free up system resources and return.
$this->freeResult($cursor);
$cursor = null;
return false;
}
/**
* Method to get the first row of the result set from the database query as an object.
*
* @param string $class The class name to use for the returned row object.
*
* @return mixed The return value or null if the query failed.
*/
public function loadObject($class = 'stdClass')
{
$ret = null;
// Execute the query and get the result set cursor.
if (!($cursor = $this->execute()))
{
return null;
}
// Get the first row from the result set as an object of type $class.
if ($object = $this->fetchObject($cursor, $class))
{
$ret = $object;
}
// Free up system resources and return.
$this->freeResult($cursor);
return $ret;
}
/**
* Method to get an array of the result set rows from the database query where each row is an object. The array
* of objects can optionally be keyed by a field name, but defaults to a sequential numeric array.
*
* NOTE: Choosing to key the result array by a non-unique field name can result in unwanted
* behavior and should be avoided.
*
* @param string $key The name of a field on which to key the result array.
* @param string $class The class name to use for the returned row objects.
*
* @return mixed The return value or null if the query failed.
*/
public function loadObjectList($key = '', $class = 'stdClass')
{
$array = array();
// Execute the query and get the result set cursor.
if (!($cursor = $this->execute()))
{
return null;
}
// Get all of the rows from the result set as objects of type $class.
while ($row = $this->fetchObject($cursor, $class))
{
if ($key)
{
$array[$row->$key] = $row;
}
else
{
$array[] = $row;
}
}
// Free up system resources and return.
$this->freeResult($cursor);
return $array;
}
/**
* Method to get the first field of the first row of the result set from the database query.
*
* @return mixed The return value or null if the query failed.
*/
public function loadResult()
{
$ret = null;
// Execute the query and get the result set cursor.
if (!($cursor = $this->execute()))
{
return null;
}
// Get the first row from the result set as an array.
if ($row = $this->fetchArray($cursor))
{
$ret = $row[0];
}
// Free up system resources and return.
$this->freeResult($cursor);
return $ret;
}
/**
* Method to get the first row of the result set from the database query as an array. Columns are indexed
* numerically so the first column in the result set would be accessible via <var>$row[0]</var>, etc.
*
* @return mixed The return value or null if the query failed.
*/
public function loadRow()
{
$ret = null;
// Execute the query and get the result set cursor.
if (!($cursor = $this->execute()))
{
return null;
}
// Get the first row from the result set as an array.
if ($row = $this->fetchArray($cursor))
{
$ret = $row;
}
// Free up system resources and return.
$this->freeResult($cursor);
return $ret;
}
/**
* Method to get an array of the result set rows from the database query where each row is an array. The array
* of objects can optionally be keyed by a field offset, but defaults to a sequential numeric array.
*
* NOTE: Choosing to key the result array by a non-unique field can result in unwanted
* behavior and should be avoided.
*
* @param string $key The name of a field on which to key the result array.
*
* @return mixed The return value or null if the query failed.
*/
public function loadRowList($key = null)
{
$array = array();
// Execute the query and get the result set cursor.
if (!($cursor = $this->execute()))
{
return null;
}
// Get all of the rows from the result set as arrays.
while ($row = $this->fetchArray($cursor))
{
if ($key !== null)
{
$array[$row[$key]] = $row;
}
else
{
$array[] = $row;
}
}
// Free up system resources and return.
$this->freeResult($cursor);
return $array;
}
/**
* Locks a table in the database.
*
* @param string $tableName The name of the table to unlock.
*
* @return AEAbstractDriver Returns this object to support chaining.
*/
public abstract function lockTable($tableName);
/**
* Execute the SQL statement.
*
* @return mixed A database cursor resource on success, boolean false on failure.
*/
abstract public function query();
/**
* An alias for query(), for compatibility with Joomla! 2.5+ which has deprecated
* query() in favour of execute()
*
* @return mixed A database cursor resource on success, boolean false on failure.
*/
public function execute()
{
return $this->query();
}
/**
* Method to quote and optionally escape a string to database requirements for insertion into the database.
*
* @param string $text The string to quote.
* @param boolean $escape True (default) to escape the string, false to leave it unchanged.
*/
public function quote($text, $escape = true)
{
return '\'' . ($escape ? $this->escape($text) : $text) . '\'';
}
/**
* Wrap an SQL statement identifier name such as column, table or database names in quotes to prevent injection
* risks and reserved word conflicts.
*
* @param mixed $name The identifier name to wrap in quotes, or an array of identifier names to wrap in quotes.
* Each type supports dot-notation name.
* @param mixed $as The AS query part associated to $name. It can be string or array, in latter case it has to be
* same length of $name; if is null there will not be any AS part for string or array element.
*/
public function quoteName($name, $as = null)
{
if (is_string($name))
{
$quotedName = $this->quoteNameStr(explode('.', $name));
$quotedAs = '';
if (!is_null($as))
{
settype($as, 'array');
$quotedAs .= ' AS ' . $this->quoteNameStr($as);
}
return $quotedName . $quotedAs;
}
else
{
$fin = array();
if (is_null($as))
{
foreach ($name as $str)
{
$fin[] = $this->quoteName($str);
}
}
elseif (is_array($name) && (count($name) == count($as)))
{
$count = count($name);
for ($i = 0; $i < $count; $i++)
{
$fin[] = $this->quoteName($name[$i], $as[$i]);
}
}
return $fin;
}
}
/**
* Quote strings coming from quoteName call.
*
* @param array $strArr Array of strings coming from quoteName dot-explosion.
*
* @return string Dot-imploded string of quoted parts.
*/
protected function quoteNameStr($strArr)
{
$parts = array();
$q = $this->nameQuote;
foreach ($strArr as $part)
{
if (is_null($part))
{
continue;
}
if (strlen($q) == 1)
{
$parts[] = $q . $part . $q;
}
else
{
$parts[] = $q{0} . $part . $q{1};
}
}
return implode('.', $parts);
}
/**
* This function replaces a string identifier <var>$prefix</var> with the string held is the
* <var>tablePrefix</var> class variable.
*
* @param string $query The SQL statement to prepare.
* @param string $prefix The common table prefix.
*
* @return string The processed SQL statement.
*/
public function replacePrefix($query, $prefix = '
{
$escaped = false;
$startPos = 0;
$quoteChar = '';
$literal = '';
$query = trim($query);
$n = strlen($query);
while ($startPos < $n)
{
$ip = strpos($query, $prefix, $startPos);
if ($ip === false)
{
break;
}
$j = strpos($query, "'", $startPos);
$k = strpos($query, '"', $startPos);
if (($k !== false) && (($k < $j) || ($j === false)))
{
$quoteChar = '"';
$j = $k;
}
else
{
$quoteChar = "'";
}
if ($j === false)
{
$j = $n;
}
$literal .= str_replace($prefix, $this->tablePrefix, substr($query, $startPos, $j - $startPos));
$startPos = $j;
$j = $startPos + 1;
if ($j >= $n)
{
break;
}
// Quote comes first, find end of quote
while (true)
{
$k = strpos($query, $quoteChar, $j);
$escaped = false;
if ($k === false)
{
break;
}
$l = $k - 1;
while ($l >= 0 && $query{$l} == '\\')
{
$l
$escaped = !$escaped;
}
if ($escaped)
{
$j = $k + 1;
continue;
}
break;
}
if ($k === false)
{
// Error in the query - no end quote; ignore it
break;
}
$literal .= substr($query, $startPos, $k - $startPos + 1);
$startPos = $k + 1;
}
if ($startPos < $n)
{
$literal .= substr($query, $startPos, $n - $startPos);
}
return $literal;
}
/**
* Renames a table in the database.
*
* @param string $oldTable The name of the table to be renamed
* @param string $newTable The new name for the table.
* @param string $backup Table prefix
* @param string $prefix For the table - used to rename constraints in non-mysql databases
*
* @return AEAbstractDriver Returns this object to support chaining.
*/
public abstract function renameTable($oldTable, $newTable, $backup = null, $prefix = null);
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean True if the database was successfully selected.
*/
abstract public function select($database);
/**
* Sets the database debugging state for the driver.
*
* @param boolean $level True to enable debugging.
*
* @return boolean The old debugging level.
*/
public function setDebug($level)
{
$previous = $this->debug;
$this->debug = (bool) $level;
return $previous;
}
/**
* Sets the SQL statement string for later execution.
*
* @param mixed $query The SQL statement to set either as a AEAbstractQuery object or a string.
* @param integer $offset The affected row offset to set.
* @param integer $limit The maximum affected rows to set.
*
* @return AEAbstractDriver This object to support method chaining.
*/
public function setQuery($query, $offset = 0, $limit = 0)
{
$this->sql = $query;
$this->limit = (int) $limit;
$this->offset = (int) $offset;
return $this;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* @return boolean True on success.
*/
abstract public function setUTF();
/**
* Method to commit a transaction.
*
* @return void
*/
abstract public function transactionCommit();
/**
* Method to roll back a transaction.
*
* @return void
*/
abstract public function transactionRollback();
/**
* Method to initialize a transaction.
*
* @return void
*/
abstract public function transactionStart();
/**
* Method to truncate a table.
*
* @param string $table The table to truncate
*
* @return void
*/
public function truncateTable($table)
{
$this->setQuery('TRUNCATE TABLE ' . $this->quoteName($table));
$this->query();
}
/**
* Updates a row in a table based on an object's properties.
*
* @param string $table The name of the database table to update.
* @param object &$object A reference to an object whose public properties match the table fields.
* @param string $key The name of the primary key.
* @param boolean $nulls True to update null fields or false to ignore them.
*
* @return boolean True on success.
*/
public function updateObject($table, &$object, $key, $nulls = false)
{
$fields = array();
$where = array();
if (is_string($key))
{
$key = array($key);
}
if (is_object($key))
{
$key = (array) $key;
}
// Create the base update statement.
$statement = 'UPDATE ' . $this->quoteName($table) . ' SET %s WHERE %s';
// Iterate over the object variables to build the query fields/value pairs.
foreach (get_object_vars($object) as $k => $v)
{
// Only process scalars that are not internal fields.
if (is_array($v) or is_object($v) or $k[0] == '_')
{
continue;
}
// Set the primary key to the WHERE clause instead of a field to update.
if (in_array($k, $key))
{
$where[] = $this->quoteName($k) . '=' . $this->quote($v);
continue;
}
// Prepare and sanitize the fields and values for the database query.
if ($v === null)
{
// If the value is null and we want to update nulls then set it.
if ($nulls)
{
$val = 'NULL';
}
// If the value is null and we do not want to update nulls then ignore this field.
else
{
continue;
}
}
// The field is not null so we prep it for update.
else
{
$val = $this->quote($v);
}
// Add the field to be updated.
$fields[] = $this->quoteName($k) . '=' . $val;
}
// We don't have any fields to update.
if (empty($fields))
{
return true;
}
// Set the query and execute the update.
$this->setQuery(sprintf($statement, implode(",", $fields), implode(' AND ', $where)));
return $this->execute();
}
/**
* Unlocks tables in the database.
*
* @return AEAbstractDriver Returns this object to support chaining.
*/
public abstract function unlockTables();
/**
* Get the error message
* @return string The error message for the most recent query
*/
public final function getErrorMsg($escaped = false)
{
if($escaped) {
return addslashes($this->errorMsg);
} else {
return $this->errorMsg;
}
}
/**
* Get the error number
* @return int The error number for the most recent query
*/
public final function getErrorNum() {
return $this->errorNum;
}
/**
* Method to escape a string for usage in an SQL statement.
*
* @param string $text The string to be escaped.
* @param boolean $extra Optional parameter to provide extra escaping.
*
* @return string The escaped string.
*/
public function getEscaped($text, $extra = false)
{
return $this->escape($text, $extra);
}
/**
* Retrieves field information about the given tables.
*
* @param mixed $tables A table name or a list of table names.
* @param boolean $typeOnly True to only return field types.
*
* @return array An array of fields by table.
*/
public function getTableFields($tables, $typeOnly = true)
{
$results = array();
settype($tables, 'array');
foreach ($tables as $table)
{
$results[$table] = $this->getTableColumns($table, $typeOnly);
}
return $results;
}
/**
* Method to get an array of values from the <var>$offset</var> field in each row of the result set from
* the database query.
*
* @param integer $offset The row offset to use to build the result array.
*
* @return mixed The return value or null if the query failed.
*/
public function loadResultArray($offset = 0)
{
return $this->loadColumn($offset);
}
/**
* Wrap an SQL statement identifier name such as column, table or database names in quotes to prevent injection
* risks and reserved word conflicts.
*
* @param string $name The identifier name to wrap in quotes.
*
* @return string The quote wrapped name.
*/
public function nameQuote($name)
{
return $this->quoteName($name);
}
/**
* Returns the abstracted name of a database object
* @param string $tableName
* @return srting
*/
public function getAbstract( $tableName )
{
$prefix = $this->getPrefix();
// Don't return abstract names for non-CMS tables
if(is_null($prefix)) return $tableName;
switch( $prefix )
{
case '':
// This is more of a hack; it assumes all tables are CMS tables if the prefix is empty.
return '#__' . $tableName;
break;
default:
// Normal behaviour for 99% of sites
$tableAbstract = $tableName;
if(!empty($prefix)) {
if( substr($tableName, 0, strlen($prefix)) == $prefix ) {
$tableAbstract = '#__' . substr($tableName, strlen($prefix));
} else {
$tableAbstract = $tableName;
}
}
return $tableAbstract;
break;
}
}
public final function getDriverType()
{
return $this->driverType;
}
public static function test()
{
return self::isSupported();
}
}
|
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Proyecto
{
<summary>
Description of MenuConsulta.
</summary>
public partial class MenuConsulta : Form
{
public MenuConsulta()
{
// The InitializeComponent() call is required for Windows Forms designer support.
InitializeComponent();
// TODO: Add constructor code after the InitializeComponent() call.
}
void ButSalirClick(object sender, EventArgs e)
{
this.Close();
}
void ButActualizarClick(object sender, EventArgs e)
{
}
void <API key>(object sender, EventArgs e)
{
ConsultaCliente cliente = new ConsultaCliente();
cliente.Show();
}
}
}
|
/* GENERAL FIXME/TODO: check that the assumptions about what is written to
mac-io is valid for DACA & Tumbler.
This driver is in bad need of a rewrite. The dbdma code has to be split,
some proper device-tree parsing code has to be written, etc...
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/config.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/soundcard.h>
#include <linux/adb.h>
#include <linux/nvram.h>
#include <linux/tty.h>
#include <linux/vt_kern.h>
#include <linux/spinlock.h>
#include <linux/kmod.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <asm/semaphore.h>
#ifdef CONFIG_ADB_CUDA
#include <linux/cuda.h>
#endif
#ifdef CONFIG_ADB_PMU
#include <linux/pmu.h>
#endif
#include <linux/i2c-dev.h>
#include <asm/uaccess.h>
#include <asm/prom.h>
#include <asm/machdep.h>
#include <asm/io.h>
#include <asm/dbdma.h>
#include <asm/pmac_feature.h>
#include <asm/irq.h>
#include <asm/nvram.h>
#include "awacs_defs.h"
#include "dmasound.h"
#include "tas3001c.h"
#include "tas3004.h"
#include "tas_common.h"
#define <API key> 0
#define <API key> 7
#define AWACS_SNAPPER 110 /* fake revision # for snapper */
#define AWACS_BURGUNDY 100 /* fake revision # for burgundy */
#define AWACS_TUMBLER 90 /* fake revision # for tumbler */
#define AWACS_DACA 80 /* fake revision # for daca (ibook) */
#define AWACS_AWACS 2 /* holding revision for AWACS */
#define AWACS_SCREAMER 3 /* holding revision for Screamer */
/*
* Interrupt numbers and addresses, & info obtained from the device tree.
*/
static int awacs_irq, awacs_tx_irq, awacs_rx_irq;
static volatile struct awacs_regs __iomem *awacs;
static volatile u32 __iomem *i2s;
static volatile struct dbdma_regs __iomem *awacs_txdma, *awacs_rxdma;
static int awacs_rate_index;
static int awacs_subframe;
static struct device_node* awacs_node;
static struct device_node* i2s_node;
static char awacs_name[64];
static int awacs_revision;
static int awacs_sleeping;
static DECLARE_MUTEX(dmasound_sem);
static int sound_device_id; /* exists after iMac revA */
static int hw_can_byteswap = 1 ; /* most pmac sound h/w can */
/* model info */
/* To be replaced with better interaction with pmac_feature.c */
static int is_pbook_3X00;
static int is_pbook_g3;
/* expansion info */
static int has_perch;
static int has_ziva;
/* for earlier powerbooks which need fiddling with mac-io to enable
* cd etc.
*/
static unsigned char __iomem *latch_base;
static unsigned char __iomem *macio_base;
/*
* Space for the DBDMA command blocks.
*/
static void *awacs_tx_cmd_space;
static volatile struct dbdma_cmd *awacs_tx_cmds;
static int <API key>;
static void *awacs_rx_cmd_space;
static volatile struct dbdma_cmd *awacs_rx_cmds;
static int <API key>;
/*
* Cached values of AWACS registers (we can't read them).
* Except on the burgundy (and screamer). XXX
*/
int awacs_reg[8];
int awacs_reg1_save;
/* tracking values for the mixer contents
*/
static int spk_vol;
static int line_vol;
static int passthru_vol;
static int ip_gain; /* mic preamp settings */
static int rec_lev = 0x4545 ; /* default CD gain 69 % */
static int mic_lev;
static int cd_lev = 0x6363 ;
static int line_lev;
static int hdp_connected;
/*
* Stuff for outputting a beep. The values range from -327 to +327
* so we can multiply by an amplitude in the range 0..100 to get a
* signed short value to put in the output buffer.
*/
static short beep_wform[256] = {
0, 40, 79, 117, 153, 187, 218, 245,
269, 288, 304, 316, 323, 327, 327, 324,
318, 310, 299, 288, 275, 262, 249, 236,
224, 213, 204, 196, 190, 186, 183, 182,
182, 183, 186, 189, 192, 196, 200, 203,
206, 208, 209, 209, 209, 207, 204, 201,
197, 193, 188, 183, 179, 174, 170, 166,
163, 161, 160, 159, 159, 160, 161, 162,
164, 166, 168, 169, 171, 171, 171, 170,
169, 167, 163, 159, 155, 150, 144, 139,
133, 128, 122, 117, 113, 110, 107, 105,
103, 103, 103, 103, 104, 104, 105, 105,
105, 103, 101, 97, 92, 86, 78, 68,
58, 45, 32, 18, 3, -11, -26, -41,
-55, -68, -79, -88, -95, -100, -102, -102,
-99, -93, -85, -75, -62, -48, -33, -16,
0, 16, 33, 48, 62, 75, 85, 93,
99, 102, 102, 100, 95, 88, 79, 68,
55, 41, 26, 11, -3, -18, -32, -45,
-58, -68, -78, -86, -92, -97, -101, -103,
-105, -105, -105, -104, -104, -103, -103, -103,
-103, -105, -107, -110, -113, -117, -122, -128,
-133, -139, -144, -150, -155, -159, -163, -167,
-169, -170, -171, -171, -171, -169, -168, -166,
-164, -162, -161, -160, -159, -159, -160, -161,
-163, -166, -170, -174, -179, -183, -188, -193,
-197, -201, -204, -207, -209, -209, -209, -208,
-206, -203, -200, -196, -192, -189, -186, -183,
-182, -182, -183, -186, -190, -196, -204, -213,
-224, -236, -249, -262, -275, -288, -299, -310,
-318, -324, -327, -327, -323, -316, -304, -288,
-269, -245, -218, -187, -153, -117, -79, -40,
};
/* beep support */
#define BEEP_SRATE 22050 /* 22050 Hz sample rate */
#define BEEP_BUFLEN 512
#define BEEP_VOLUME 15 /* 0 - 100 */
static int beep_vol = BEEP_VOLUME;
static int beep_playing;
static int awacs_beep_state;
static short *beep_buf;
static void *<API key>;
static volatile struct dbdma_cmd *beep_dbdma_cmd;
/* Burgundy functions */
static void awacs_burgundy_wcw(unsigned addr,unsigned newval);
static unsigned awacs_burgundy_rcw(unsigned addr);
static void <API key>(unsigned address, int volume);
static int <API key>(unsigned address);
static void <API key>(unsigned address, int volume);
static int <API key>(unsigned address);
/* we will allocate a single 'emergency' dbdma cmd block to use if the
tx status comes up "DEAD". This happens on some PowerComputing Pmac
clones, either owing to a bug in dbdma or some interaction between
IDE and sound. However, this measure would deal with DEAD status if
if appeared elsewhere.
for the sake of memory efficiency we'll allocate this cmd as part of
the beep cmd stuff.
*/
static volatile struct dbdma_cmd *emergency_dbdma_cmd;
#ifdef CONFIG_PM
/*
* Stuff for restoring after a sleep.
*/
static int awacs_sleep_notify(struct pmu_sleep_notifier *self, int when);
struct pmu_sleep_notifier <API key> = {
awacs_sleep_notify, SLEEP_LEVEL_SOUND,
};
#endif /* CONFIG_PM */
/* for (soft) sample rate translations */
int expand_bal; /* Balance factor for expanding (not volume!) */
int expand_read_bal; /* Balance factor for expanding reads (not volume!) */
static void *PMacAlloc(unsigned int size, int flags);
static void PMacFree(void *ptr, unsigned int size);
static int PMacIrqInit(void);
#ifdef MODULE
static void PMacIrqCleanup(void);
#endif
static void PMacSilence(void);
static void PMacInit(void);
static int PMacSetFormat(int format);
static int PMacSetVolume(int volume);
static void PMacPlay(void);
static void PMacRecord(void);
static irqreturn_t pmac_awacs_tx_intr(int irq, void *devid, struct pt_regs *regs);
static irqreturn_t pmac_awacs_rx_intr(int irq, void *devid, struct pt_regs *regs);
static irqreturn_t pmac_awacs_intr(int irq, void *devid, struct pt_regs *regs);
static void awacs_write(int val);
static int awacs_get_volume(int reg, int lshift);
static int awacs_volume_setter(int volume, int n, int mute, int lshift);
static int PMacMixerIoctl(u_int cmd, u_long arg);
static int PMacWriteSqSetup(void);
static int PMacReadSqSetup(void);
static void PMacAbortRead(void);
extern TRANS transAwacsNormal ;
extern TRANS transAwacsExpand ;
extern TRANS <API key> ;
extern TRANS <API key> ;
extern int daca_init(void);
extern void daca_cleanup(void);
extern int daca_set_volume(uint left_vol, uint right_vol);
extern void daca_get_volume(uint * left_vol, uint *right_vol);
extern int daca_enter_sleep(void);
extern int daca_leave_sleep(void);
#define TRY_LOCK() \
if ((rc = down_interruptible(&dmasound_sem)) != 0) \
return rc;
#define LOCK() down(&dmasound_sem);
#define UNLOCK() up(&dmasound_sem);
/* We use different versions that the ones provided in dmasound.h
*
* FIXME: Use different names ;)
*/
#undef IOCTL_IN
#undef IOCTL_OUT
#define IOCTL_IN(arg, ret) \
rc = get_user(ret, (int __user *)(arg)); \
if (rc) break;
#define IOCTL_OUT(arg, ret) \
ioctl_return2((int __user *)(arg), ret)
static inline int ioctl_return2(int __user *addr, int value)
{
return value < 0 ? value : put_user(value, addr);
}
int gpio_audio_reset, <API key>;
int gpio_amp_mute, gpio_amp_mute_pol;
int gpio_headphone_mute, <API key>;
int <API key>, <API key>;
int gpio_headphone_irq;
int
setup_audio_gpio(const char *name, const char* compatible, int *gpio_addr, int* gpio_pol)
{
struct device_node *np;
u32* pp;
np = find_devices("gpio");
if (!np)
return -ENODEV;
np = np->child;
while(np != 0) {
if (name) {
char *property = get_property(np,"audio-gpio",NULL);
if (property != 0 && strcmp(property,name) == 0)
break;
} else if (compatible && <API key>(np, compatible))
break;
np = np->sibling;
}
if (!np)
return -ENODEV;
pp = (u32 *)get_property(np, "AAPL,address", NULL);
if (!pp)
return -ENODEV;
*gpio_addr = (*pp) & 0x0000ffff;
pp = (u32 *)get_property(np, "<API key>", NULL);
if (pp)
*gpio_pol = *pp;
else
*gpio_pol = 1;
if (np->n_intrs > 0)
return np->intrs[0].line;
return 0;
}
static inline void
write_audio_gpio(int gpio_addr, int data)
{
if (!gpio_addr)
return;
pmac_call_feature(PMAC_FTR_WRITE_GPIO, NULL, gpio_addr, data ? 0x05 : 0x04);
}
static inline int
read_audio_gpio(int gpio_addr)
{
if (!gpio_addr)
return 0;
return ((pmac_call_feature(PMAC_FTR_READ_GPIO, NULL, gpio_addr, 0) & 0x02) !=0);
}
/*
* Headphone interrupt via GPIO (Tumbler, Snapper, DACA)
*/
static irqreturn_t
headphone_intr(int irq, void *devid, struct pt_regs *regs)
{
unsigned long flags;
spin_lock_irqsave(&dmasound.lock, flags);
if (read_audio_gpio(<API key>) == <API key>) {
printk(KERN_INFO "Audio jack plugged, muting speakers.\n");
write_audio_gpio(gpio_headphone_mute, !<API key>);
write_audio_gpio(gpio_amp_mute, gpio_amp_mute_pol);
<API key>(sound_device_id,<API key>,0);
} else {
printk(KERN_INFO "Audio jack unplugged, enabling speakers.\n");
write_audio_gpio(gpio_amp_mute, !gpio_amp_mute_pol);
write_audio_gpio(gpio_headphone_mute, <API key>);
<API key>(sound_device_id,<API key>,0);
}
<API key>(&dmasound.lock, flags);
return IRQ_HANDLED;
}
/* Initialize tumbler */
static int
tas_dmasound_init(void)
{
setup_audio_gpio(
"audio-hw-reset",
NULL,
&gpio_audio_reset,
&<API key>);
setup_audio_gpio(
"amp-mute",
NULL,
&gpio_amp_mute,
&gpio_amp_mute_pol);
setup_audio_gpio("headphone-mute",
NULL,
&gpio_headphone_mute,
&<API key>);
gpio_headphone_irq = setup_audio_gpio(
"headphone-detect",
NULL,
&<API key>,
&<API key>);
/* Fix some broken OF entries in desktop machines */
if (!gpio_headphone_irq)
gpio_headphone_irq = setup_audio_gpio(
NULL,
"keywest-gpio15",
&<API key>,
&<API key>);
write_audio_gpio(gpio_audio_reset, <API key>);
msleep(100);
write_audio_gpio(gpio_audio_reset, !<API key>);
msleep(100);
if (gpio_headphone_irq) {
if (request_irq(gpio_headphone_irq,headphone_intr,0,"Headphone detect",NULL) < 0) {
printk(KERN_ERR "tumbler: Can't request headphone interrupt\n");
gpio_headphone_irq = 0;
} else {
u8 val;
/* Activate headphone status interrupts */
val = pmac_call_feature(PMAC_FTR_READ_GPIO, NULL, <API key>, 0);
pmac_call_feature(PMAC_FTR_WRITE_GPIO, NULL, <API key>, val | 0x80);
/* Trigger it */
headphone_intr(0,NULL,NULL);
}
}
if (!gpio_headphone_irq) {
/* Some machine enter this case ? */
printk(KERN_WARNING "tumbler: Headphone detect IRQ not found, enabling all outputs !\n");
write_audio_gpio(gpio_amp_mute, !gpio_amp_mute_pol);
write_audio_gpio(gpio_headphone_mute, !<API key>);
}
return 0;
}
static int
<API key>(void)
{
if (gpio_headphone_irq)
free_irq(gpio_headphone_irq, NULL);
return 0;
}
/* We don't support 48k yet */
static int tas_freqs[1] = { 44100 } ;
static int tas_freqs_ok[1] = { 1 } ;
/* don't know what to do really - just have to leave it where
* OF left things
*/
static int
tas_set_frame_rate(void)
{
if (i2s) {
out_le32(i2s + (<API key> >> 2), 0x41190000);
out_le32(i2s + (<API key> >> 2), 0x02000200);
}
dmasound.hard.speed = 44100 ;
awacs_rate_index = 0 ;
return 44100 ;
}
static int
tas_mixer_ioctl(u_int cmd, u_long arg)
{
int __user *argp = (int __user *)arg;
int data;
int rc;
rc=tas_device_ioctl(cmd, arg);
if (rc != -EINVAL) {
return rc;
}
if ((cmd & ~0xff) == MIXER_WRITE(0) &&
<API key>() & (1<<(cmd & 0xff))) {
rc = get_user(data, argp);
if (rc<0) return rc;
tas_set_mixer_level(cmd & 0xff, data);
tas_get_mixer_level(cmd & 0xff, &data);
return ioctl_return2(argp, data);
}
if ((cmd & ~0xff) == MIXER_READ(0) &&
<API key>() & (1<<(cmd & 0xff))) {
tas_get_mixer_level(cmd & 0xff, &data);
return ioctl_return2(argp, data);
}
switch(cmd) {
case <API key>:
data = <API key>() | SOUND_MASK_SPEAKER;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = tas_stereo_mixers();
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
rc = IOCTL_OUT(arg, 0);
break;
case <API key>:
// XXX FIXME: find a way to check what is really available */
data = SOUND_MASK_LINE | SOUND_MASK_MIC;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
if (awacs_reg[0] & MASK_MUX_AUDIN)
data |= SOUND_MASK_LINE;
if (awacs_reg[0] & MASK_MUX_MIC)
data |= SOUND_MASK_MIC;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
IOCTL_IN(arg, data);
data =0;
rc = IOCTL_OUT(arg, data);
break;
case <API key>: /* really bell volume */
IOCTL_IN(arg, data);
beep_vol = data & 0xff;
/* fall through */
case <API key>:
rc = IOCTL_OUT(arg, (beep_vol<<8) | beep_vol);
break;
case SOUND_MIXER_OUTMASK:
case SOUND_MIXER_OUTSRC:
default:
rc = -EINVAL;
}
return rc;
}
static void __init
<API key>(unsigned int *prop, unsigned int l)
{
int i ;
if (prop) {
for (i=0; i<1; i++)
tas_freqs_ok[i] = 0;
for (l /= sizeof(int); l > 0; --l) {
unsigned int r = *prop++;
/* Apple 'Fixed' format */
if (r >= 0x10000)
r >>= 16;
for (i = 0; i < 1; ++i) {
if (r == tas_freqs[i]) {
tas_freqs_ok[i] = 1;
break;
}
}
}
}
/* else we assume that all the rates are available */
}
/*
* PCI PowerMac, with AWACS, Screamer, Burgundy, DACA or Tumbler and DBDMA.
*/
static void *PMacAlloc(unsigned int size, int flags)
{
return kmalloc(size, flags);
}
static void PMacFree(void *ptr, unsigned int size)
{
kfree(ptr);
}
static int __init PMacIrqInit(void)
{
if (awacs)
if (request_irq(awacs_irq, pmac_awacs_intr, 0, "Built-in Sound misc", NULL))
return 0;
if (request_irq(awacs_tx_irq, pmac_awacs_tx_intr, 0, "Built-in Sound out", NULL)
|| request_irq(awacs_rx_irq, pmac_awacs_rx_intr, 0, "Built-in Sound in", NULL))
return 0;
return 1;
}
#ifdef MODULE
static void PMacIrqCleanup(void)
{
/* turn off input & output dma */
DBDMA_DO_STOP(awacs_txdma);
DBDMA_DO_STOP(awacs_rxdma);
if (awacs)
/* disable interrupts from awacs interface */
out_le32(&awacs->control, in_le32(&awacs->control) & 0xfff);
/* Switch off the sound clock */
pmac_call_feature(<API key>, awacs_node, 0, 0);
/* Make sure proper bits are set on pismo & tipb */
if ((<API key>("PowerBook3,1") ||
<API key>("PowerBook3,2")) && awacs) {
awacs_reg[1] |= MASK_PAROUT0 | MASK_PAROUT1;
awacs_write(MASK_ADDR1 | awacs_reg[1]);
msleep(200);
}
if (awacs)
free_irq(awacs_irq, NULL);
free_irq(awacs_tx_irq, NULL);
free_irq(awacs_rx_irq, NULL);
if (awacs)
iounmap(awacs);
if (i2s)
iounmap(i2s);
iounmap(awacs_txdma);
iounmap(awacs_rxdma);
release_OF_resource(awacs_node, 0);
release_OF_resource(awacs_node, 1);
release_OF_resource(awacs_node, 2);
kfree(awacs_tx_cmd_space);
kfree(awacs_rx_cmd_space);
kfree(<API key>);
kfree(beep_buf);
#ifdef CONFIG_PM
<API key>(&<API key>);
#endif
}
#endif /* MODULE */
static void PMacSilence(void)
{
/* turn off output dma */
DBDMA_DO_STOP(awacs_txdma);
}
/* don't know what to do really - just have to leave it where
* OF left things
*/
static int daca_set_frame_rate(void)
{
if (i2s) {
out_le32(i2s + (<API key> >> 2), 0x41190000);
out_le32(i2s + (<API key> >> 2), 0x02000200);
}
dmasound.hard.speed = 44100 ;
awacs_rate_index = 0 ;
return 44100 ;
}
static int awacs_freqs[8] = {
44100, 29400, 22050, 17640, 14700, 11025, 8820, 7350
};
static int awacs_freqs_ok[8] = { 1, 1, 1, 1, 1, 1, 1, 1 };
static int
<API key>(int desired, int catch_r)
{
int tolerance, i = 8 ;
/*
* If we have a sample rate which is within catchRadius percent
* of the requested value, we don't have to expand the samples.
* Otherwise choose the next higher rate.
* N.B.: burgundy awacs only works at 44100 Hz.
*/
do {
tolerance = catch_r * awacs_freqs[--i] / 100;
if (awacs_freqs_ok[i]
&& dmasound.soft.speed <= awacs_freqs[i] + tolerance)
break;
} while (i > 0);
dmasound.hard.speed = awacs_freqs[i];
awacs_rate_index = i;
out_le32(&awacs->control, MASK_IEPC | (i << 8) | 0x11 );
awacs_reg[1] = (awacs_reg[1] & ~MASK_SAMPLERATE) | (i << 3);
awacs_write(awacs_reg[1] | MASK_ADDR1);
return dmasound.hard.speed;
}
static int
<API key>(void)
{
awacs_rate_index = 0 ;
awacs_reg[1] = (awacs_reg[1] & ~MASK_SAMPLERATE) ;
/* XXX disable error interrupt on burgundy for now */
out_le32(&awacs->control, MASK_IEPC | 0 | 0x11 | MASK_IEE);
return 44100 ;
}
static int
set_frame_rate(int desired, int catch_r)
{
switch (awacs_revision) {
case AWACS_BURGUNDY:
dmasound.hard.speed = <API key>();
break ;
case AWACS_TUMBLER:
case AWACS_SNAPPER:
dmasound.hard.speed = tas_set_frame_rate();
break ;
case AWACS_DACA:
dmasound.hard.speed =
daca_set_frame_rate();
break ;
default:
dmasound.hard.speed = <API key>(desired,
catch_r);
break ;
}
return dmasound.hard.speed ;
}
static void
awacs_recalibrate(void)
{
/* Sorry for the horrible delays... I hope to get that improved
* by making the whole PM process asynchronous in a future version
*/
msleep(750);
awacs_reg[1] |= MASK_CMUTE | MASK_AMUTE;
awacs_write(awacs_reg[1] | MASK_RECALIBRATE | MASK_ADDR1);
msleep(1000);
awacs_write(awacs_reg[1] | MASK_ADDR1);
}
static void PMacInit(void)
{
int tolerance;
switch (dmasound.soft.format) {
case AFMT_S16_LE:
case AFMT_U16_LE:
if (hw_can_byteswap)
dmasound.hard.format = AFMT_S16_LE;
else
dmasound.hard.format = AFMT_S16_BE;
break;
default:
dmasound.hard.format = AFMT_S16_BE;
break;
}
dmasound.hard.stereo = 1;
dmasound.hard.size = 16;
/* set dmasound.hard.speed - on the basis of what we want (soft)
* and the tolerance we'll allow.
*/
set_frame_rate(dmasound.soft.speed, catchRadius) ;
tolerance = (catchRadius * dmasound.hard.speed) / 100;
if (dmasound.soft.speed >= dmasound.hard.speed - tolerance) {
dmasound.trans_write = &transAwacsNormal;
dmasound.trans_read = &<API key>;
} else {
dmasound.trans_write = &transAwacsExpand;
dmasound.trans_read = &<API key>;
}
if (awacs) {
if (hw_can_byteswap && (dmasound.hard.format == AFMT_S16_LE))
out_le32(&awacs->byteswap, BS_VAL);
else
out_le32(&awacs->byteswap, 0);
}
expand_bal = -dmasound.soft.speed;
expand_read_bal = -dmasound.soft.speed;
}
static int PMacSetFormat(int format)
{
int size;
int req_format = format;
switch (format) {
case AFMT_QUERY:
return dmasound.soft.format;
case AFMT_MU_LAW:
case AFMT_A_LAW:
case AFMT_U8:
case AFMT_S8:
size = 8;
break;
case AFMT_S16_LE:
if(!hw_can_byteswap)
format = AFMT_S16_BE;
case AFMT_S16_BE:
size = 16;
break;
case AFMT_U16_LE:
if(!hw_can_byteswap)
format = AFMT_U16_BE;
case AFMT_U16_BE:
size = 16;
break;
default:
printk(KERN_ERR "dmasound: unknown format 0x%x, using AFMT_U8\n",
format);
size = 8;
format = AFMT_U8;
}
if (req_format == format) {
dmasound.soft.format = format;
dmasound.soft.size = size;
if (dmasound.minDev == SND_DEV_DSP) {
dmasound.dsp.format = format;
dmasound.dsp.size = size;
}
}
return format;
}
#define <API key>(x) (15 - ((((x) - 1) * 15) / 99))
#define <API key>(y) (100 - ((y) * 99 / 15))
static int awacs_get_volume(int reg, int lshift)
{
int volume;
volume = <API key>((reg >> lshift) & 0xf);
volume |= <API key>(reg & 0xf) << 8;
return volume;
}
static int awacs_volume_setter(int volume, int n, int mute, int lshift)
{
int r1, rn;
if (mute && volume == 0) {
r1 = awacs_reg[1] | mute;
} else {
r1 = awacs_reg[1] & ~mute;
rn = awacs_reg[n] & ~(0xf | (0xf << lshift));
rn |= ((<API key>(volume & 0xff) & 0xf) << lshift);
rn |= <API key>((volume >> 8) & 0xff) & 0xf;
awacs_reg[n] = rn;
awacs_write((n << 12) | rn);
volume = awacs_get_volume(rn, lshift);
}
if (r1 != awacs_reg[1]) {
awacs_reg[1] = r1;
awacs_write(r1 | MASK_ADDR1);
}
return volume;
}
static int PMacSetVolume(int volume)
{
printk(KERN_WARNING "Bogus call to PMacSetVolume !\n");
return 0;
}
static void <API key>(int speed)
{
out_le32(&awacs->control,
(in_le32(&awacs->control) & ~0x1f00)
| ((speed > 0 ? speed : awacs_rate_index) << 8));
if (hw_can_byteswap && (dmasound.hard.format == AFMT_S16_LE) && speed == -1)
out_le32(&awacs->byteswap, BS_VAL);
else
out_le32(&awacs->byteswap, 0);
}
/* CHECK: how much of this *really* needs IRQs masked? */
static void __PMacPlay(void)
{
volatile struct dbdma_cmd *cp;
int next_frg, count;
count = 300 ; /* > two cycles at the lowest sample rate */
/* what we want to send next */
next_frg = (write_sq.front + write_sq.active) % write_sq.max_count;
if (awacs_beep_state) {
/* sound takes precedence over beeps */
/* stop the dma channel */
out_le32(&awacs_txdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16);
while ( (in_le32(&awacs_txdma->status) & RUN) && count
udelay(1);
if (awacs)
<API key>(-1);
out_le32(&awacs_txdma->cmdptr,
virt_to_bus(&(awacs_tx_cmds[next_frg])));
beep_playing = 0;
awacs_beep_state = 0;
}
/* this won't allow more than two frags to be in the output queue at
once. (or one, if the max frags is 2 - because count can't exceed
2 in that case)
*/
while (write_sq.active < 2 && write_sq.active < write_sq.count) {
count = (write_sq.count == write_sq.active + 1) ?
write_sq.rear_size:write_sq.block_size ;
if (count < write_sq.block_size) {
if (!write_sq.syncing) /* last block not yet filled,*/
break; /* and we're not syncing or POST-ed */
else {
/* pretend the block is full to force a new
block to be started on the next write */
write_sq.rear_size = write_sq.block_size ;
write_sq.syncing &= ~2 ; /* clear POST */
}
}
cp = &awacs_tx_cmds[next_frg];
st_le16(&cp->req_count, count);
st_le16(&cp->xfer_status, 0);
st_le16(&cp->command, OUTPUT_MORE + INTR_ALWAYS);
/* put a STOP at the end of the queue - but only if we have
space for it. This means that, if we under-run and we only
have two fragments, we might re-play sound from an existing
queued frag. I guess the solution to that is not to set two
frags if you are likely to under-run...
*/
if (write_sq.count < write_sq.max_count) {
if (++next_frg >= write_sq.max_count)
next_frg = 0 ; /* wrap */
/* if we get here then we've underrun so we will stop*/
st_le16(&awacs_tx_cmds[next_frg].command, DBDMA_STOP);
}
/* set the dbdma controller going, if it is not already */
if (write_sq.active == 0)
out_le32(&awacs_txdma->cmdptr, virt_to_bus(cp));
(void)in_le32(&awacs_txdma->status);
out_le32(&awacs_txdma->control, ((RUN|WAKE) << 16) + (RUN|WAKE));
++write_sq.active;
}
}
static void PMacPlay(void)
{
LOCK();
if (!awacs_sleeping) {
unsigned long flags;
spin_lock_irqsave(&dmasound.lock, flags);
__PMacPlay();
<API key>(&dmasound.lock, flags);
}
UNLOCK();
}
static void PMacRecord(void)
{
unsigned long flags;
if (read_sq.active)
return;
spin_lock_irqsave(&dmasound.lock, flags);
/* This is all we have to do......Just start it up.
*/
out_le32(&awacs_rxdma->control, ((RUN|WAKE) << 16) + (RUN|WAKE));
read_sq.active = 1;
<API key>(&dmasound.lock, flags);
}
/* if the TX status comes up "DEAD" - reported on some Power Computing machines
we need to re-start the dbdma - but from a different physical start address
and with a different transfer length. It would get very messy to do this
with the normal dbdma_cmd blocks - we would have to re-write the buffer start
addresses each time. So, we will keep a single dbdma_cmd block which can be
fiddled with.
When DEAD status is first reported the content of the faulted dbdma block is
copied into the emergency buffer and we note that the buffer is in use.
we then bump the start physical address by the amount that was successfully
output before it died.
On any subsequent DEAD result we just do the bump-ups (we know that we are
already using the emergency dbdma_cmd).
CHECK: this just tries to "do it". It is possible that we should abandon
xfers when the number of residual bytes gets below a certain value - I can
see that this might cause a loop-forever if too small a transfer causes
DEAD status. However this is a TODO for now - we'll see what gets reported.
When we get a successful transfer result with the emergency buffer we just
pretend that it completed using the original dmdma_cmd and carry on. The
'next_cmd' field will already point back to the original loop of blocks.
*/
static irqreturn_t
pmac_awacs_tx_intr(int irq, void *devid, struct pt_regs *regs)
{
int i = write_sq.front;
int stat;
int i_nowrap = write_sq.front;
volatile struct dbdma_cmd *cp;
/* != 0 when we are dealing with a DEAD xfer */
static int emergency_in_use;
spin_lock(&dmasound.lock);
while (write_sq.active > 0) { /* we expect to have done something*/
if (emergency_in_use) /* we are dealing with DEAD xfer */
cp = emergency_dbdma_cmd ;
else
cp = &awacs_tx_cmds[i];
stat = ld_le16(&cp->xfer_status);
if (stat & DEAD) {
unsigned short req, res ;
unsigned int phy ;
#ifdef DEBUG_DMASOUND
printk("dmasound_pmac: tx-irq: xfer died - patching it up...\n") ;
#endif
/* to clear DEAD status we must first clear RUN
set it to quiescent to be on the safe side */
(void)in_le32(&awacs_txdma->status);
out_le32(&awacs_txdma->control,
(RUN|PAUSE|FLUSH|WAKE) << 16);
write_sq.died++ ;
if (!emergency_in_use) { /* new problem */
memcpy((void *)emergency_dbdma_cmd, (void *)cp,
sizeof(struct dbdma_cmd));
emergency_in_use = 1;
cp = emergency_dbdma_cmd;
}
/* now bump the values to reflect the amount
we haven't yet shifted */
req = ld_le16(&cp->req_count);
res = ld_le16(&cp->res_count);
phy = ld_le32(&cp->phy_addr);
phy += (req - res);
st_le16(&cp->req_count, res);
st_le16(&cp->res_count, 0);
st_le16(&cp->xfer_status, 0);
st_le32(&cp->phy_addr, phy);
st_le32(&cp->cmd_dep, virt_to_bus(&awacs_tx_cmds[(i+1)%write_sq.max_count]));
st_le16(&cp->command, OUTPUT_MORE | BR_ALWAYS | INTR_ALWAYS);
/* point at our patched up command block */
out_le32(&awacs_txdma->cmdptr, virt_to_bus(cp));
/* we must re-start the controller */
(void)in_le32(&awacs_txdma->status);
/* should complete clearing the DEAD status */
out_le32(&awacs_txdma->control,
((RUN|WAKE) << 16) + (RUN|WAKE));
break; /* this block is still going */
}
if ((stat & ACTIVE) == 0)
break; /* this frame is still going */
if (emergency_in_use)
emergency_in_use = 0 ; /* done that */
--write_sq.count;
--write_sq.active;
i_nowrap++;
if (++i >= write_sq.max_count)
i = 0;
}
/* if we stopped and we were not sync-ing - then we under-ran */
if( write_sq.syncing == 0 ){
stat = in_le32(&awacs_txdma->status) ;
/* we hit the dbdma_stop */
if( (stat & ACTIVE) == 0 ) write_sq.xruns++ ;
}
/* if we used some data up then wake the writer to supply some more*/
if (i_nowrap != write_sq.front)
WAKE_UP(write_sq.action_queue);
write_sq.front = i;
/* but make sure we funnel what we've already got */\
if (!awacs_sleeping)
__PMacPlay();
/* make the wake-on-empty conditional on syncing */
if (!write_sq.active && (write_sq.syncing & 1))
WAKE_UP(write_sq.sync_queue); /* any time we're empty */
spin_unlock(&dmasound.lock);
return IRQ_HANDLED;
}
static irqreturn_t
pmac_awacs_rx_intr(int irq, void *devid, struct pt_regs *regs)
{
int stat ;
/* For some reason on my PowerBook G3, I get one interrupt
* when the interrupt vector is installed (like something is
* pending). This happens before the dbdma is initialized by
* us, so I just check the command pointer and if it is zero,
* just blow it off.
*/
if (in_le32(&awacs_rxdma->cmdptr) == 0)
return IRQ_HANDLED;
/* We also want to blow 'em off when shutting down.
*/
if (read_sq.active == 0)
return IRQ_HANDLED;
spin_lock(&dmasound.lock);
/* Check multiple buffers in case we were held off from
* interrupt processing for a long time. Geeze, I really hope
* this doesn't happen.
*/
while ((stat=awacs_rx_cmds[read_sq.rear].xfer_status)) {
/* if we got a "DEAD" status then just log it for now.
and try to restart dma.
TODO: figure out how best to fix it up
*/
if (stat & DEAD){
#ifdef DEBUG_DMASOUND
printk("dmasound_pmac: rx-irq: DIED - attempting resurection\n");
#endif
/* to clear DEAD status we must first clear RUN
set it to quiescent to be on the safe side */
(void)in_le32(&awacs_txdma->status);
out_le32(&awacs_txdma->control,
(RUN|PAUSE|FLUSH|WAKE) << 16);
awacs_rx_cmds[read_sq.rear].xfer_status = 0;
awacs_rx_cmds[read_sq.rear].res_count = 0;
read_sq.died++ ;
(void)in_le32(&awacs_txdma->status);
/* re-start the same block */
out_le32(&awacs_rxdma->cmdptr,
virt_to_bus(&awacs_rx_cmds[read_sq.rear]));
/* we must re-start the controller */
(void)in_le32(&awacs_rxdma->status);
/* should complete clearing the DEAD status */
out_le32(&awacs_rxdma->control,
((RUN|WAKE) << 16) + (RUN|WAKE));
spin_unlock(&dmasound.lock);
return IRQ_HANDLED; /* try this block again */
}
/* Clear status and move on to next buffer.
*/
awacs_rx_cmds[read_sq.rear].xfer_status = 0;
read_sq.rear++;
/* Wrap the buffer ring.
*/
if (read_sq.rear >= read_sq.max_active)
read_sq.rear = 0;
/* If we have caught up to the front buffer, bump it.
* This will cause weird (but not fatal) results if the
* read loop is currently using this buffer. The user is
* behind in this case anyway, so weird things are going
* to happen.
*/
if (read_sq.rear == read_sq.front) {
read_sq.front++;
read_sq.xruns++ ; /* we overan */
if (read_sq.front >= read_sq.max_active)
read_sq.front = 0;
}
}
WAKE_UP(read_sq.action_queue);
spin_unlock(&dmasound.lock);
return IRQ_HANDLED;
}
static irqreturn_t
pmac_awacs_intr(int irq, void *devid, struct pt_regs *regs)
{
int ctrl;
int status;
int r1;
spin_lock(&dmasound.lock);
ctrl = in_le32(&awacs->control);
status = in_le32(&awacs->codec_stat);
if (ctrl & MASK_PORTCHG) {
/* tested on Screamer, should work on others too */
if (awacs_revision == AWACS_SCREAMER) {
if (((status & MASK_HDPCONN) >> 3) && (hdp_connected == 0)) {
hdp_connected = 1;
r1 = awacs_reg[1] | MASK_SPKMUTE;
awacs_reg[1] = r1;
awacs_write(r1 | MASK_ADDR_MUTE);
} else if (((status & MASK_HDPCONN) >> 3 == 0) && (hdp_connected == 1)) {
hdp_connected = 0;
r1 = awacs_reg[1] & ~MASK_SPKMUTE;
awacs_reg[1] = r1;
awacs_write(r1 | MASK_ADDR_MUTE);
}
}
}
if (ctrl & MASK_CNTLERR) {
int err = (in_le32(&awacs->codec_stat) & MASK_ERRCODE) >> 16;
/* CHECK: we just swallow burgundy errors at the moment..*/
if (err != 0 && awacs_revision != AWACS_BURGUNDY)
printk(KERN_ERR "dmasound_pmac: error %x\n", err);
}
/* Writing 1s to the CNTLERR and PORTCHG bits clears them... */
out_le32(&awacs->control, ctrl);
spin_unlock(&dmasound.lock);
return IRQ_HANDLED;
}
static void
awacs_write(int val)
{
int count = 300 ;
if (awacs_revision >= AWACS_DACA || !awacs)
return ;
while ((in_le32(&awacs->codec_ctrl) & MASK_NEWECMD) && count
udelay(1) ; /* timeout is > 2 samples at lowest rate */
out_le32(&awacs->codec_ctrl, val | (awacs_subframe << 22));
(void)in_le32(&awacs->byteswap);
}
/* this is called when the beep timer expires... it will be called even
if the beep has been overidden by other sound output.
*/
static void awacs_nosound(unsigned long xx)
{
unsigned long flags;
int count = 600 ; /* > four samples at lowest rate */
spin_lock_irqsave(&dmasound.lock, flags);
if (beep_playing) {
st_le16(&beep_dbdma_cmd->command, DBDMA_STOP);
out_le32(&awacs_txdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16);
while ((in_le32(&awacs_txdma->status) & RUN) && count
udelay(1);
if (awacs)
<API key>(-1);
beep_playing = 0;
}
<API key>(&dmasound.lock, flags);
}
/*
* We generate the beep with a single dbdma command that loops a buffer
* forever - without generating interrupts.
*
* So, to stop it you have to stop dma output as per awacs_nosound.
*/
static int awacs_beep_event(struct input_dev *dev, unsigned int type,
unsigned int code, int hz)
{
unsigned long flags;
int beep_speed = 0;
int srate;
int period, ncycles, nsamples;
int i, j, f;
short *p;
static int beep_hz_cache;
static int beep_nsamples_cache;
static int beep_volume_cache;
if (type != EV_SND)
return -1;
switch (code) {
case SND_BELL:
if (hz)
hz = 1000;
break;
case SND_TONE:
break;
default:
return -1;
}
if (beep_buf == NULL)
return -1;
/* quick-hack fix for DACA, Burgundy & Tumbler */
if (awacs_revision >= AWACS_DACA){
srate = 44100 ;
} else {
for (i = 0; i < 8 && awacs_freqs[i] >= BEEP_SRATE; ++i)
if (awacs_freqs_ok[i])
beep_speed = i;
srate = awacs_freqs[beep_speed];
}
if (hz <= srate / BEEP_BUFLEN || hz > srate / 2) {
/* cancel beep currently playing */
awacs_nosound(0);
return 0;
}
spin_lock_irqsave(&dmasound.lock, flags);
if (beep_playing || write_sq.active || beep_buf == NULL) {
<API key>(&dmasound.lock, flags);
return -1; /* too hard, sorry :-( */
}
beep_playing = 1;
st_le16(&beep_dbdma_cmd->command, OUTPUT_MORE + BR_ALWAYS);
<API key>(&dmasound.lock, flags);
if (hz == beep_hz_cache && beep_vol == beep_volume_cache) {
nsamples = beep_nsamples_cache;
} else {
period = srate * 256 / hz; /* fixed point */
ncycles = BEEP_BUFLEN * 256 / period;
nsamples = (period * ncycles) >> 8;
f = ncycles * 65536 / nsamples;
j = 0;
p = beep_buf;
for (i = 0; i < nsamples; ++i, p += 2) {
p[0] = p[1] = beep_wform[j >> 8] * beep_vol;
j = (j + f) & 0xffff;
}
beep_hz_cache = hz;
beep_volume_cache = beep_vol;
beep_nsamples_cache = nsamples;
}
st_le16(&beep_dbdma_cmd->req_count, nsamples*4);
st_le16(&beep_dbdma_cmd->xfer_status, 0);
st_le32(&beep_dbdma_cmd->cmd_dep, virt_to_bus(beep_dbdma_cmd));
st_le32(&beep_dbdma_cmd->phy_addr, virt_to_bus(beep_buf));
awacs_beep_state = 1;
spin_lock_irqsave(&dmasound.lock, flags);
if (beep_playing) { /* i.e. haven't been terminated already */
int count = 300 ;
out_le32(&awacs_txdma->control, (RUN|WAKE|FLUSH|PAUSE) << 16);
while ((in_le32(&awacs_txdma->status) & RUN) && count
udelay(1); /* timeout > 2 samples at lowest rate*/
if (awacs)
<API key>(beep_speed);
out_le32(&awacs_txdma->cmdptr, virt_to_bus(beep_dbdma_cmd));
(void)in_le32(&awacs_txdma->status);
out_le32(&awacs_txdma->control, RUN | (RUN << 16));
}
<API key>(&dmasound.lock, flags);
return 0;
}
/* used in init and for wake-up */
static void
load_awacs(void)
{
awacs_write(awacs_reg[0] + MASK_ADDR0);
awacs_write(awacs_reg[1] + MASK_ADDR1);
awacs_write(awacs_reg[2] + MASK_ADDR2);
awacs_write(awacs_reg[4] + MASK_ADDR4);
if (awacs_revision == AWACS_SCREAMER) {
awacs_write(awacs_reg[5] + MASK_ADDR5);
msleep(100);
awacs_write(awacs_reg[6] + MASK_ADDR6);
msleep(2);
awacs_write(awacs_reg[1] + MASK_ADDR1);
awacs_write(awacs_reg[7] + MASK_ADDR7);
}
if (awacs) {
if (hw_can_byteswap && (dmasound.hard.format == AFMT_S16_LE))
out_le32(&awacs->byteswap, BS_VAL);
else
out_le32(&awacs->byteswap, 0);
}
}
#ifdef CONFIG_PM
/*
* Save state when going to sleep, restore it afterwards.
*/
/* FIXME: sort out disabling/re-enabling of read stuff as well */
static int awacs_sleep_notify(struct pmu_sleep_notifier *self, int when)
{
unsigned long flags;
switch (when) {
case PBOOK_SLEEP_NOW:
LOCK();
awacs_sleeping = 1;
/* Tell the rest of the driver we are now going to sleep */
mb();
if (awacs_revision == AWACS_SCREAMER ||
awacs_revision == AWACS_AWACS) {
awacs_reg1_save = awacs_reg[1];
awacs_reg[1] |= MASK_AMUTE | MASK_CMUTE;
awacs_write(MASK_ADDR1 | awacs_reg[1]);
}
PMacSilence();
/* stop rx - if going - a bit of a daft user... but */
out_le32(&awacs_rxdma->control, (RUN|WAKE|FLUSH << 16));
/* deny interrupts */
if (awacs)
disable_irq(awacs_irq);
disable_irq(awacs_tx_irq);
disable_irq(awacs_rx_irq);
/* Chip specific sleep code */
switch (awacs_revision) {
case AWACS_TUMBLER:
case AWACS_SNAPPER:
write_audio_gpio(gpio_headphone_mute, <API key>);
write_audio_gpio(gpio_amp_mute, gpio_amp_mute_pol);
tas_enter_sleep();
write_audio_gpio(gpio_audio_reset, <API key>);
break ;
case AWACS_DACA:
daca_enter_sleep();
break ;
case AWACS_BURGUNDY:
break ;
case AWACS_SCREAMER:
case AWACS_AWACS:
default:
out_le32(&awacs->control, 0x11) ;
break ;
}
/* Disable sound clock */
pmac_call_feature(<API key>, awacs_node, 0, 0);
/* According to Darwin, we do that after turning off the sound
* chip clock. All this will have to be cleaned up once we properly
* parse the OF sound-objects
*/
if ((<API key>("PowerBook3,1") ||
<API key>("PowerBook3,2")) && awacs) {
awacs_reg[1] |= MASK_PAROUT0 | MASK_PAROUT1;
awacs_write(MASK_ADDR1 | awacs_reg[1]);
msleep(200);
}
break;
case PBOOK_WAKE:
/* Enable sound clock */
pmac_call_feature(<API key>, awacs_node, 0, 1);
if ((<API key>("PowerBook3,1") ||
<API key>("PowerBook3,2")) && awacs) {
msleep(100);
awacs_reg[1] &= ~(MASK_PAROUT0 | MASK_PAROUT1);
awacs_write(MASK_ADDR1 | awacs_reg[1]);
msleep(300);
} else
msleep(1000);
/* restore settings */
switch (awacs_revision) {
case AWACS_TUMBLER:
case AWACS_SNAPPER:
write_audio_gpio(gpio_headphone_mute, <API key>);
write_audio_gpio(gpio_amp_mute, gpio_amp_mute_pol);
write_audio_gpio(gpio_audio_reset, <API key>);
msleep(100);
write_audio_gpio(gpio_audio_reset, !<API key>);
msleep(150);
tas_leave_sleep(); /* Stub for now */
headphone_intr(0,NULL,NULL);
break;
case AWACS_DACA:
msleep(10); /* Check this !!! */
daca_leave_sleep();
break ; /* dont know how yet */
case AWACS_BURGUNDY:
break ;
case AWACS_SCREAMER:
case AWACS_AWACS:
default:
load_awacs() ;
break ;
}
/* Recalibrate chip */
if (awacs_revision == AWACS_SCREAMER && awacs)
awacs_recalibrate();
/* Make sure dma is stopped */
PMacSilence();
if (awacs)
enable_irq(awacs_irq);
enable_irq(awacs_tx_irq);
enable_irq(awacs_rx_irq);
if (awacs) {
/* OK, allow ints back again */
out_le32(&awacs->control, MASK_IEPC
| (awacs_rate_index << 8) | 0x11
| (awacs_revision < AWACS_DACA ? MASK_IEE: 0));
}
if (macio_base && is_pbook_g3) {
/* FIXME: should restore the setup we had...*/
out_8(macio_base + 0x37, 3);
} else if (is_pbook_3X00) {
in_8(latch_base + 0x190);
}
/* Remove mute */
if (awacs_revision == AWACS_SCREAMER ||
awacs_revision == AWACS_AWACS) {
awacs_reg[1] = awacs_reg1_save;
awacs_write(MASK_ADDR1 | awacs_reg[1]);
}
awacs_sleeping = 0;
/* Resume pending sounds. */
/* we don't try to restart input... */
spin_lock_irqsave(&dmasound.lock, flags);
__PMacPlay();
<API key>(&dmasound.lock, flags);
UNLOCK();
}
return PBOOK_SLEEP_OK;
}
#endif /* CONFIG_PM */
/* All the burgundy functions: */
/* Waits for busy flag to clear */
static inline void
<API key>(void)
{
int count = 50; /* > 2 samples at 44k1 */
while ((in_le32(&awacs->codec_ctrl) & MASK_NEWECMD) && count
udelay(1) ;
}
static inline void
<API key>(void)
{
int count = 50 ; /* > 2 samples at 44k1 */
while ((!(in_le32(&awacs->codec_stat) & MASK_EXTEND)) && count
udelay(1) ;
count = 50;
while ((in_le32(&awacs->codec_stat) & MASK_EXTEND) && count
udelay(1);
}
static void
awacs_burgundy_wcw(unsigned addr, unsigned val)
{
out_le32(&awacs->codec_ctrl, addr + 0x200c00 + (val & 0xff));
<API key>();
out_le32(&awacs->codec_ctrl, addr + 0x200d00 +((val>>8) & 0xff));
<API key>();
out_le32(&awacs->codec_ctrl, addr + 0x200e00 +((val>>16) & 0xff));
<API key>();
out_le32(&awacs->codec_ctrl, addr + 0x200f00 +((val>>24) & 0xff));
<API key>();
}
static unsigned
awacs_burgundy_rcw(unsigned addr)
{
unsigned val = 0;
unsigned long flags;
/* should have timeouts here */
spin_lock_irqsave(&dmasound.lock, flags);
out_le32(&awacs->codec_ctrl, addr + 0x100000);
<API key>();
<API key>();
val += (in_le32(&awacs->codec_stat) >> 4) & 0xff;
out_le32(&awacs->codec_ctrl, addr + 0x100100);
<API key>();
<API key>();
val += ((in_le32(&awacs->codec_stat)>>4) & 0xff) <<8;
out_le32(&awacs->codec_ctrl, addr + 0x100200);
<API key>();
<API key>();
val += ((in_le32(&awacs->codec_stat)>>4) & 0xff) <<16;
out_le32(&awacs->codec_ctrl, addr + 0x100300);
<API key>();
<API key>();
val += ((in_le32(&awacs->codec_stat)>>4) & 0xff) <<24;
<API key>(&dmasound.lock, flags);
return val;
}
static void
awacs_burgundy_wcb(unsigned addr, unsigned val)
{
out_le32(&awacs->codec_ctrl, addr + 0x300000 + (val & 0xff));
<API key>();
}
static unsigned
awacs_burgundy_rcb(unsigned addr)
{
unsigned val = 0;
unsigned long flags;
/* should have timeouts here */
spin_lock_irqsave(&dmasound.lock, flags);
out_le32(&awacs->codec_ctrl, addr + 0x100000);
<API key>();
<API key>();
val += (in_le32(&awacs->codec_stat) >> 4) & 0xff;
<API key>(&dmasound.lock, flags);
return val;
}
static int
<API key>(void)
{
/* Checks to see the chip is alive and kicking */
int error = in_le32(&awacs->codec_ctrl) & MASK_ERRCODE;
return error == 0xf0000;
}
static int
awacs_burgundy_init(void)
{
if (<API key>()) {
printk(KERN_WARNING "dmasound_pmac: burgundy not working :-(\n");
return 1;
}
awacs_burgundy_wcb(<API key>,
<API key>);
awacs_burgundy_wcb(<API key>,
<API key>);
awacs_burgundy_wcw(<API key>,
<API key>);
awacs_burgundy_wcb(<API key>,
<API key>);
awacs_burgundy_wcb(<API key>,
<API key>);
awacs_burgundy_wcb(<API key>,
DEF_BURGUNDY_GAINCD);
awacs_burgundy_wcb(<API key>,
<API key>);
awacs_burgundy_wcb(<API key>,
<API key>);
awacs_burgundy_wcb(<API key>,
<API key>);
awacs_burgundy_wcb(<API key>,
<API key>);
awacs_burgundy_wcb(<API key>,
<API key>);
awacs_burgundy_wcb(<API key>,
<API key>);
awacs_burgundy_wcw(<API key>,
<API key>);
awacs_burgundy_wcw(<API key>,
DEF_BURGUNDY_VOLCD);
awacs_burgundy_wcw(<API key>,
<API key>);
awacs_burgundy_wcw(<API key>,
DEF_BURGUNDY_VOLMIC);
return 0;
}
static void
<API key>(unsigned address, int volume)
{
int hardvolume,lvolume,rvolume;
lvolume = (volume & 0xff) ? (volume & 0xff) + 155 : 0;
rvolume = ((volume >>8)&0xff) ? ((volume >> 8)&0xff ) + 155 : 0;
hardvolume = lvolume + (rvolume << 16);
awacs_burgundy_wcw(address, hardvolume);
}
static int
<API key>(unsigned address)
{
int softvolume,wvolume;
wvolume = awacs_burgundy_rcw(address);
softvolume = (wvolume & 0xff) - 155;
softvolume += (((wvolume >> 16) & 0xff) - 155)<<8;
return softvolume > 0 ? softvolume : 0;
}
static int
<API key>(unsigned address)
{
int lvolume,rvolume,wvolume;
wvolume = awacs_burgundy_rcw(address);
wvolume &= 0xffff;
rvolume = (wvolume & 0xff) - 155;
lvolume = ((wvolume & 0xff00)>>8) - 155;
return lvolume + (rvolume << 8);
}
static void
<API key>(unsigned address, int volume)
{
int lvolume,rvolume,hardvolume;
lvolume = (volume &0xff) ? (volume & 0xff) + 155 :0;
rvolume = ((volume >>8) & 0xff) ? (volume >> 8) + 155 :0;
hardvolume = lvolume + (rvolume << 8);
hardvolume += (hardvolume << 16);
awacs_burgundy_wcw(address, hardvolume);
}
/* End burgundy functions */
/* Set up output volumes on machines with the 'perch/whisper' extension card.
* this has an SGS i2c chip (7433) which is accessed using the cuda.
*
* TODO: split this out and make use of the other parts of the SGS chip to
* do Bass, Treble etc.
*/
static void
awacs_enable_amp(int spkr_vol)
{
#ifdef CONFIG_ADB_CUDA
struct adb_request req;
if (sys_ctrler != SYS_CTRLER_CUDA)
return;
/* turn on headphones */
cuda_request(&req, NULL, 5, CUDA_PACKET, CUDA_GET_SET_IIC,
0x8a, 4, 0);
while (!req.complete) cuda_poll();
cuda_request(&req, NULL, 5, CUDA_PACKET, CUDA_GET_SET_IIC,
0x8a, 6, 0);
while (!req.complete) cuda_poll();
/* turn on speaker */
cuda_request(&req, NULL, 5, CUDA_PACKET, CUDA_GET_SET_IIC,
0x8a, 3, (100 - (spkr_vol & 0xff)) * 32 / 100);
while (!req.complete) cuda_poll();
cuda_request(&req, NULL, 5, CUDA_PACKET, CUDA_GET_SET_IIC,
0x8a, 5, (100 - ((spkr_vol >> 8) & 0xff)) * 32 / 100);
while (!req.complete) cuda_poll();
cuda_request(&req, NULL, 5, CUDA_PACKET,
CUDA_GET_SET_IIC, 0x8a, 1, 0x29);
while (!req.complete) cuda_poll();
#endif /* CONFIG_ADB_CUDA */
}
/*
* /dev/mixer abstraction
*/
static void do_line_lev(int data)
{
line_lev = data ;
awacs_reg[0] &= ~MASK_MUX_AUDIN;
if ((data & 0xff) >= 50)
awacs_reg[0] |= MASK_MUX_AUDIN;
awacs_write(MASK_ADDR0 | awacs_reg[0]);
}
static void do_ip_gain(int data)
{
ip_gain = data ;
data &= 0xff;
awacs_reg[0] &= ~MASK_GAINLINE;
if (awacs_revision == AWACS_SCREAMER) {
awacs_reg[6] &= ~MASK_MIC_BOOST ;
if (data >= 33) {
awacs_reg[0] |= MASK_GAINLINE;
if( data >= 66)
awacs_reg[6] |= MASK_MIC_BOOST ;
}
awacs_write(MASK_ADDR6 | awacs_reg[6]) ;
} else {
if (data >= 50)
awacs_reg[0] |= MASK_GAINLINE;
}
awacs_write(MASK_ADDR0 | awacs_reg[0]);
}
static void do_mic_lev(int data)
{
mic_lev = data ;
data &= 0xff;
awacs_reg[0] &= ~MASK_MUX_MIC;
if (data >= 50)
awacs_reg[0] |= MASK_MUX_MIC;
awacs_write(MASK_ADDR0 | awacs_reg[0]);
}
static void do_cd_lev(int data)
{
cd_lev = data ;
awacs_reg[0] &= ~MASK_MUX_CD;
if ((data & 0xff) >= 50)
awacs_reg[0] |= MASK_MUX_CD;
awacs_write(MASK_ADDR0 | awacs_reg[0]);
}
static void do_rec_lev(int data)
{
int left, right ;
rec_lev = data ;
/* need to fudge this to use the volume setter routine */
left = 100 - (data & 0xff) ; if( left < 0 ) left = 0 ;
right = 100 - ((data >> 8) & 0xff) ; if( right < 0 ) right = 0 ;
left |= (right << 8 );
left = awacs_volume_setter(left, 0, 0, 4);
}
static void do_passthru_vol(int data)
{
passthru_vol = data ;
awacs_reg[1] &= ~MASK_LOOPTHRU;
if (awacs_revision == AWACS_SCREAMER) {
if( data ) { /* switch it on for non-zero */
awacs_reg[1] |= MASK_LOOPTHRU;
awacs_write(MASK_ADDR1 | awacs_reg[1]);
}
data = awacs_volume_setter(data, 5, 0, 6) ;
} else {
if ((data & 0xff) >= 50)
awacs_reg[1] |= MASK_LOOPTHRU;
awacs_write(MASK_ADDR1 | awacs_reg[1]);
data = (awacs_reg[1] & MASK_LOOPTHRU)? 100: 0;
}
}
static int awacs_mixer_ioctl(u_int cmd, u_long arg)
{
int data;
int rc;
switch (cmd) {
case <API key>:
/* say we will allow multiple inputs? prob. wrong
so I'm switching it to single */
return IOCTL_OUT(arg, 1);
case <API key>:
data = SOUND_MASK_VOLUME | SOUND_MASK_SPEAKER
| SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD
| SOUND_MASK_IGAIN | SOUND_MASK_RECLEV
| SOUND_MASK_ALTPCM
| SOUND_MASK_MONITOR;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = 0;
if (awacs_reg[0] & MASK_MUX_AUDIN)
data |= SOUND_MASK_LINE;
if (awacs_reg[0] & MASK_MUX_MIC)
data |= SOUND_MASK_MIC;
if (awacs_reg[0] & MASK_MUX_CD)
data |= SOUND_MASK_CD;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
IOCTL_IN(arg, data);
data &= (SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD);
awacs_reg[0] &= ~(MASK_MUX_CD | MASK_MUX_MIC
| MASK_MUX_AUDIN);
if (data & SOUND_MASK_LINE)
awacs_reg[0] |= MASK_MUX_AUDIN;
if (data & SOUND_MASK_MIC)
awacs_reg[0] |= MASK_MUX_MIC;
if (data & SOUND_MASK_CD)
awacs_reg[0] |= MASK_MUX_CD;
awacs_write(awacs_reg[0] | MASK_ADDR0);
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = SOUND_MASK_VOLUME | SOUND_MASK_SPEAKER| SOUND_MASK_RECLEV ;
if (awacs_revision == AWACS_SCREAMER)
data |= SOUND_MASK_MONITOR ;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
IOCTL_IN(arg, data);
line_vol = data ;
awacs_volume_setter(data, 2, 0, 6);
/* fall through */
case <API key>:
rc = IOCTL_OUT(arg, line_vol);
break;
case <API key>:
IOCTL_IN(arg, data);
spk_vol = data ;
if (has_perch)
awacs_enable_amp(data);
else
(void)awacs_volume_setter(data, 4, MASK_CMUTE, 6);
/* fall though */
case <API key>:
rc = IOCTL_OUT(arg, spk_vol);
break;
case <API key>: /* really bell volume */
IOCTL_IN(arg, data);
beep_vol = data & 0xff;
/* fall through */
case <API key>:
rc = IOCTL_OUT(arg, beep_vol);
break;
case <API key>:
IOCTL_IN(arg, data);
do_line_lev(data) ;
/* fall through */
case <API key>:
rc = IOCTL_OUT(arg, line_lev);
break;
case <API key>:
IOCTL_IN(arg, data);
do_ip_gain(data) ;
/* fall through */
case <API key>:
rc = IOCTL_OUT(arg, ip_gain);
break;
case <API key>:
IOCTL_IN(arg, data);
do_mic_lev(data);
/* fall through */
case <API key>:
rc = IOCTL_OUT(arg, mic_lev);
break;
case <API key>:
IOCTL_IN(arg, data);
do_cd_lev(data);
/* fall through */
case SOUND_MIXER_READ_CD:
rc = IOCTL_OUT(arg, cd_lev);
break;
case <API key>:
IOCTL_IN(arg, data);
do_rec_lev(data) ;
/* fall through */
case <API key>:
rc = IOCTL_OUT(arg, rec_lev);
break;
case MIXER_WRITE(SOUND_MIXER_MONITOR):
IOCTL_IN(arg, data);
do_passthru_vol(data) ;
/* fall through */
case MIXER_READ(SOUND_MIXER_MONITOR):
rc = IOCTL_OUT(arg, passthru_vol);
break;
default:
rc = -EINVAL;
}
return rc;
}
static void awacs_mixer_init(void)
{
awacs_volume_setter(line_vol, 2, 0, 6);
if (has_perch)
awacs_enable_amp(spk_vol);
else
(void)awacs_volume_setter(spk_vol, 4, MASK_CMUTE, 6);
do_line_lev(line_lev) ;
do_ip_gain(ip_gain) ;
do_mic_lev(mic_lev) ;
do_cd_lev(cd_lev) ;
do_rec_lev(rec_lev) ;
do_passthru_vol(passthru_vol) ;
}
static int <API key>(u_int cmd, u_long arg)
{
int data;
int rc;
/* We are, we are, we are... Burgundy or better */
switch(cmd) {
case <API key>:
data = SOUND_MASK_VOLUME | SOUND_MASK_CD |
SOUND_MASK_LINE | SOUND_MASK_MIC |
SOUND_MASK_SPEAKER | SOUND_MASK_ALTPCM;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = SOUND_MASK_LINE | SOUND_MASK_MIC
| SOUND_MASK_CD;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = 0;
if (awacs_reg[0] & MASK_MUX_AUDIN)
data |= SOUND_MASK_LINE;
if (awacs_reg[0] & MASK_MUX_MIC)
data |= SOUND_MASK_MIC;
if (awacs_reg[0] & MASK_MUX_CD)
data |= SOUND_MASK_CD;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
IOCTL_IN(arg, data);
data &= (SOUND_MASK_LINE
| SOUND_MASK_MIC | SOUND_MASK_CD);
awacs_reg[0] &= ~(MASK_MUX_CD | MASK_MUX_MIC
| MASK_MUX_AUDIN);
if (data & SOUND_MASK_LINE)
awacs_reg[0] |= MASK_MUX_AUDIN;
if (data & SOUND_MASK_MIC)
awacs_reg[0] |= MASK_MUX_MIC;
if (data & SOUND_MASK_CD)
awacs_reg[0] |= MASK_MUX_CD;
awacs_write(awacs_reg[0] | MASK_ADDR0);
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = SOUND_MASK_VOLUME | SOUND_MASK_SPEAKER
| SOUND_MASK_RECLEV | SOUND_MASK_CD
| SOUND_MASK_LINE;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
rc = IOCTL_OUT(arg, 0);
break;
case <API key>:
IOCTL_IN(arg, data);
<API key>(<API key>, data);
/* Fall through */
case <API key>:
rc = IOCTL_OUT(arg, <API key>(<API key>));
break;
case <API key>:
IOCTL_IN(arg, data);
if (!(data & 0xff)) {
/* Mute the left speaker */
awacs_burgundy_wcb(<API key>,
awacs_burgundy_rcb(<API key>) & ~0x2);
} else {
/* Unmute the left speaker */
awacs_burgundy_wcb(<API key>,
awacs_burgundy_rcb(<API key>) | 0x2);
}
if (!(data & 0xff00)) {
/* Mute the right speaker */
awacs_burgundy_wcb(<API key>,
awacs_burgundy_rcb(<API key>) & ~0x4);
} else {
/* Unmute the right speaker */
awacs_burgundy_wcb(<API key>,
awacs_burgundy_rcb(<API key>) | 0x4);
}
data = (((data&0xff)*16)/100 > 0xf ? 0xf :
(((data&0xff)*16)/100)) +
((((data>>8)*16)/100 > 0xf ? 0xf :
((((data>>8)*16)/100)))<<4);
awacs_burgundy_wcb(<API key>, ~data);
/* Fall through */
case <API key>:
data = awacs_burgundy_rcb(<API key>);
data = (((data & 0xf)*100)/16) + ((((data>>4)*100)/16)<<8);
rc = IOCTL_OUT(arg, (~data) & 0x0000ffff);
break;
case <API key>: /* really bell volume */
IOCTL_IN(arg, data);
beep_vol = data & 0xff;
/* fall through */
case <API key>:
rc = IOCTL_OUT(arg, beep_vol);
break;
case <API key>:
IOCTL_IN(arg, data);
<API key>(<API key>, data);
/* fall through */
case <API key>:
data = <API key>(<API key>);
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
IOCTL_IN(arg, data);
/* Mic is mono device */
data = (data << 8) + (data << 24);
<API key>(<API key>, data);
/* fall through */
case <API key>:
data = <API key>(<API key>);
data <<= 24;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
IOCTL_IN(arg, data);
<API key>(<API key>, data);
/* fall through */
case SOUND_MIXER_READ_CD:
data = <API key>(<API key>);
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
IOCTL_IN(arg, data);
data = awacs_volume_setter(data, 0, 0, 4);
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = awacs_get_volume(awacs_reg[0], 4);
rc = IOCTL_OUT(arg, data);
break;
case SOUND_MIXER_OUTMASK:
case SOUND_MIXER_OUTSRC:
default:
rc = -EINVAL;
}
return rc;
}
static int daca_mixer_ioctl(u_int cmd, u_long arg)
{
int data;
int rc;
/* And the DACA's no genius either! */
switch(cmd) {
case <API key>:
data = SOUND_MASK_VOLUME;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = 0;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = 0;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
IOCTL_IN(arg, data);
data =0;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
data = SOUND_MASK_VOLUME;
rc = IOCTL_OUT(arg, data);
break;
case <API key>:
rc = IOCTL_OUT(arg, 0);
break;
case <API key>:
IOCTL_IN(arg, data);
daca_set_volume(data, data);
/* Fall through */
case <API key>:
daca_get_volume(& data, &data);
rc = IOCTL_OUT(arg, data);
break;
case SOUND_MIXER_OUTMASK:
case SOUND_MIXER_OUTSRC:
default:
rc = -EINVAL;
}
return rc;
}
static int PMacMixerIoctl(u_int cmd, u_long arg)
{
int rc;
/* Different IOCTLS for burgundy and, eventually, DACA & Tumbler */
TRY_LOCK();
switch (awacs_revision){
case AWACS_BURGUNDY:
rc = <API key>(cmd, arg);
break ;
case AWACS_DACA:
rc = daca_mixer_ioctl(cmd, arg);
break;
case AWACS_TUMBLER:
case AWACS_SNAPPER:
rc = tas_mixer_ioctl(cmd, arg);
break ;
default:
rc = awacs_mixer_ioctl(cmd, arg);
}
UNLOCK();
return rc;
}
static void PMacMixerInit(void)
{
switch (awacs_revision) {
case AWACS_TUMBLER:
printk("AE-Init tumbler mixer\n");
break ;
case AWACS_SNAPPER:
printk("AE-Init snapper mixer\n");
break ;
case AWACS_DACA:
case AWACS_BURGUNDY:
break ; /* don't know yet */
case AWACS_AWACS:
case AWACS_SCREAMER:
default:
awacs_mixer_init() ;
break ;
}
}
/* Write/Read sq setup functions:
Check to see if we have enough (or any) dbdma cmd buffers for the
user's fragment settings. If not, allocate some. If this fails we will
point at the beep buffer - as an emergency provision - to stop dma tromping
on some random bit of memory (if someone lets it go anyway).
The command buffers are then set up to point to the fragment buffers
(allocated elsewhere). We need n+1 commands the last of which holds
a NOP + loop to start.
*/
static int PMacWriteSqSetup(void)
{
int i, count = 600 ;
volatile struct dbdma_cmd *cp;
LOCK();
/* stop the controller from doing any output - if it isn't already.
it _should_ be before this is called anyway */
out_le32(&awacs_txdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16);
while ((in_le32(&awacs_txdma->status) & RUN) && count
udelay(1);
#ifdef DEBUG_DMASOUND
if (count <= 0)
printk("dmasound_pmac: write sq setup: timeout waiting for dma to stop\n");
#endif
if ((write_sq.max_count + 1) > <API key>) {
kfree(awacs_tx_cmd_space);
<API key> = 0;
/* we need nbufs + 1 (for the loop) and we should request + 1
again because the DBDMA_ALIGN might pull the start up by up
to sizeof(struct dbdma_cmd) - 4.
*/
awacs_tx_cmd_space = kmalloc
((write_sq.max_count + 1 + 1) * sizeof(struct dbdma_cmd),
GFP_KERNEL);
if (awacs_tx_cmd_space == NULL) {
/* don't leave it dangling - nasty but better than a
random address */
out_le32(&awacs_txdma->cmdptr, virt_to_bus(beep_dbdma_cmd));
printk(KERN_ERR
"dmasound_pmac: can't allocate dbdma cmd buffers"
", driver disabled\n");
UNLOCK();
return -ENOMEM;
}
awacs_tx_cmds = (volatile struct dbdma_cmd *)
DBDMA_ALIGN(awacs_tx_cmd_space);
<API key> = write_sq.max_count + 1;
}
cp = awacs_tx_cmds;
memset((void *)cp, 0, (write_sq.max_count+1) * sizeof(struct dbdma_cmd));
for (i = 0; i < write_sq.max_count; ++i, ++cp) {
st_le32(&cp->phy_addr, virt_to_bus(write_sq.buffers[i]));
}
st_le16(&cp->command, DBDMA_NOP + BR_ALWAYS);
st_le32(&cp->cmd_dep, virt_to_bus(awacs_tx_cmds));
/* point the controller at the command stack - ready to go */
out_le32(&awacs_txdma->cmdptr, virt_to_bus(awacs_tx_cmds));
UNLOCK();
return 0;
}
static int PMacReadSqSetup(void)
{
int i, count = 600;
volatile struct dbdma_cmd *cp;
LOCK();
/* stop the controller from doing any input - if it isn't already.
it _should_ be before this is called anyway */
out_le32(&awacs_rxdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16);
while ((in_le32(&awacs_rxdma->status) & RUN) && count
udelay(1);
#ifdef DEBUG_DMASOUND
if (count <= 0)
printk("dmasound_pmac: read sq setup: timeout waiting for dma to stop\n");
#endif
if ((read_sq.max_count+1) > <API key> ) {
kfree(awacs_rx_cmd_space);
<API key> = 0;
/* we need nbufs + 1 (for the loop) and we should request + 1 again
because the DBDMA_ALIGN might pull the start up by up to
sizeof(struct dbdma_cmd) - 4 (assuming kmalloc aligns 32 bits).
*/
awacs_rx_cmd_space = kmalloc
((read_sq.max_count + 1 + 1) * sizeof(struct dbdma_cmd),
GFP_KERNEL);
if (awacs_rx_cmd_space == NULL) {
/* don't leave it dangling - nasty but better than a
random address */
out_le32(&awacs_rxdma->cmdptr, virt_to_bus(beep_dbdma_cmd));
printk(KERN_ERR
"dmasound_pmac: can't allocate dbdma cmd buffers"
", driver disabled\n");
UNLOCK();
return -ENOMEM;
}
awacs_rx_cmds = (volatile struct dbdma_cmd *)
DBDMA_ALIGN(awacs_rx_cmd_space);
<API key> = read_sq.max_count + 1 ;
}
cp = awacs_rx_cmds;
memset((void *)cp, 0, (read_sq.max_count+1) * sizeof(struct dbdma_cmd));
/* Set dma buffers up in a loop */
for (i = 0; i < read_sq.max_count; i++,cp++) {
st_le32(&cp->phy_addr, virt_to_bus(read_sq.buffers[i]));
st_le16(&cp->command, INPUT_MORE + INTR_ALWAYS);
st_le16(&cp->req_count, read_sq.block_size);
st_le16(&cp->xfer_status, 0);
}
/* The next two lines make the thing loop around.
*/
st_le16(&cp->command, DBDMA_NOP + BR_ALWAYS);
st_le32(&cp->cmd_dep, virt_to_bus(awacs_rx_cmds));
/* point the controller at the command stack - ready to go */
out_le32(&awacs_rxdma->cmdptr, virt_to_bus(awacs_rx_cmds));
UNLOCK();
return 0;
}
/* TODO: this needs work to guarantee that when it returns DMA has stopped
but in a more elegant way than is done here....
*/
static void PMacAbortRead(void)
{
int i;
volatile struct dbdma_cmd *cp;
LOCK();
/* give it a chance to update the output and provide the IRQ
that is expected.
*/
out_le32(&awacs_rxdma->control, ((FLUSH) << 16) + FLUSH );
cp = awacs_rx_cmds;
for (i = 0; i < read_sq.max_count; i++,cp++)
st_le16(&cp->command, DBDMA_STOP);
/*
* We should probably wait for the thing to stop before we
* release the memory.
*/
msleep(100) ; /* give it a (small) chance to act */
/* apply the sledgehammer approach - just stop it now */
out_le32(&awacs_rxdma->control, (RUN|PAUSE|FLUSH|WAKE) << 16);
UNLOCK();
}
extern char *get_afmt_string(int);
static int PMacStateInfo(char *b, size_t sp)
{
int i, len = 0;
len = sprintf(b,"HW rates: ");
switch (awacs_revision){
case AWACS_DACA:
case AWACS_BURGUNDY:
len += sprintf(b,"44100 ") ;
break ;
case AWACS_TUMBLER:
case AWACS_SNAPPER:
for (i=0; i<1; i++){
if (tas_freqs_ok[i])
len += sprintf(b+len,"%d ", tas_freqs[i]) ;
}
break ;
case AWACS_AWACS:
case AWACS_SCREAMER:
default:
for (i=0; i<8; i++){
if (awacs_freqs_ok[i])
len += sprintf(b+len,"%d ", awacs_freqs[i]) ;
}
break ;
}
len += sprintf(b+len,"s/sec\n") ;
if (len < sp) {
len += sprintf(b+len,"HW AFMTS: ");
i = AFMT_U16_BE ;
while (i) {
if (i & dmasound.mach.hardware_afmts)
len += sprintf(b+len,"%s ",
get_afmt_string(i & dmasound.mach.hardware_afmts));
i >>= 1 ;
}
len += sprintf(b+len,"\n") ;
}
return len ;
}
static SETTINGS def_hard = {
.format = AFMT_S16_BE,
.stereo = 1,
.size = 16,
.speed = 44100
} ;
static SETTINGS def_soft = {
.format = AFMT_S16_BE,
.stereo = 1,
.size = 16,
.speed = 44100
} ;
static MACHINE machPMac = {
.name = awacs_name,
.name2 = "PowerMac Built-in Sound",
.owner = THIS_MODULE,
.dma_alloc = PMacAlloc,
.dma_free = PMacFree,
.irqinit = PMacIrqInit,
#ifdef MODULE
.irqcleanup = PMacIrqCleanup,
#endif /* MODULE */
.init = PMacInit,
.silence = PMacSilence,
.setFormat = PMacSetFormat,
.setVolume = PMacSetVolume,
.play = PMacPlay,
.record = NULL, /* default to no record */
.mixer_init = PMacMixerInit,
.mixer_ioctl = PMacMixerIoctl,
.write_sq_setup = PMacWriteSqSetup,
.read_sq_setup = PMacReadSqSetup,
.state_info = PMacStateInfo,
.abort_read = PMacAbortRead,
.min_dsp_speed = 7350,
.max_dsp_speed = 44100,
.version = ((<API key><<8) + <API key>)
};
/* Check for pmac models that we care about in terms of special actions.
*/
void __init
set_model(void)
{
/* portables/lap-tops */
if (<API key>("AAPL,3400/2400") ||
<API key>("AAPL,3500")) {
is_pbook_3X00 = 1 ;
}
if (<API key>("PowerBook1,1") || /* lombard */
<API key>("AAPL,PowerBook1998")){ /* wallstreet */
is_pbook_g3 = 1 ;
return ;
}
}
/* Get the OF node that tells us about the registers, interrupts etc. to use
for sound IO.
On most machines the sound IO OF node is the 'davbus' node. On newer pmacs
with DACA (& Tumbler) the node to use is i2s-a. On much older machines i.e.
before 9500 there is no davbus node and we have to use the 'awacs' property.
In the latter case we signal this by setting the codec value - so that the
code that looks for chip properties knows how to go about it.
*/
static struct device_node* __init
get_snd_io_node(void)
{
struct device_node *np = NULL;
/* set up awacs_node for early OF which doesn't have a full set of
* properties on davbus
*/
awacs_node = find_devices("awacs");
if (awacs_node)
awacs_revision = AWACS_AWACS;
/* powermac models after 9500 (other than those which use DACA or
* Tumbler) have a node called "davbus".
*/
np = find_devices("davbus");
/*
* if we didn't find a davbus device, try 'i2s-a' since
* this seems to be what iBooks (& Tumbler) have.
*/
if (np == NULL)
np = i2s_node = find_devices("i2s-a");
/* if we didn't find this - perhaps we are on an early model
* which _only_ has an 'awacs' node
*/
if (np == NULL && awacs_node)
np = awacs_node ;
/* if we failed all these return null - this will cause the
* driver to give up...
*/
return np ;
}
/* Get the OF node that contains the info about the sound chip, inputs s-rates
etc.
This node does not exist (or contains much reduced info) on earlier machines
we have to deduce the info other ways for these.
*/
static struct device_node* __init
get_snd_info_node(struct device_node *io)
{
struct device_node *info;
info = find_devices("sound");
while (info && info->parent != io)
info = info->next;
return info;
}
/* Find out what type of codec we have.
*/
static int __init
get_codec_type(struct device_node *info)
{
/* already set if pre-davbus model and info will be NULL */
int codec = awacs_revision ;
if (info) {
/* must do awacs first to allow screamer to overide it */
if (<API key>(info, "awacs"))
codec = AWACS_AWACS ;
if (<API key>(info, "screamer"))
codec = AWACS_SCREAMER;
if (<API key>(info, "burgundy"))
codec = AWACS_BURGUNDY ;
if (<API key>(info, "daca"))
codec = AWACS_DACA;
if (<API key>(info, "tumbler"))
codec = AWACS_TUMBLER;
if (<API key>(info, "snapper"))
codec = AWACS_SNAPPER;
}
return codec ;
}
/* find out what type, if any, of expansion card we have
*/
static void __init
get_expansion_type(void)
{
if (find_devices("perch") != NULL)
has_perch = 1;
if (find_devices("pb-ziva-pc") != NULL)
has_ziva = 1;
/* need to work out how we deal with iMac SRS module */
}
/* set up frame rates.
* I suspect that these routines don't quite go about it the right way:
* - where there is more than one rate - I think that the first property
* value is the number of rates.
* TODO: check some more device trees and modify accordingly
* Set dmasound.mach.max_dsp_rate on the basis of these routines.
*/
static void __init
<API key>(unsigned int *prop, unsigned int l)
{
int i ;
if (prop) {
for (i=0; i<8; i++)
awacs_freqs_ok[i] = 0 ;
for (l /= sizeof(int); l > 0; --l) {
unsigned int r = *prop++;
/* Apple 'Fixed' format */
if (r >= 0x10000)
r >>= 16;
for (i = 0; i < 8; ++i) {
if (r == awacs_freqs[i]) {
awacs_freqs_ok[i] = 1;
break;
}
}
}
}
/* else we assume that all the rates are available */
}
static void __init
<API key>(unsigned int *prop, unsigned int l)
{
int temp[9] ;
int i = 0 ;
if (prop) {
for (l /= sizeof(int); l > 0; --l) {
unsigned int r = *prop++;
/* Apple 'Fixed' format */
if (r >= 0x10000)
r >>= 16;
temp[i] = r ;
i++ ; if(i>=9) i=8;
}
}
#ifdef DEBUG_DMASOUND
if (i > 1){
int j;
printk("dmasound_pmac: burgundy with multiple frame rates\n");
for(j=0; j<i; j++)
printk("%d ", temp[j]) ;
printk("\n") ;
}
#endif
}
static void __init
<API key>(unsigned int *prop, unsigned int l)
{
int temp[9] ;
int i = 0 ;
if (prop) {
for (l /= sizeof(int); l > 0; --l) {
unsigned int r = *prop++;
/* Apple 'Fixed' format */
if (r >= 0x10000)
r >>= 16;
temp[i] = r ;
i++ ; if(i>=9) i=8;
}
}
#ifdef DEBUG_DMASOUND
if (i > 1){
int j;
printk("dmasound_pmac: DACA with multiple frame rates\n");
for(j=0; j<i; j++)
printk("%d ", temp[j]) ;
printk("\n") ;
}
#endif
}
static void __init
init_frame_rates(unsigned int *prop, unsigned int l)
{
switch (awacs_revision) {
case AWACS_TUMBLER:
case AWACS_SNAPPER:
<API key>(prop, l);
break ;
case AWACS_DACA:
<API key>(prop, l);
break ;
case AWACS_BURGUNDY:
<API key>(prop, l);
break ;
default:
<API key>(prop, l);
break ;
}
}
/* find things/machines that can't do mac-io byteswap
*/
static void __init
set_hw_byteswap(struct device_node *io)
{
struct device_node *mio ;
unsigned int kl = 0 ;
/* if seems that Keylargo can't byte-swap */
for (mio = io->parent; mio ; mio = mio->parent) {
if (strcmp(mio->name, "mac-io") == 0) {
if (<API key>(mio, "Keylargo"))
kl = 1;
break;
}
}
hw_can_byteswap = !kl;
}
/* Allocate the resources necessary for beep generation. This cannot be (quite)
done statically (yet) because we cannot do virt_to_bus() on static vars when
the code is loaded as a module.
for the sake of saving the possibility that two allocations will incur the
overhead of two pull-ups in DBDMA_ALIGN() we allocate the 'emergency' dmdma
command here as well... even tho' it is not part of the beep process.
*/
int32_t
__init setup_beep(void)
{
/* Initialize beep stuff */
/* want one cmd buffer for beeps, and a second one for emergencies
- i.e. dbdma error conditions.
ask for three to allow for pull up in DBDMA_ALIGN().
*/
<API key> =
kmalloc((2 + 1) * sizeof(struct dbdma_cmd), GFP_KERNEL);
if(<API key> == NULL) {
printk(KERN_ERR "dmasound_pmac: no beep dbdma cmd space\n") ;
return -ENOMEM ;
}
beep_dbdma_cmd = (volatile struct dbdma_cmd *)
DBDMA_ALIGN(<API key>);
/* set up emergency dbdma cmd */
emergency_dbdma_cmd = beep_dbdma_cmd+1 ;
beep_buf = (short *) kmalloc(BEEP_BUFLEN * 4, GFP_KERNEL);
if (beep_buf == NULL) {
printk(KERN_ERR "dmasound_pmac: no memory for beep buffer\n");
kfree(<API key>) ;
return -ENOMEM ;
}
return 0 ;
}
static struct input_dev awacs_beep_dev = {
.evbit = { BIT(EV_SND) },
.sndbit = { BIT(SND_BELL) | BIT(SND_TONE) },
.event = awacs_beep_event,
.name = "dmasound beeper",
.phys = "macio/input0", /* what the heck is this?? */
.id = {
.bustype = BUS_HOST,
},
};
int __init dmasound_awacs_init(void)
{
struct device_node *io = NULL, *info = NULL;
int vol, res;
if (_machine != _MACH_Pmac)
return -ENODEV;
awacs_subframe = 0;
awacs_revision = 0;
hw_can_byteswap = 1 ; /* most can */
/* look for models we need to handle specially */
set_model() ;
/* find the OF node that tells us about the dbdma stuff
*/
io = get_snd_io_node();
if (io == NULL) {
#ifdef DEBUG_DMASOUND
printk("dmasound_pmac: couldn't find sound io OF node\n");
#endif
return -ENODEV ;
}
/* find the OF node that tells us about the sound sub-system
* this doesn't exist on pre-davbus machines (earlier than 9500)
*/
if (awacs_revision != AWACS_AWACS) { /* set for pre-davbus */
info = get_snd_info_node(io) ;
if (info == NULL){
#ifdef DEBUG_DMASOUND
printk("dmasound_pmac: couldn't find 'sound' OF node\n");
#endif
return -ENODEV ;
}
}
awacs_revision = get_codec_type(info) ;
if (awacs_revision == 0) {
#ifdef DEBUG_DMASOUND
printk("dmasound_pmac: couldn't find a Codec we can handle\n");
#endif
return -ENODEV ; /* we don't know this type of h/w */
}
/* set up perch, ziva, SRS or whatever else we have as sound
* expansion.
*/
get_expansion_type();
/* we've now got enough information to make up the audio topology.
* we will map the sound part of mac-io now so that we can probe for
* other info if necessary (early AWACS we want to read chip ids)
*/
if (io->n_addrs < 3 || io->n_intrs < 3) {
/* OK - maybe we need to use the 'awacs' node (on earlier
* machines).
*/
if (awacs_node) {
io = awacs_node ;
if (io->n_addrs < 3 || io->n_intrs < 3) {
printk("dmasound_pmac: can't use %s"
" (%d addrs, %d intrs)\n",
io->full_name, io->n_addrs, io->n_intrs);
return -ENODEV;
}
} else {
printk("dmasound_pmac: can't use %s (%d addrs, %d intrs)\n",
io->full_name, io->n_addrs, io->n_intrs);
}
}
if (!request_OF_resource(io, 0, NULL)) {
printk(KERN_ERR "dmasound: can't request IO resource !\n");
return -ENODEV;
}
if (!request_OF_resource(io, 1, " (tx dma)")) {
release_OF_resource(io, 0);
printk(KERN_ERR "dmasound: can't request TX DMA resource !\n");
return -ENODEV;
}
if (!request_OF_resource(io, 2, " (rx dma)")) {
release_OF_resource(io, 0);
release_OF_resource(io, 1);
printk(KERN_ERR "dmasound: can't request RX DMA resource !\n");
return -ENODEV;
}
/* all OF versions I've seen use this value */
if (i2s_node)
i2s = ioremap(io->addrs[0].address, 0x1000);
else
awacs = ioremap(io->addrs[0].address, 0x1000);
awacs_txdma = ioremap(io->addrs[1].address, 0x100);
awacs_rxdma = ioremap(io->addrs[2].address, 0x100);
/* first of all make sure that the chip is powered up....*/
pmac_call_feature(<API key>, io, 0, 1);
if (awacs_revision == AWACS_SCREAMER && awacs)
awacs_recalibrate();
awacs_irq = io->intrs[0].line;
awacs_tx_irq = io->intrs[1].line;
awacs_rx_irq = io->intrs[2].line;
/* Hack for legacy crap that will be killed someday */
awacs_node = io;
/* if we have an awacs or screamer - probe the chip to make
* sure we have the right revision.
*/
if (awacs_revision <= AWACS_SCREAMER){
uint32_t temp, rev, mfg ;
/* find out the awacs revision from the chip */
temp = in_le32(&awacs->codec_stat);
rev = (temp >> 12) & 0xf;
mfg = (temp >> 8) & 0xf;
#ifdef DEBUG_DMASOUND
printk("dmasound_pmac: Awacs/Screamer Codec Mfct: %d Rev %d\n", mfg, rev);
#endif
if (rev >= AWACS_SCREAMER)
awacs_revision = AWACS_SCREAMER ;
else
awacs_revision = rev ;
}
dmasound.mach = machPMac;
/* find out other bits & pieces from OF, these may be present
only on some models ... so be careful.
*/
/* in the absence of a frame rates property we will use the defaults
*/
if (info) {
unsigned int *prop, l;
sound_device_id = 0;
/* device ID appears post g3 b&w */
prop = (unsigned int *)get_property(info, "device-id", NULL);
if (prop != 0)
sound_device_id = *prop;
/* look for a property saying what sample rates
are available */
prop = (unsigned int *)get_property(info, "sample-rates", &l);
if (prop == 0)
prop = (unsigned int *) get_property
(info, "output-frame-rates", &l);
/* if it's there use it to set up frame rates */
init_frame_rates(prop, l) ;
}
if (awacs)
out_le32(&awacs->control, 0x11); /* set everything quiesent */
set_hw_byteswap(io) ; /* figure out if the h/w can do it */
#ifdef CONFIG_NVRAM
/* get default volume from nvram */
vol = ((pmac_xpram_read( 8 ) & 7 ) << 1 );
#else
vol = 0;
#endif
/* set up tracking values */
spk_vol = vol * 100 ;
spk_vol /= 7 ; /* get set value to a percentage */
spk_vol |= (spk_vol << 8) ; /* equal left & right */
line_vol = passthru_vol = spk_vol ;
/* fill regs that are shared between AWACS & Burgundy */
awacs_reg[2] = vol + (vol << 6);
awacs_reg[4] = vol + (vol << 6);
awacs_reg[5] = vol + (vol << 6); /* screamer has loopthru vol control */
awacs_reg[6] = 0; /* maybe should be vol << 3 for PCMCIA speaker */
awacs_reg[7] = 0;
awacs_reg[0] = MASK_MUX_CD;
awacs_reg[1] = MASK_LOOPTHRU;
/* FIXME: Only machines with external SRS module need MASK_PAROUT */
if (has_perch || sound_device_id == 0x5
|| /*sound_device_id == 0x8 ||*/ sound_device_id == 0xb)
awacs_reg[1] |= MASK_PAROUT0 | MASK_PAROUT1;
switch (awacs_revision) {
case AWACS_TUMBLER:
tas_register_driver(&tas3001c_hooks);
tas_init(<API key>, <API key>);
tas_dmasound_init();
tas_post_init();
break ;
case AWACS_SNAPPER:
tas_register_driver(&tas3004_hooks);
tas_init(<API key>,<API key>);
tas_dmasound_init();
tas_post_init();
break;
case AWACS_DACA:
daca_init();
break;
case AWACS_BURGUNDY:
awacs_burgundy_init();
break ;
case AWACS_SCREAMER:
case AWACS_AWACS:
default:
load_awacs();
break ;
}
/* enable/set-up external modules - when we know how */
if (has_perch)
awacs_enable_amp(100 * 0x101);
/* Reset dbdma channels */
out_le32(&awacs_txdma->control, (RUN|PAUSE|FLUSH|WAKE|DEAD) << 16);
while (in_le32(&awacs_txdma->status) & RUN)
udelay(1);
out_le32(&awacs_rxdma->control, (RUN|PAUSE|FLUSH|WAKE|DEAD) << 16);
while (in_le32(&awacs_rxdma->status) & RUN)
udelay(1);
/* Initialize beep stuff */
if ((res=setup_beep()))
return res ;
#ifdef CONFIG_PM
<API key>(&<API key>);
#endif /* CONFIG_PM */
/* Powerbooks have odd ways of enabling inputs such as
an expansion-bay CD or sound from an internal modem
or a PC-card modem. */
if (is_pbook_3X00) {
/*
* Enable CD and PC-card sound inputs.
* This is done by reading from address
* f301a000, + 0x10 to enable the expansion-bay
* CD sound input, + 0x80 to enable the PC-card
* sound input. The 0x100 enables the SCSI bus
* terminator power.
*/
latch_base = ioremap (0xf301a000, 0x1000);
in_8(latch_base + 0x190);
} else if (is_pbook_g3) {
struct device_node* mio;
macio_base = NULL;
for (mio = io->parent; mio; mio = mio->parent) {
if (strcmp(mio->name, "mac-io") == 0
&& mio->n_addrs > 0) {
macio_base = ioremap(mio->addrs[0].address, 0x40);
break;
}
}
/*
* Enable CD sound input.
* The relevant bits for writing to this byte are 0x8f.
* I haven't found out what the 0x80 bit does.
* For the 0xf bits, writing 3 or 7 enables the CD
* input, any other value disables it. Values
* 1, 3, 5, 7 enable the microphone. Values 0, 2,
* 4, 6, 8 - f enable the input from the modem.
* -- paulus.
*/
if (macio_base)
out_8(macio_base + 0x37, 3);
}
if (hw_can_byteswap)
dmasound.mach.hardware_afmts = (AFMT_S16_BE | AFMT_S16_LE) ;
else
dmasound.mach.hardware_afmts = AFMT_S16_BE ;
/* shut out chips that do output only.
* may need to extend this to machines which have no inputs - even tho'
* they use screamer - IIRC one of the powerbooks is like this.
*/
if (awacs_revision != AWACS_DACA) {
dmasound.mach.capabilities = DSP_CAP_DUPLEX ;
dmasound.mach.record = PMacRecord ;
}
dmasound.mach.default_hard = def_hard ;
dmasound.mach.default_soft = def_soft ;
switch (awacs_revision) {
case AWACS_BURGUNDY:
sprintf(awacs_name, "PowerMac Burgundy ") ;
break ;
case AWACS_DACA:
sprintf(awacs_name, "PowerMac DACA ") ;
break ;
case AWACS_TUMBLER:
sprintf(awacs_name, "PowerMac Tumbler ") ;
break ;
case AWACS_SNAPPER:
sprintf(awacs_name, "PowerMac Snapper ") ;
break ;
case AWACS_SCREAMER:
sprintf(awacs_name, "PowerMac Screamer ") ;
break ;
case AWACS_AWACS:
default:
sprintf(awacs_name, "PowerMac AWACS rev %d ", awacs_revision) ;
break ;
}
/*
* XXX: we should handle errors here, but that would mean
* rewriting the whole init code. later..
*/
<API key>(&awacs_beep_dev);
return dmasound_init();
}
static void __exit <API key>(void)
{
<API key>(&awacs_beep_dev);
switch (awacs_revision) {
case AWACS_TUMBLER:
case AWACS_SNAPPER:
<API key>();
tas_cleanup();
break ;
case AWACS_DACA:
daca_cleanup();
break;
}
dmasound_deinit();
}
MODULE_DESCRIPTION("PowerMac built-in audio driver.");
MODULE_LICENSE("GPL");
module_init(dmasound_awacs_init);
module_exit(<API key>);
|
// boost-libs variant/test/test8.cpp header file
// Eric Friedman, Itay Maman
#include "boost/test/minimal.hpp"
#include "boost/variant.hpp"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using namespace boost;
typedef variant<float, std::string, int, std::vector<std::string> > t_var1;
struct int_sum : static_visitor<>
{
int_sum() : result_(0) { }
void operator()(int t)
{
result_ += t;
}
result_type operator()(float ) { }
result_type operator()(const std::string& ) { }
result_type operator()(const std::vector<std::string>& ) { }
int result_;
};
template <typename T, typename Variant>
T& check_pass(Variant& v, T value)
{
BOOST_CHECK(get<T>(&v));
try
{
T& r = get<T>(v);
BOOST_CHECK(r == value);
return r;
}
catch(boost::bad_get&)
{
throw; // must never reach
}
}
template <typename T, typename Variant>
void check_fail(Variant& v)
{
BOOST_CHECK(!relaxed_get<T>(&v));
try
{
T& r = relaxed_get<T>(v);
(void)r; // suppress warning about r not being used
BOOST_CHECK(false && &r); // should never reach
}
catch(const boost::bad_get& e)
{
BOOST_CHECK(!!e.what()); // make sure that what() is const qualified and returnes something
}
}
int test_main(int , char* [])
{
int_sum acc;
t_var1 v1 = 800;
// check get on non-const variant
{
int& r1 = check_pass<int>(v1, 800);
const int& cr1 = check_pass<const int>(v1, 800);
check_fail<float>(v1);
check_fail<const float>(v1);
check_fail<short>(v1);
check_fail<const short>(v1);
apply_visitor(acc, v1);
BOOST_CHECK(acc.result_ == 800);
r1 = 920; // NOTE: modifies content of v1
apply_visitor(acc, v1);
BOOST_CHECK(cr1 == 920);
BOOST_CHECK(acc.result_ == 800 + 920);
}
// check const correctness:
{
const t_var1& c = v1;
check_pass<const int>(c, 920);
check_fail<const float>(c);
check_fail<const short>(c);
}
return boost::exit_success;
}
|
#include "iaf_psc_alpha_presc.h"
#include "exceptions.h"
#include "network.h"
#include "dict.h"
#include "integerdatum.h"
#include "doubledatum.h"
#include "dictutils.h"
#include "numerics.h"
#include "<API key>.h"
#include <limits>
nest::RecordablesMap<nest::iaf_psc_alpha_presc> nest::iaf_psc_alpha_presc::recordablesMap_;
namespace nest
{
/*
* Override the create() method with one call to RecordablesMap::insert_()
* for each quantity to be recorded.
*/
template <>
void RecordablesMap<iaf_psc_alpha_presc>::create()
{
// use standard names whereever you can for consistency!
insert_(names::V_m, &iaf_psc_alpha_presc::get_V_m_);
}
}
nest::iaf_psc_alpha_presc::Parameters_::Parameters_()
: tau_m_ ( 10.0 ),
tau_syn_( 2.0 ),
c_m_ (250.0 ),
t_ref_ ( 2.0 ),
E_L_ (-70.0 ),
I_e_ ( 0.0 ),
U_th_ (-55.0-E_L_), // mV, rel to E_L_
U_min_ (-std::numeric_limits<double_t>::infinity()),
U_reset_(-70.0-E_L_),
Interpol_(iaf_psc_alpha_presc::LINEAR)
{}
nest::iaf_psc_alpha_presc::State_::State_()
: y0_(0.0),
y1_(0.0),
y2_(0.0),
y3_(0.0),
r_(0),
last_spike_step_(-1),
last_spike_offset_(0.0)
{}
void nest::iaf_psc_alpha_presc::Parameters_::get(DictionaryDatum &d) const
{
def<double>(d, names::E_L, E_L_);
def<double>(d, names::I_e, I_e_);
def<double>(d, names::V_th, U_th_+E_L_);
def<double>(d, names::V_min, U_min_+E_L_);
def<double>(d, names::V_reset, U_reset_+E_L_);
def<double>(d, names::C_m, c_m_);
def<double>(d, names::tau_m, tau_m_);
def<double>(d, names::tau_syn, tau_syn_);
def<double>(d, names::t_ref, t_ref_);
def<long>(d, names::Interpol_Order, Interpol_);
}
double nest::iaf_psc_alpha_presc::Parameters_::set(const DictionaryDatum& d)
{
// if E_L_ is changed, we need to adjust all variables defined relative to E_L_
const double ELold = E_L_;
updateValue<double>(d, names::E_L, E_L_);
const double delta_EL = E_L_ - ELold;
updateValue<double>(d, names::tau_m, tau_m_);
updateValue<double>(d, names::tau_syn, tau_syn_);
updateValue<double>(d, names::C_m, c_m_);
updateValue<double>(d, names::t_ref, t_ref_);
updateValue<double>(d, names::I_e, I_e_);
if (updateValue<double>(d, names::V_th, U_th_))
U_th_ -= E_L_;
else
U_th_ -= delta_EL;
if (updateValue<double>(d, names::V_min, U_min_))
U_min_ -= E_L_;
else
U_min_ -= delta_EL;
if (updateValue<double>(d, names::V_reset, U_reset_))
U_reset_ -= E_L_;
else
U_reset_ -= delta_EL;
long_t tmp;
if ( updateValue<long_t>(d, names::Interpol_Order, tmp) )
{
if ( NO_INTERPOL <= tmp && tmp < END_INTERP_ORDER )
Interpol_ = static_cast<interpOrder>(tmp);
else
throw BadProperty("Invalid interpolation order. "
"Valid orders are 0, 1, 2, 3.");
}
if ( U_reset_ >= U_th_ )
throw BadProperty("Reset potential must be smaller than threshold.");
if ( U_reset_ < U_min_ )
throw BadProperty("Reset potential must be greater equal minimum potential.");
if ( c_m_ <= 0 )
throw BadProperty("Capacitance must be strictly positive.");
if ( t_ref_ < 0 )
throw BadProperty("Refractory time must not be negative.");
if ( tau_m_ <= 0 || tau_syn_ <= 0 )
throw BadProperty("All time constants must be strictly positive.");
if ( tau_m_ == tau_syn_ )
throw BadProperty("Membrane and synapse time constant(s) must differ."
"See note in documentation.");
return delta_EL;
}
void nest::iaf_psc_alpha_presc::State_::get(DictionaryDatum &d,
const Parameters_& p) const
{
def<double>(d, names::V_m, y3_ + p.E_L_); // Membrane potential
def<double>(d, names::t_spike, Time(Time::step(last_spike_step_)).get_ms());
def<double>(d, names::offset, last_spike_offset_);
}
void nest::iaf_psc_alpha_presc::State_::set(const DictionaryDatum& d, const Parameters_& p, double delta_EL)
{
if ( updateValue<double>(d, names::V_m, y3_) )
y3_ -= p.E_L_;
else
y3_ -= delta_EL;
}
nest::iaf_psc_alpha_presc::Buffers_::Buffers_(iaf_psc_alpha_presc& n)
: logger_(n)
{}
nest::iaf_psc_alpha_presc::Buffers_::Buffers_(const Buffers_&, iaf_psc_alpha_presc& n)
: logger_(n)
{}
nest::iaf_psc_alpha_presc::iaf_psc_alpha_presc()
: Node(),
P_(),
S_(),
B_(*this)
{
recordablesMap_.create();
}
nest::iaf_psc_alpha_presc::iaf_psc_alpha_presc(const iaf_psc_alpha_presc& n)
: Node(n),
P_(n.P_),
S_(n.S_),
B_(n.B_, *this)
{}
void nest::iaf_psc_alpha_presc::init_state_(const Node& proto)
{
const iaf_psc_alpha_presc& pr = downcast<iaf_psc_alpha_presc>(proto);
S_ = pr.S_;
}
void nest::iaf_psc_alpha_presc::init_buffers_()
{
B_.spike_y1_.clear(); // includes resize
B_.spike_y2_.clear(); // includes resize
B_.spike_y3_.clear(); // includes resize
B_.currents_.clear(); // includes resize
B_.logger_.reset();
}
void nest::iaf_psc_alpha_presc::calibrate()
{
B_.logger_.init();
V_.h_ms_ = Time::get_resolution().get_ms();
V_.PSCInitialValue_ = 1.0 * numerics::e / P_.tau_syn_;
V_.gamma_ = 1/P_.c_m_ / ( 1/P_.tau_syn_ - 1/P_.tau_m_ );
V_.gamma_sq_ = 1/P_.c_m_ / ( ( 1/P_.tau_syn_ - 1/P_.tau_m_ ) * ( 1/P_.tau_syn_ - 1/P_.tau_m_ ) );
// pre-compute matrix for full time step
V_.expm1_tau_m_ = numerics::expm1(-V_.h_ms_/P_.tau_m_);
V_.expm1_tau_syn_ = numerics::expm1(-V_.h_ms_/P_.tau_syn_);
V_.P30_ = -P_.tau_m_ / P_.c_m_ * V_.expm1_tau_m_;
V_.P31_ = V_.gamma_sq_ * V_.expm1_tau_m_ - V_.gamma_sq_ * V_.expm1_tau_syn_
- V_.h_ms_ * V_.gamma_ * V_.expm1_tau_syn_ - V_.h_ms_ * V_.gamma_;
V_.P32_ = V_.gamma_ * V_.expm1_tau_m_ - V_.gamma_ * V_.expm1_tau_syn_;
// t_ref_ is the refractory period in ms
// refractory_steps_ is the duration of the refractory period in whole
// steps, rounded down
V_.refractory_steps_ = Time(Time::ms(P_.t_ref_)).get_steps();
assert(V_.refractory_steps_ >= 0); // since t_ref_ >= 0, this can only fail in error
}
void nest::iaf_psc_alpha_presc::update(Time const & origin,
const long_t from, const long_t to)
{
assert(to >= 0);
assert(static_cast<delay>(from) < Scheduler::get_min_delay());
assert(from < to);
/* Neurons may have been initialized to superthreshold potentials.
We need to check for this here and issue spikes at the beginning of
the interval.
*/
if ( S_.y3_ >= P_.U_th_ )
{
set_spiketime(Time::step(origin.get_steps() + from + 1));
S_.last_spike_offset_ = V_.h_ms_ * (1-std::numeric_limits<double_t>::epsilon());
// reset neuron and make it refractory
S_.y3_ = P_.U_reset_;
S_.r_ = V_.refractory_steps_;
// send spike
SpikeEvent se;
se.set_offset(S_.last_spike_offset_);
network()->send(*this, se, from);
}
for ( long_t lag = from ; lag < to ; ++lag )
{
// time at start of update step
const long_t T = origin.get_steps() + lag;
// save state at beginning of interval for spike-time interpolation
V_.y0_before_ = S_.y0_;
V_.y1_before_ = S_.y1_;
V_.y2_before_ = S_.y2_;
V_.y3_before_ = S_.y3_;
/* obtain input to y3_
We need to collect this value even while the neuron is refractory,
since we need to clear any spikes that have come in from the
ring buffer.
*/
const double_t dy3 = B_.spike_y3_.get_value(lag);
if ( S_.r_ == 0 )
{
// neuron is not refractory
S_.y3_ = V_.P30_ * (P_.I_e_+S_.y0_) + V_.P31_*S_.y1_ + V_.P32_*S_.y2_ + V_.expm1_tau_m_*S_.y3_ + S_.y3_;
S_.y3_ += dy3; // add input
// enforce lower bound
S_.y3_ = ( S_.y3_< P_.U_min_ ? P_.U_min_ : S_.y3_);
}
else if ( S_.r_ == 1 )
{
// neuron returns from refractoriness during interval
S_.r_ = 0;
// Iterate third component (membrane pot) from end of
// refractory period to end of interval. As first-order
// approximation, add a proportion of the effect of synaptic
// input during the interval to membrane pot. The proportion
// is given by the part of the interval after the end of the
// refractory period.
S_.y3_ = P_.U_reset_ + // try fix 070623, md
update_y3_delta_() + dy3 - dy3 * (1 - S_.last_spike_offset_/V_.h_ms_);
// enforce lower bound
S_.y3_ = ( S_.y3_< P_.U_min_ ? P_.U_min_ : S_.y3_);
}
else
{
// neuron is refractory
// y3_ remains unchanged at 0.0
--S_.r_;
}
// update synaptic currents
S_.y2_ =V_. expm1_tau_syn_*V_.h_ms_*S_.y1_ + V_.expm1_tau_syn_*S_.y2_ + V_.h_ms_*S_.y1_ + S_.y2_;
S_.y1_ = V_.expm1_tau_syn_*S_.y1_ + S_.y1_;
// add synaptic inputs from the ring buffer
// this must happen BEFORE threshold-crossing interpolation,
// since synaptic inputs occured during the interval
S_.y1_ += B_.spike_y1_.get_value(lag);
S_.y2_ += B_.spike_y2_.get_value(lag);
//neuron spikes
if ( S_.y3_ >= P_.U_th_ )
{
// compute spike time
set_spiketime(Time::step(T+1));
// The time for the threshpassing
S_.last_spike_offset_ = V_.h_ms_ - thresh_find_(V_.h_ms_);
// reset AFTER spike-time interpolation
S_.y3_ = P_.U_reset_;
S_.r_ = V_.refractory_steps_;
// sent event
SpikeEvent se;
se.set_offset(S_.last_spike_offset_);
network()->send(*this, se, lag);
}
// Set new input current. The current change occurs at the
// end of the interval and thus must come AFTER the threshold-
// crossing interpolation
S_.y0_ = B_.currents_.get_value(lag);
// logging
B_.logger_.record_data(origin.get_steps()+lag);
} // from lag = from ...
}
//function handles exact spike times
void nest::iaf_psc_alpha_presc::handle(SpikeEvent & e)
{
assert(e.get_delay() > 0 );
const long_t Tdeliver = e.<API key>(network()->get_slice_origin());
const double_t spike_weight = V_.PSCInitialValue_ * e.get_weight() * e.get_multiplicity();
const double_t dt = e.get_offset();
// Building the new matrix for the offset of the spike
// NOTE: We do not use get matrix, but compute only those
// components we actually need for spike registration
const double_t ps_e_TauSyn = numerics::expm1(-dt/P_.tau_syn_); // needed in any case
const double_t ps_e_Tau = numerics::expm1(-dt/P_.tau_m_);
const double_t ps_P31 = V_.gamma_sq_ * ps_e_Tau - V_.gamma_sq_ * ps_e_TauSyn
- dt * V_.gamma_ * ps_e_TauSyn - dt * V_.gamma_;
B_.spike_y1_.add_value(Tdeliver, spike_weight*ps_e_TauSyn + spike_weight);
B_.spike_y2_.add_value(Tdeliver, spike_weight*dt*ps_e_TauSyn + spike_weight*dt);
B_.spike_y3_.add_value(Tdeliver, spike_weight*ps_P31);
}
void nest::iaf_psc_alpha_presc::handle(CurrentEvent& e)
{
assert(e.get_delay() > 0);
const double_t c=e.get_current();
const double_t w=e.get_weight();
// add weighted current; HEP 2002-10-04
B_.currents_.add_value(e.<API key>(network()->get_slice_origin()),
w * c);
}
void nest::iaf_psc_alpha_presc::handle(DataLoggingRequest& e)
{
B_.logger_.handle(e);
}
inline
void nest::iaf_psc_alpha_presc::set_spiketime(Time const & now)
{
S_.last_spike_step_ = now.get_steps();
}
inline
nest::Time nest::iaf_psc_alpha_presc::get_spiketime() const
{
return Time::step(S_.last_spike_step_);
}
nest::double_t nest::iaf_psc_alpha_presc::update_y3_delta_() const
{
/* We need to proceed in two steps:
1. Update the synaptic currents as far as <API key>, when the refractory
period ends. y3_ is clamped to 0 during this time.
2. Update y3_ from t_th to the end of the interval. The synaptic
currents need not be updated during this time, since they are
anyways updated for the entire interval outside.
Instead of calling get_matrix(), we compute only those components
we actually need locally.
*/
// update synaptic currents
const double t_th = V_.h_ms_ - S_.last_spike_offset_;
double_t ps_e_TauSyn = numerics::expm1(-t_th/P_.tau_syn_);
//ps_y2_ = ps_P21_*y1_before_ + ps_P22_* y2_before_;
const double ps_y2 = t_th * ps_e_TauSyn * V_.y1_before_
+ ps_e_TauSyn * V_.y2_before_ + t_th * V_.y1_before_ + V_.y2_before_ ;
//ps_y1_ = y1_before_*ps_P11_;
const double ps_y1 = ps_e_TauSyn * V_.y1_before_ + V_.y1_before_ ;
// update y3_ over remaineder of interval
const double_t dt = S_.last_spike_offset_;
ps_e_TauSyn = numerics::expm1(-dt / P_.tau_syn_);
const double_t ps_e_Tau = numerics::expm1(-dt/P_.tau_m_);
const double_t ps_P30 = - P_.tau_m_ / P_.c_m_ * ps_e_Tau;
const double_t ps_P31 = V_.gamma_sq_ * ps_e_Tau - V_.gamma_sq_ * ps_e_TauSyn
- dt*V_.gamma_*ps_e_TauSyn - dt*V_.gamma_;
const double_t ps_P32 = V_.gamma_*ps_e_Tau - V_.gamma_* ps_e_TauSyn;
// y3_ == 0.0 at beginning of sub-step
return ps_P30 * (P_.I_e_+V_.y0_before_) + ps_P31 * ps_y1 + ps_P32 * ps_y2;
}
// finds threshpassing
inline
nest::double_t nest::iaf_psc_alpha_presc::thresh_find_(double_t const dt) const
{
switch (P_.Interpol_) {
case NO_INTERPOL: return dt;
case LINEAR : return thresh_find1_(dt);
case QUADRATIC : return thresh_find2_(dt);
case CUBIC : return thresh_find3_(dt);
default:
network()->message(SLIInterpreter::M_ERROR, "iaf_psc_alpha_presc::thresh_find_()",
"Invalid <API key> model error.");
throw BadProperty();
}
return 0;
}
// finds threshpassing via linear interpolation
nest::double_t nest::iaf_psc_alpha_presc::thresh_find1_(double_t const dt) const
{
double_t tau = ( P_.U_th_ - V_.y3_before_ ) * dt / ( S_.y3_ - V_.y3_before_ );
return tau;
}
// finds threshpassing via quadratic interpolation
nest::double_t nest::iaf_psc_alpha_presc::thresh_find2_(double_t const dt) const
{
const double_t h_sq = dt * dt;
const double_t derivative = - V_.y3_before_/P_.tau_m_ + (P_.I_e_ + V_.y0_before_ + V_.y2_before_)/P_.c_m_;
const double_t a = (-V_.y3_before_/h_sq) + (S_.y3_/h_sq) - (derivative/dt);
const double_t b = derivative;
const double_t c = V_.y3_before_;
const double_t sqr_ = std::sqrt(b*b - 4*a*c + 4*a*P_.U_th_);
const double_t tau1 = (-b + sqr_) / (2*a);
const double_t tau2 = (- b - sqr_) / (2*a);
if (tau1 >= 0)
return tau1;
else if (tau2 >= 0)
return tau2;
else
return thresh_find1_(dt);
}
nest::double_t nest::iaf_psc_alpha_presc::thresh_find3_(double_t const dt) const
{
const double_t h_ms_=dt;
const double_t h_sq = h_ms_*h_ms_;
const double_t h_cb = h_sq*h_ms_;
const double_t deriv_t1 = - V_.y3_before_/P_.tau_m_ + (P_.I_e_ + V_.y0_before_ + V_.y2_before_)/P_.c_m_;
const double_t deriv_t2 = - S_.y3_/P_.tau_m_ + (P_.I_e_ + S_.y0_ + S_.y2_)/P_.c_m_;
const double_t w3_ = (2 * V_.y3_before_ / h_cb) - (2 * S_.y3_ / h_cb)
+ ( deriv_t1 / h_sq) + ( deriv_t2 / h_sq) ;
const double_t w2_ = - (3 * V_.y3_before_ / h_sq) + (3 * S_.y3_ / h_sq)
- ( 2 * deriv_t1 / h_ms_) - ( deriv_t2 / h_ms_) ;
const double_t w1_ = deriv_t1;
const double_t w0_ = V_.y3_before_;
//normal form : x^3 + r*x^2 + s*x + t with coefficients : r, s, t
const double_t r = w2_ / w3_;
const double_t s = w1_ / w3_;
const double_t t = (w0_ - P_.U_th_) / w3_;
const double_t r_sq= r*r;
//substitution y = x + r/3 : y^3 + p*y + q == 0
const double_t p = - r_sq / 3 + s;
const double_t q = 2 * ( r_sq * r ) / 27 - r * s / 3 + t;
//discriminante
const double_t D = std::pow( (p/3), 3) + std::pow( (q/2), 2);
double_t tau1;
double_t tau2;
double_t tau3;
if(D<0){
const double_t roh = std::sqrt( -(p*p*p)/ 27 );
const double_t phi = std::acos( -q/ (2*roh) );
const double_t a = 2 * std::pow(roh, (1.0/3.0));
tau1 = (a * std::cos( phi/3 )) - r/3;
tau2 = (a * std::cos( phi/3 + 2* numerics::pi/3 )) - r/3;
tau3 = (a * std::cos( phi/3 + 4* numerics::pi/3 )) - r/3;
}
else{
const double_t sgnq = (q >= 0 ? 1 : -1);
const double_t u = -sgnq * std::pow(std::fabs(q)/2.0 + std::sqrt(D), 1.0/3.0);
const double_t v = - p/(3*u);
tau1= (u+v) - r/3;
if (tau1 >= 0) {
return tau1;
}
else {
return thresh_find2_(dt);
}
}
//set tau to the smallest root above 0
double tau = (tau1 >= 0) ? tau1 : 2*h_ms_;
if ((tau2 >=0) && (tau2 < tau)) tau = tau2;
if ((tau3 >=0) && (tau3 < tau)) tau = tau3;
return (tau <= h_ms_) ? tau : thresh_find2_(dt);
}
|
#include "vcardupdate.h"
#include "tag.h"
namespace gloox
{
VCardUpdate::VCardUpdate()
: StanzaExtension( ExtVCardUpdate ),
m_notReady( true ), m_noImage( true ), m_valid( true )
{
}
VCardUpdate::VCardUpdate( const std::string& hash )
: StanzaExtension( ExtVCardUpdate ),
m_hash( hash ), m_notReady( false ), m_noImage( false ), m_valid( true )
{
if( m_hash.empty() )
{
m_noImage = true;
m_valid = false;
}
}
VCardUpdate::VCardUpdate( const Tag* tag )
: StanzaExtension( ExtVCardUpdate ),
m_notReady( true ), m_noImage( true ), m_valid( false )
{
if( tag && tag->name() == "x" && tag->hasAttribute( XMLNS, <API key> ) )
{
m_valid = true;
if( tag->hasChild( "photo" ) )
{
m_notReady = false;
m_hash = tag->findChild( "photo" )->cdata();
if( !m_hash.empty() )
m_noImage = false;
}
}
}
VCardUpdate::~VCardUpdate()
{
}
const std::string& VCardUpdate::filterString() const
{
static const std::string filter = "/presence/x[@xmlns='" + <API key> + "']";
return filter;
}
Tag* VCardUpdate::tag() const
{
if( !m_valid )
return 0;
Tag* x = new Tag( "x", XMLNS, <API key> );
if( !m_notReady )
{
Tag* p = new Tag( x, "photo" );
if( !m_noImage )
p->setCData( m_hash );
}
return x;
}
}
|
<?php
require_once('../../config.inc.php');
require_once('common.php');
require_once('charts.inc.php');
testlinkInitPage($db,true,false,"checkRights");
$cfg = new stdClass();
$cfg->scale = new stdClass();
$chart_cfg = config_get('results');
$chart_cfg = $chart_cfg['charts']['dimensions']['keywordBarChart'];
$cfg->chartTitle = lang_get($chart_cfg['chartTitle']);
$cfg->XSize = $chart_cfg['XSize'];
$cfg->YSize = $chart_cfg['YSize'];
$cfg->beginX = $chart_cfg['beginX'];
$cfg->beginY = $chart_cfg['beginY'];
$cfg->scale->legendXAngle = $chart_cfg['legendXAngle'];
$args = init_args();
$info = getDataAndScale($db,$args);
createChart($info,$cfg);
/*
function: getDataAndScale
args: dbHandler
returns: object
*/
function getDataAndScale(&$dbHandler,$argsObj)
{
$resultsCfg = config_get('results');
$obj = new stdClass();
$items = array();
$totals = null;
$metricsMgr = new tlTestPlanMetrics($dbHandler);
$dummy = $metricsMgr-><API key>($argsObj->tplan_id);
$obj->canDraw = false;
if( !is_null($dummy) )
{
$dataSet = $dummy->info;
$obj->canDraw = !is_null($dataSet) && (count($dataSet) > 0);
}
if($obj->canDraw)
{
// Process to enable alphabetical order
foreach($dataSet as $keyword_id => $elem)
{
$item_descr[$elem['name']] = $keyword_id;
}
ksort($item_descr);
foreach($item_descr as $name => $keyword_id)
{
$items[] = htmlspecialchars($name);
foreach($dataSet[$keyword_id]['details'] as $status => $value)
{
$totals[$status][] = $value['qty'];
}
}
}
$obj->xAxis = new stdClass();
$obj->xAxis->values = $items;
$obj->xAxis->serieName = 'Serie8';
$obj->series_color = null;
$obj->scale = new stdClass();
$obj->scale->maxY = 0;
$obj->scale->minY = 0;
$obj->scale->divisions = 0;
if(!is_null($totals))
{
// in this array position we will find minimun value after an rsort
$minPos = count($dataSet)-1;
$obj->scale->maxY = 0;
$obj->scale->minY = 0;
foreach($totals as $status => $values)
{
$obj->chart_data[] = $values;
$obj->series_label[] = lang_get($resultsCfg['status_label'][$status]);
if( isset($resultsCfg['charts']['status_colour'][$status]) )
{
$obj->series_color[] = $resultsCfg['charts']['status_colour'][$status];
}
}
}
return $obj;
}
function init_args()
{
$argsObj = new stdClass();
// $argsObj->tproject_id = intval($_REQUEST['tproject_id']);
$argsObj->tplan_id = intval($_REQUEST['tplan_id']);
if( isset($_REQUEST['debug']) )
{
$argsObj->debug = 'yes';
}
return $argsObj;
}
function checkRights(&$db,&$user)
{
return $user->hasRight($db,'testplan_metrics');
}
?>
|
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <asm/mach-types.h>
#include <mach/camera.h>
#include <mach/msm_bus_board.h>
#include <mach/gpiomux.h>
#include <mach/socinfo.h>
#include "../devices.h"
#include "../board-8064.h"
#ifdef CONFIG_MSM_CAMERA
static struct gpiomux_setting cam_settings[] = {
{
.func = GPIOMUX_FUNC_GPIO, /*suspend*/
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_DOWN,
},
{
.func = GPIOMUX_FUNC_1, /*active 1*/
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
},
{
.func = GPIOMUX_FUNC_GPIO, /*active 2*/
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
},
{
#ifdef <API key>
//config GPIO_2's fuction 4:CAM_MCLK2 as CAM_MCLK for front camera now
.func = GPIOMUX_FUNC_4, /*active 3*/
#else
.func = GPIOMUX_FUNC_2, /*active 3*/
#endif
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
},
{
.func = GPIOMUX_FUNC_5, /*active 4*/
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_UP,
},
{
.func = GPIOMUX_FUNC_6, /*active 5*/
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_UP,
},
{
.func = GPIOMUX_FUNC_2, /*active 6*/
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_UP,
},
{
.func = GPIOMUX_FUNC_3, /*active 7*/
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_UP,
},
{
.func = GPIOMUX_FUNC_GPIO, /*i2c suspend*/
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_KEEPER,
},
{
.func = GPIOMUX_FUNC_9, /*active 9*/
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
},
{
.func = GPIOMUX_FUNC_A, /*active 10*/
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
},
{
.func = GPIOMUX_FUNC_6, /*active 11*/
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
},
{
.func = GPIOMUX_FUNC_4, /*active 12*/
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
},
};
static struct msm_gpiomux_config <API key>[] = {
{
.gpio = 1,
.settings = {
[GPIOMUX_ACTIVE] = &cam_settings[2],
[GPIOMUX_SUSPENDED] = &cam_settings[0],
},
},
{
.gpio = 2,
.settings = {
#ifdef <API key>
[GPIOMUX_ACTIVE] = &cam_settings[3],
#else
[GPIOMUX_ACTIVE] = &cam_settings[12],
#endif
[GPIOMUX_SUSPENDED] = &cam_settings[0],
},
},
{
.gpio = 3,
.settings = {
[GPIOMUX_ACTIVE] = &cam_settings[2],
[GPIOMUX_SUSPENDED] = &cam_settings[0],
},
},
#ifdef <API key>
//GPIO4 is configed as "BOOT_CONFIG" now, the original config of
//GPIO4 is CAM_MCLK1 for front camera, so remove this config here
#else
{
.gpio = 4,
.settings = {
[GPIOMUX_ACTIVE] = &cam_settings[3],
[GPIOMUX_SUSPENDED] = &cam_settings[0],
},
},
#endif
{
.gpio = 5,
.settings = {
[GPIOMUX_ACTIVE] = &cam_settings[1],
[GPIOMUX_SUSPENDED] = &cam_settings[0],
},
},
{
.gpio = 34,
.settings = {
[GPIOMUX_ACTIVE] = &cam_settings[2],
[GPIOMUX_SUSPENDED] = &cam_settings[0],
},
},
{
.gpio = 107,
.settings = {
[GPIOMUX_ACTIVE] = &cam_settings[2],
[GPIOMUX_SUSPENDED] = &cam_settings[0],
},
},
{
.gpio = 10,
.settings = {
[GPIOMUX_ACTIVE] = &cam_settings[9],
[GPIOMUX_SUSPENDED] = &cam_settings[8],
},
},
{
.gpio = 11,
.settings = {
[GPIOMUX_ACTIVE] = &cam_settings[10],
[GPIOMUX_SUSPENDED] = &cam_settings[8],
},
},
#ifdef <API key>
//GPIO12-13 are not for camera related use
#else
{
.gpio = 12,
.settings = {
[GPIOMUX_ACTIVE] = &cam_settings[11],
[GPIOMUX_SUSPENDED] = &cam_settings[8],
},
},
{
.gpio = 13,
.settings = {
[GPIOMUX_ACTIVE] = &cam_settings[11],
[GPIOMUX_SUSPENDED] = &cam_settings[8],
},
},
#endif
};
#ifdef <API key>
#define <API key> 12
#else
#define <API key> 3
#endif
#define <API key> 1
static struct <API key> msm_flash_src = {
.flash_sr_type = <API key>,
._fsrc.ext_driver_src.led_en = <API key>,
._fsrc.ext_driver_src.led_flash_en = <API key>,
#ifdef <API key>
._fsrc.ext_driver_src.flash_id = <API key>,
#else
._fsrc.ext_driver_src.flash_id = <API key>,
#endif
};
static struct msm_gpiomux_config <API key>[] = {
};
static struct msm_bus_vectors cam_init_vectors[] = {
{
.src = MSM_BUS_MASTER_VFE,
.dst = <API key>,
.ab = 0,
.ib = 0,
},
{
.src = MSM_BUS_MASTER_VPE,
.dst = <API key>,
.ab = 0,
.ib = 0,
},
{
.src = <API key>,
.dst = <API key>,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors cam_preview_vectors[] = {
{
.src = MSM_BUS_MASTER_VFE,
.dst = <API key>,
.ab = 27648000,
.ib = 2656000000UL,
},
{
.src = MSM_BUS_MASTER_VPE,
.dst = <API key>,
.ab = 0,
.ib = 0,
},
{
.src = <API key>,
.dst = <API key>,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors cam_video_vectors[] = {
{
.src = MSM_BUS_MASTER_VFE,
.dst = <API key>,
.ab = 600000000,
.ib = 2656000000UL,
},
{
.src = MSM_BUS_MASTER_VPE,
.dst = <API key>,
.ab = 206807040,
.ib = 488816640,
},
{
.src = <API key>,
.dst = <API key>,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors <API key>[] = {
{
.src = MSM_BUS_MASTER_VFE,
.dst = <API key>,
.ab = 600000000,
.ib = 2656000000UL,
},
{
.src = MSM_BUS_MASTER_VPE,
.dst = <API key>,
.ab = 0,
.ib = 0,
},
{
.src = <API key>,
.dst = <API key>,
.ab = 540000000,
.ib = 1350000000,
},
};
static struct msm_bus_vectors cam_zsl_vectors[] = {
{
.src = MSM_BUS_MASTER_VFE,
.dst = <API key>,
.ab = 600000000,
.ib = 2656000000UL,
},
{
.src = MSM_BUS_MASTER_VPE,
.dst = <API key>,
.ab = 0,
.ib = 0,
},
{
.src = <API key>,
.dst = <API key>,
.ab = 540000000,
.ib = 1350000000,
},
};
static struct msm_bus_vectors <API key>[] = {
{
.src = MSM_BUS_MASTER_VFE,
.dst = <API key>,
.ab = 348192000,
.ib = 617103360,
},
{
.src = MSM_BUS_MASTER_VPE,
.dst = <API key>,
.ab = 206807040,
.ib = 488816640,
},
{
.src = <API key>,
.dst = <API key>,
.ab = 540000000,
.ib = 1350000000,
},
};
static struct msm_bus_vectors cam_dual_vectors[] = {
{
.src = MSM_BUS_MASTER_VFE,
.dst = <API key>,
.ab = 600000000,
.ib = 2656000000UL,
},
{
.src = MSM_BUS_MASTER_VPE,
.dst = <API key>,
.ab = 206807040,
.ib = 488816640,
},
{
.src = <API key>,
.dst = <API key>,
.ab = 540000000,
.ib = 1350000000,
},
{
.src = <API key>,
.dst = <API key>,
.ab = 43200000,
.ib = 69120000,
},
{
.src = MSM_BUS_MASTER_VFE,
.dst = <API key>,
.ab = 43200000,
.ib = 69120000,
},
};
static struct msm_bus_vectors <API key>[] = {
{
.src = MSM_BUS_MASTER_VFE,
.dst = <API key>,
.ab = 1451520,
.ib = 3870720,
},
{
.src = MSM_BUS_MASTER_VPE,
.dst = <API key>,
.ab = 0,
.ib = 0,
},
{
.src = <API key>,
.dst = <API key>,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_paths <API key>[] = {
{
ARRAY_SIZE(cam_init_vectors),
cam_init_vectors,
},
{
ARRAY_SIZE(cam_preview_vectors),
cam_preview_vectors,
},
{
ARRAY_SIZE(cam_video_vectors),
cam_video_vectors,
},
{
ARRAY_SIZE(<API key>),
<API key>,
},
{
ARRAY_SIZE(cam_zsl_vectors),
cam_zsl_vectors,
},
{
ARRAY_SIZE(<API key>),
<API key>,
},
{
ARRAY_SIZE(cam_dual_vectors),
cam_dual_vectors,
},
{
ARRAY_SIZE(<API key>),
<API key>,
},
};
static struct msm_bus_scale_pdata <API key> = {
<API key>,
ARRAY_SIZE(<API key>),
.name = "msm_camera",
};
static struct <API key> <API key>[] = {
{
.csid_core = 0,
.is_vpe = 1,
.cam_bus_scale_table = &<API key>,
},
{
.csid_core = 1,
.is_vpe = 1,
.cam_bus_scale_table = &<API key>,
},
};
static struct camera_vreg_t apq_8064_cam_vreg[] = {
#ifdef CONFIG_IMX135
{"cam_vdig", REG_LDO, 1050000, 1050000, 105000},
#else
{"cam_vdig", REG_LDO, 1200000, 1200000, 105000},
#endif
{"cam_vio", REG_VS, 0, 0, 0},
{"cam_vana", REG_LDO, 2800000, 2850000, 85600},
{"cam_vaf", REG_LDO, 2800000, 2850000, 300000},
};
#ifdef CONFIG_OV5648
static struct camera_vreg_t <API key>[] = {
{"cam_vio", REG_VS, 0, 0, 0,10},
{"cam_vana", REG_LDO, 2800000, 2850000, 85600,10},
};
#endif
#define CAML_RSTN <API key>(28)
#define CAMR_RSTN 34
#ifdef CONFIG_OV5648
#define CAMR_PWD 36 //The PWD of front camera OV5648 for Z5MINI
#endif
#ifdef <API key>
#define BACK_CAM_PWDN_VCM 37
#endif
static struct gpio <API key>[] = {
};
static struct gpio <API key>[] = {
{5, GPIOF_DIR_IN, "CAMIF_MCLK"},
{CAML_RSTN, GPIOF_DIR_OUT, "CAM_RESET"},
#ifdef <API key>
{BACK_CAM_PWDN_VCM,GPIOF_DIR_OUT,"BACK_CAM_PWDN_VCM"},
#endif
};
static struct msm_gpio_set_tbl <API key>[] = {
{CAML_RSTN, GPIOF_OUT_INIT_LOW, 10000},
{CAML_RSTN, GPIOF_OUT_INIT_HIGH, 10000},
#ifdef <API key>
{BACK_CAM_PWDN_VCM, GPIOF_OUT_INIT_LOW, 10000},
{BACK_CAM_PWDN_VCM, GPIOF_OUT_INIT_HIGH, 10000},
#endif
};
static struct <API key> <API key> = {
.<API key> = <API key>,
.<API key> = ARRAY_SIZE(<API key>),
.cam_gpio_common_tbl = <API key>,
.<API key> = ARRAY_SIZE(<API key>),
.cam_gpio_req_tbl = <API key>,
.<API key> = ARRAY_SIZE(<API key>),
.cam_gpio_set_tbl = <API key>,
.<API key> = ARRAY_SIZE(<API key>),
};
static struct gpio <API key>[] = {
#ifdef <API key>
{2, GPIOF_DIR_IN, "CAMIF_MCLK"},
#else
{4, GPIOF_DIR_IN, "CAMIF_MCLK"},
{12, GPIOF_DIR_IN, "CAMIF_I2C_DATA"},
{13, GPIOF_DIR_IN, "CAMIF_I2C_CLK"},
#endif
{CAMR_RSTN, GPIOF_DIR_OUT, "CAM_RESET"},
#ifdef CONFIG_OV5648
{CAMR_PWD,GPIOF_DIR_OUT,"CAM_PWD"},
#endif
};
static struct msm_gpio_set_tbl <API key>[] = {
#ifdef CONFIG_OV5648
{CAMR_PWD, GPIOF_OUT_INIT_LOW, 10000},
{CAMR_PWD, GPIOF_OUT_INIT_HIGH, 10000},
#endif
{CAMR_RSTN, GPIOF_OUT_INIT_LOW, 10000},
{CAMR_RSTN, GPIOF_OUT_INIT_HIGH, 10000},
};
static struct <API key> <API key> = {
.<API key> = <API key>,
.<API key> = ARRAY_SIZE(<API key>),
.cam_gpio_common_tbl = <API key>,
.<API key> = ARRAY_SIZE(<API key>),
.cam_gpio_req_tbl = <API key>,
.<API key> = ARRAY_SIZE(<API key>),
.cam_gpio_set_tbl = <API key>,
.<API key> = ARRAY_SIZE(<API key>),
};
static struct msm_camera_i2c_conf <API key> = {
.use_i2c_mux = 1,
.mux_dev = &<API key>,
.i2c_mux_mode = MODE_L,
};
static struct i2c_board_info <API key> = {
I2C_BOARD_INFO("msm_actuator", 0x11),
};
static struct msm_actuator_info <API key> = {
.board_info = &<API key>,
.cam_name = <API key>,
.bus_id = <API key>,
.vcm_pwd = 0,
.vcm_enable = 0,
};
static struct i2c_board_info <API key> = {
I2C_BOARD_INFO("msm_actuator", 0x18),
};
static struct msm_actuator_info <API key> = {
.board_info = &<API key>,
.cam_name = <API key>,
.bus_id = <API key>,
.vcm_pwd = 0,
.vcm_enable = 0,
};
static struct msm_camera_i2c_conf <API key> = {
.use_i2c_mux = 1,
.mux_dev = &<API key>,
.i2c_mux_mode = MODE_L,
};
static struct <API key> flash_imx135 = {
#ifdef <API key>
.flash_type = <API key>,
.flash_src = &msm_flash_src,
#else
.flash_type = <API key>,
#endif
};
static struct <API key> <API key> = {
.csi_lane_assign = 0xE4,
.csi_lane_mask = 0xF,
};
static struct <API key> <API key> = {
.mount_angle = 90,
.cam_vreg = apq_8064_cam_vreg,
.num_vreg = ARRAY_SIZE(apq_8064_cam_vreg),
.gpio_conf = &<API key>,
.i2c_conf = &<API key>,
.csi_lane_params = &<API key>,
};
static struct <API key> <API key> = {
.sensor_name = "imx135",
.pdata = &<API key>[0],
.flash_data = &flash_imx135,
.<API key> = &<API key>,
.csi_if = 1,
.camera_type = BACK_CAMERA_2D,
.sensor_type = BAYER_SENSOR,
.actuator_info = &<API key>,
};
static struct <API key> flash_imx074 = {
.flash_type = <API key>,
.flash_src = &msm_flash_src
};
static struct <API key> <API key> = {
.csi_lane_assign = 0xE4,
.csi_lane_mask = 0xF,
};
static struct <API key> <API key> = {
.mount_angle = 90,
.cam_vreg = apq_8064_cam_vreg,
.num_vreg = ARRAY_SIZE(apq_8064_cam_vreg),
.gpio_conf = &<API key>,
.i2c_conf = &<API key>,
.csi_lane_params = &<API key>,
};
static struct i2c_board_info <API key> = {
I2C_BOARD_INFO("imx074_eeprom", 0x34 << 1),
};
static struct msm_eeprom_info imx074_eeprom_info = {
.board_info = &<API key>,
.bus_id = <API key>,
};
static struct <API key> <API key> = {
.sensor_name = "imx074",
.pdata = &<API key>[0],
.flash_data = &flash_imx074,
.<API key> = &<API key>,
.csi_if = 1,
.camera_type = BACK_CAMERA_2D,
.sensor_type = BAYER_SENSOR,
.actuator_info = &<API key>,
.eeprom_info = &imx074_eeprom_info,
};
static struct <API key> <API key> = {
.csi_lane_assign = 0xE4,
.csi_lane_mask = 0xF,
};
static struct <API key> flash_imx091 = {
#ifdef <API key>
.flash_type = <API key>,
.flash_src = &msm_flash_src,
#else
.flash_type = <API key>,
#endif
};
static struct <API key> <API key> = {
#ifdef <API key>
.mount_angle = 90,
#else
.mount_angle = 0,
#endif
.cam_vreg = apq_8064_cam_vreg,
.num_vreg = ARRAY_SIZE(apq_8064_cam_vreg),
.gpio_conf = &<API key>,
.i2c_conf = &<API key>,
.csi_lane_params = &<API key>,
};
static struct i2c_board_info <API key> = {
I2C_BOARD_INFO("imx091_eeprom", 0x21),
};
static struct msm_eeprom_info imx091_eeprom_info = {
.board_info = &<API key>,
.bus_id = <API key>,
};
static struct <API key> <API key> = {
.sensor_name = "imx091",
.pdata = &<API key>[0],
.flash_data = &flash_imx091,
.<API key> = &<API key>,
.csi_if = 1,
.camera_type = BACK_CAMERA_2D,
.sensor_type = BAYER_SENSOR,
.actuator_info = &<API key>,
.eeprom_info = &imx091_eeprom_info,
};
static struct <API key> flash_s5k3l1yx = {
.flash_type = <API key>,
};
static struct <API key> <API key> = {
.csi_lane_assign = 0xE4,
.csi_lane_mask = 0xF,
};
static struct <API key> <API key> = {
.mount_angle = 90,
.cam_vreg = apq_8064_cam_vreg,
.num_vreg = ARRAY_SIZE(apq_8064_cam_vreg),
.gpio_conf = &<API key>,
.i2c_conf = &<API key>,
.csi_lane_params = &<API key>,
};
static struct <API key> <API key> = {
.sensor_name = "s5k3l1yx",
.pdata = &<API key>[0],
.flash_data = &flash_s5k3l1yx,
.<API key> = &<API key>,
.csi_if = 1,
.camera_type = BACK_CAMERA_2D,
.sensor_type = BAYER_SENSOR,
};
static struct <API key> flash_mt9m114 = {
.flash_type = <API key>
};
static struct <API key> <API key> = {
.csi_lane_assign = 0xE4,
.csi_lane_mask = 0x1,
};
static struct <API key> <API key> = {
.mount_angle = 90,
.cam_vreg = apq_8064_cam_vreg,
.num_vreg = ARRAY_SIZE(apq_8064_cam_vreg),
.gpio_conf = &<API key>,
.i2c_conf = &<API key>,
.csi_lane_params = &<API key>,
};
static struct <API key> <API key> = {
.sensor_name = "mt9m114",
.pdata = &<API key>[1],
.flash_data = &flash_mt9m114,
.<API key> = &<API key>,
.csi_if = 1,
.camera_type = FRONT_CAMERA_2D,
.sensor_type = YUV_SENSOR,
};
static struct <API key> flash_ov2720 = {
.flash_type = <API key>,
};
static struct <API key> <API key> = {
.csi_lane_assign = 0xE4,
.csi_lane_mask = 0x3,
};
static struct <API key> <API key> = {
.mount_angle = 0,
.cam_vreg = apq_8064_cam_vreg,
.num_vreg = ARRAY_SIZE(apq_8064_cam_vreg),
.gpio_conf = &<API key>,
.i2c_conf = &<API key>,
.csi_lane_params = &<API key>,
};
static struct <API key> <API key> = {
.sensor_name = "ov2720",
.pdata = &<API key>[1],
.flash_data = &flash_ov2720,
.<API key> = &<API key>,
.csi_if = 1,
.camera_type = FRONT_CAMERA_2D,
.sensor_type = BAYER_SENSOR,
};
#ifdef CONFIG_IMX132
static struct <API key> flash_imx132 = {
.flash_type = <API key>,
};
static struct <API key> <API key> = {
.csi_lane_assign = 0xE4,
.csi_lane_mask = 0x3,
};
static struct <API key> <API key> = {
.mount_angle = 270,
.cam_vreg = apq_8064_cam_vreg,
.num_vreg = ARRAY_SIZE(apq_8064_cam_vreg),
.gpio_conf = &<API key>,
.i2c_conf = &<API key>,
.csi_lane_params = &<API key>,
};
static struct <API key> <API key> = {
.sensor_name = "imx132",
.pdata = &<API key>[1],
.flash_data = &flash_imx132,
.<API key> = &<API key>,
.csi_if = 1,
.camera_type = FRONT_CAMERA_2D,
.sensor_type = BAYER_SENSOR,
};
#endif
#ifdef CONFIG_OV5648
static struct <API key> flash_ov5648 = {
.flash_type = <API key>,
};
static struct <API key> <API key> = {
.csi_lane_assign = 0xE4,
.csi_lane_mask = 0x3,
};
static struct <API key> <API key> = {
.mount_angle = 270,
.cam_vreg = <API key>,
.num_vreg = ARRAY_SIZE(<API key>),
.gpio_conf = &<API key>,
.i2c_conf = &<API key>,
.csi_lane_params = &<API key>,
};
static struct <API key> <API key> = {
.sensor_name = "ov5648",
.pdata = &<API key>[1],
.flash_data = &flash_ov5648,
.<API key> = &<API key>,
.csi_if = 1,
.camera_type = FRONT_CAMERA_2D,
.sensor_type = BAYER_SENSOR,
};
#endif
static struct platform_device msm_camera_server = {
.name = "msm_cam_server",
.id = 0,
};
void __init apq8064_init_cam(void)
{
/* for SGLTE2 platform, do not configure i2c/gpiomux gsbi4 is used for
* some other purpose */
if (<API key>() != <API key>) {
msm_gpiomux_install(<API key>,
ARRAY_SIZE(<API key>));
}
if (<API key>()) {
<API key>.mount_angle = 0;
<API key>.mount_angle = 0;
} else if (<API key>())
<API key>.mount_angle = 180;
<API key>(&msm_camera_server);
if (<API key>() != <API key>)
<API key>(&<API key>);
<API key>(&<API key>);
<API key>(&<API key>);
<API key>(&<API key>);
<API key>(&<API key>);
<API key>(&<API key>);
<API key>(&msm8960_device_vfe);
<API key>(&msm8960_device_vpe);
}
#ifdef CONFIG_I2C
static struct i2c_board_info <API key>[] = {
{
I2C_BOARD_INFO("imx074", 0x1A),
.platform_data = &<API key>,
},
{
I2C_BOARD_INFO("imx135", 0x20),
.platform_data = &<API key>,
},
{
I2C_BOARD_INFO("mt9m114", 0x48),
.platform_data = &<API key>,
},
{
I2C_BOARD_INFO("ov2720", 0x6C),
.platform_data = &<API key>,
},
{
I2C_BOARD_INFO("sc628a", 0x6E),
},
#ifdef <API key>
{
I2C_BOARD_INFO("lm3642", 0x63),//camera flash led driver ic
},
#endif
{
I2C_BOARD_INFO("imx091", 0x34),
.platform_data = &<API key>,
},
{
I2C_BOARD_INFO("s5k3l1yx", 0x21), //conflict with imx135, change from 0x20 to 0x21, tanyijun
.platform_data = &<API key>,
},
#ifdef CONFIG_IMX132
{
I2C_BOARD_INFO("imx132", 0x6D),//use i2c slave write addr
.platform_data = &<API key>,
},
#endif
#ifdef CONFIG_OV5648
{
I2C_BOARD_INFO("ov5648", 0x6d),//use i2c slave write addr
.platform_data = &<API key>,
},
#endif
};
struct <API key> <API key> = {
.board_info = <API key>,
.num_i2c_board_info = ARRAY_SIZE(<API key>),
};
#endif
#endif
|
/* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
/*
* Wirzenius wrote this portably, Torvalds fucked it up :-)
*
* from hush: simple_itoa() was lifted from boa-0.93.15
*/
#include <common.h>
#include <charset.h>
#include <efi_loader.h>
#include <div64.h>
#include <hexdump.h>
#include <stdarg.h>
#include <uuid.h>
#include <vsprintf.h>
#include <linux/ctype.h>
#include <linux/err.h>
#include <linux/types.h>
#include <linux/string.h>
/* we use this so that we can do without the ctype library */
#define is_digit(c) ((c) >= '0' && (c) <= '9')
static int skip_atoi(const char **s)
{
int i = 0;
while (is_digit(**s))
i = i * 10 + *((*s)++) - '0';
return i;
}
/* Formats correctly any integer in [0,99999].
* Outputs from one to five digits depending on input.
* On i386 gcc 4.1.2 -O2: ~250 bytes of code. */
static char *put_dec_trunc(char *buf, unsigned q)
{
unsigned d3, d2, d1, d0;
d1 = (q>>4) & 0xf;
d2 = (q>>8) & 0xf;
d3 = (q>>12);
d0 = 6*(d3 + d2 + d1) + (q & 0xf);
q = (d0 * 0xcd) >> 11;
d0 = d0 - 10*q;
*buf++ = d0 + '0'; /* least significant digit */
d1 = q + 9*d3 + 5*d2 + d1;
if (d1 != 0) {
q = (d1 * 0xcd) >> 11;
d1 = d1 - 10*q;
*buf++ = d1 + '0'; /* next digit */
d2 = q + 2*d2;
if ((d2 != 0) || (d3 != 0)) {
q = (d2 * 0xd) >> 7;
d2 = d2 - 10*q;
*buf++ = d2 + '0'; /* next digit */
d3 = q + 4*d3;
if (d3 != 0) {
q = (d3 * 0xcd) >> 11;
d3 = d3 - 10*q;
*buf++ = d3 + '0'; /* next digit */
if (q != 0)
*buf++ = q + '0'; /* most sign. digit */
}
}
}
return buf;
}
/* Same with if's removed. Always emits five digits */
static char *put_dec_full(char *buf, unsigned q)
{
/* BTW, if q is in [0,9999], 8-bit ints will be enough, */
/* but anyway, gcc produces better code with full-sized ints */
unsigned d3, d2, d1, d0;
d1 = (q>>4) & 0xf;
d2 = (q>>8) & 0xf;
d3 = (q>>12);
/*
* Possible ways to approx. divide by 10
* gcc -O2 replaces multiply with shifts and adds
* (x * 0xcd) >> 11: 11001101 - shorter code than * 0x67 (on i386)
* (x * 0x67) >> 10: 1100111
* (x * 0x34) >> 9: 110100 - same
* (x * 0x1a) >> 8: 11010 - same
* (x * 0x0d) >> 7: 1101 - same, shortest code (on i386)
*/
d0 = 6*(d3 + d2 + d1) + (q & 0xf);
q = (d0 * 0xcd) >> 11;
d0 = d0 - 10*q;
*buf++ = d0 + '0';
d1 = q + 9*d3 + 5*d2 + d1;
q = (d1 * 0xcd) >> 11;
d1 = d1 - 10*q;
*buf++ = d1 + '0';
d2 = q + 2*d2;
q = (d2 * 0xd) >> 7;
d2 = d2 - 10*q;
*buf++ = d2 + '0';
d3 = q + 4*d3;
q = (d3 * 0xcd) >> 11; /* - shorter code */
/* q = (d3 * 0x67) >> 10; - would also work */
d3 = d3 - 10*q;
*buf++ = d3 + '0';
*buf++ = q + '0';
return buf;
}
/* No inlining helps gcc to use registers better */
static noinline char *put_dec(char *buf, uint64_t num)
{
while (1) {
unsigned rem;
if (num < 100000)
return put_dec_trunc(buf, num);
rem = do_div(num, 100000);
buf = put_dec_full(buf, rem);
}
}
#define ZEROPAD 1 /* pad with zero */
#define SIGN 2 /* unsigned/signed long */
#define PLUS 4 /* show plus */
#define SPACE 8 /* space if plus */
#define LEFT 16 /* left justified */
#define SMALL 32 /* Must be 32 == 0x20 */
#define SPECIAL 64
/*
* Macro to add a new character to our output string, but only if it will
* fit. The macro moves to the next character position in the output string.
*/
#define ADDCH(str, ch) do { \
if ((str) < end) \
*(str) = (ch); \
++str; \
} while (0)
static char *number(char *buf, char *end, u64 num,
int base, int size, int precision, int type)
{
/* we are called with base 8, 10 or 16, only, thus don't need "G..." */
static const char digits[16] = "0123456789ABCDEF";
char tmp[66];
char sign;
char locase;
int need_pfx = ((type & SPECIAL) && base != 10);
int i;
/* locase = 0 or 0x20. ORing digits or letters with 'locase'
* produces same digits or (maybe lowercased) letters */
locase = (type & SMALL);
if (type & LEFT)
type &= ~ZEROPAD;
sign = 0;
if (type & SIGN) {
if ((s64) num < 0) {
sign = '-';
num = -(s64) num;
size
} else if (type & PLUS) {
sign = '+';
size
} else if (type & SPACE) {
sign = ' ';
size
}
}
if (need_pfx) {
size
if (base == 16)
size
}
/* generate full string in tmp[], in reverse order */
i = 0;
if (num == 0)
tmp[i++] = '0';
/* Generic code, for any base:
else do {
tmp[i++] = (digits[do_div(num,base)] | locase);
} while (num != 0);
*/
else if (base != 10) { /* 8 or 16 */
int mask = base - 1;
int shift = 3;
if (base == 16)
shift = 4;
do {
tmp[i++] = (digits[((unsigned char)num) & mask]
| locase);
num >>= shift;
} while (num);
} else { /* base 10 */
i = put_dec(tmp, num) - tmp;
}
/* printing 100 using %2d gives "100", not "00" */
if (i > precision)
precision = i;
/* leading space padding */
size -= precision;
if (!(type & (ZEROPAD + LEFT))) {
while (--size >= 0)
ADDCH(buf, ' ');
}
/* sign */
if (sign)
ADDCH(buf, sign);
/* "0x" / "0" prefix */
if (need_pfx) {
ADDCH(buf, '0');
if (base == 16)
ADDCH(buf, 'X' | locase);
}
/* zero or space padding */
if (!(type & LEFT)) {
char c = (type & ZEROPAD) ? '0' : ' ';
while (--size >= 0)
ADDCH(buf, c);
}
/* hmm even more zero padding? */
while (i <= --precision)
ADDCH(buf, '0');
/* actual digits of result */
while (--i >= 0)
ADDCH(buf, tmp[i]);
/* trailing space padding */
while (--size >= 0)
ADDCH(buf, ' ');
return buf;
}
static char *string(char *buf, char *end, char *s, int field_width,
int precision, int flags)
{
int len, i;
if (s == NULL)
s = "<NULL>";
len = strnlen(s, precision);
if (!(flags & LEFT))
while (len < field_width
ADDCH(buf, ' ');
for (i = 0; i < len; ++i)
ADDCH(buf, *s++);
while (len < field_width
ADDCH(buf, ' ');
return buf;
}
/* U-Boot uses UTF-16 strings in the EFI context only. */
#if CONFIG_IS_ENABLED(EFI_LOADER) && !defined(API_BUILD)
static char *string16(char *buf, char *end, u16 *s, int field_width,
int precision, int flags)
{
const u16 *str = s ? s : L"<NULL>";
ssize_t i, len = utf16_strnlen(str, precision);
if (!(flags & LEFT))
for (; len < field_width; --field_width)
ADDCH(buf, ' ');
for (i = 0; i < len && buf + utf16_utf8_strnlen(str, 1) <= end; ++i) {
s32 s = utf16_get(&str);
if (s < 0)
s = '?';
utf8_put(s, &buf);
}
for (; len < field_width; --field_width)
ADDCH(buf, ' ');
return buf;
}
#if CONFIG_IS_ENABLED(<API key>)
static char *device_path_string(char *buf, char *end, void *dp, int field_width,
int precision, int flags)
{
u16 *str;
/* If dp == NULL output the string '<NULL>' */
if (!dp)
return string16(buf, end, dp, field_width, precision, flags);
str = efi_dp_str((struct efi_device_path *)dp);
if (!str)
return ERR_PTR(-ENOMEM);
buf = string16(buf, end, str, field_width, precision, flags);
efi_free_pool(str);
return buf;
}
#endif
#endif
static char *mac_address_string(char *buf, char *end, u8 *addr, int field_width,
int precision, int flags)
{
/* (6 * 2 hex digits), 5 colons and trailing zero */
char mac_addr[6 * 3];
char *p = mac_addr;
int i;
for (i = 0; i < 6; i++) {
p = hex_byte_pack(p, addr[i]);
if (!(flags & SPECIAL) && i != 5)
*p++ = ':';
}
*p = '\0';
return string(buf, end, mac_addr, field_width, precision,
flags & ~SPECIAL);
}
static char *ip6_addr_string(char *buf, char *end, u8 *addr, int field_width,
int precision, int flags)
{
/* (8 * 4 hex digits), 7 colons and trailing zero */
char ip6_addr[8 * 5];
char *p = ip6_addr;
int i;
for (i = 0; i < 8; i++) {
p = hex_byte_pack(p, addr[2 * i]);
p = hex_byte_pack(p, addr[2 * i + 1]);
if (!(flags & SPECIAL) && i != 7)
*p++ = ':';
}
*p = '\0';
return string(buf, end, ip6_addr, field_width, precision,
flags & ~SPECIAL);
}
static char *ip4_addr_string(char *buf, char *end, u8 *addr, int field_width,
int precision, int flags)
{
/* (4 * 3 decimal digits), 3 dots and trailing zero */
char ip4_addr[4 * 4];
char temp[3]; /* hold each IP quad in reverse order */
char *p = ip4_addr;
int i, digits;
for (i = 0; i < 4; i++) {
digits = put_dec_trunc(temp, addr[i]) - temp;
/* reverse the digits in the quad */
while (digits
*p++ = temp[digits];
if (i != 3)
*p++ = '.';
}
*p = '\0';
return string(buf, end, ip4_addr, field_width, precision,
flags & ~SPECIAL);
}
#ifdef CONFIG_LIB_UUID
/*
* This works (roughly) the same way as Linux's.
*
* %pUb: <API key>
* %pUB: <API key>
* %pUl: <API key>
* %pUL: <API key>
*/
static char *uuid_string(char *buf, char *end, u8 *addr, int field_width,
int precision, int flags, const char *fmt)
{
char uuid[UUID_STR_LEN + 1];
int str_format;
switch (*(++fmt)) {
case 'L':
str_format = <API key> | UUID_STR_UPPER_CASE;
break;
case 'l':
str_format = <API key>;
break;
case 'B':
str_format = UUID_STR_FORMAT_STD | UUID_STR_UPPER_CASE;
break;
default:
str_format = UUID_STR_FORMAT_STD;
break;
}
if (addr)
uuid_bin_to_str(addr, uuid, str_format);
else
strcpy(uuid, "<NULL>");
return string(buf, end, uuid, field_width, precision, flags);
}
#endif
/*
* Show a '%p' thing. A kernel extension is that the '%p' is followed
* by an extra set of alphanumeric characters that are extended format
* specifiers.
*
* Right now we handle:
*
* - 'M' For a 6-byte MAC address, it prints the address in the
* usual colon-separated hex notation
* - 'I' [46] for IPv4/IPv6 addresses printed in the usual way (dot-separated
* decimal for v4 and colon separated network-order 16 bit hex for v6)
* - 'i' [46] for 'raw' IPv4/IPv6 addresses, IPv6 omits the colons, IPv4 is
* currently the same
*
* Note: The difference between 'S' and 'F' is that on ia64 and ppc64
* function pointers are really function descriptors, which contain a
* pointer to the real address.
*/
static char *pointer(const char *fmt, char *buf, char *end, void *ptr,
int field_width, int precision, int flags)
{
u64 num = (uintptr_t)ptr;
/*
* Being a boot loader, we explicitly allow pointers to
* (physical) address null.
*/
#if 0
if (!ptr)
return string(buf, end, "(null)", field_width, precision,
flags);
#endif
switch (*fmt) {
/* Device paths only exist in the EFI context. */
#if CONFIG_IS_ENABLED(<API key>) && !defined(API_BUILD)
case 'D':
return device_path_string(buf, end, ptr, field_width,
precision, flags);
#endif
case 'a':
flags |= SPECIAL | ZEROPAD;
switch (fmt[1]) {
case 'p':
default:
field_width = sizeof(phys_addr_t) * 2 + 2;
num = *(phys_addr_t *)ptr;
break;
}
break;
case 'm':
flags |= SPECIAL;
/* Fallthrough */
case 'M':
return mac_address_string(buf, end, ptr, field_width,
precision, flags);
case 'i':
flags |= SPECIAL;
/* Fallthrough */
case 'I':
if (fmt[1] == '6')
return ip6_addr_string(buf, end, ptr, field_width,
precision, flags);
if (fmt[1] == '4')
return ip4_addr_string(buf, end, ptr, field_width,
precision, flags);
flags &= ~SPECIAL;
break;
#ifdef CONFIG_LIB_UUID
case 'U':
return uuid_string(buf, end, ptr, field_width, precision,
flags, fmt);
#endif
default:
break;
}
flags |= SMALL;
if (field_width == -1) {
field_width = 2*sizeof(void *);
flags |= ZEROPAD;
}
return number(buf, end, num, 16, field_width, precision, flags);
}
static int vsnprintf_internal(char *buf, size_t size, const char *fmt,
va_list args)
{
u64 num;
int base;
char *str;
int flags; /* flags to number() */
int field_width; /* width of output field */
int precision; /* min. # of digits for integers; max
number of chars for from string */
int qualifier; /* 'h', 'l', or 'L' for integer fields */
/* 'z' support added 23/7/1999 S.H. */
/* 'z' changed to 'Z' --davidm 1/25/99 */
/* 't' added for ptrdiff_t */
char *end = buf + size;
/* Make sure end is always >= buf - do we want this in U-Boot? */
if (end < buf) {
end = ((void *)-1);
size = end - buf;
}
str = buf;
for (; *fmt ; ++fmt) {
if (*fmt != '%') {
ADDCH(str, *fmt);
continue;
}
/* process flags */
flags = 0;
repeat:
++fmt; /* this also skips first '%' */
switch (*fmt) {
case '-':
flags |= LEFT;
goto repeat;
case '+':
flags |= PLUS;
goto repeat;
case ' ':
flags |= SPACE;
goto repeat;
case '
flags |= SPECIAL;
goto repeat;
case '0':
flags |= ZEROPAD;
goto repeat;
}
/* get field width */
field_width = -1;
if (is_digit(*fmt))
field_width = skip_atoi(&fmt);
else if (*fmt == '*') {
++fmt;
/* it's the next argument */
field_width = va_arg(args, int);
if (field_width < 0) {
field_width = -field_width;
flags |= LEFT;
}
}
/* get the precision */
precision = -1;
if (*fmt == '.') {
++fmt;
if (is_digit(*fmt))
precision = skip_atoi(&fmt);
else if (*fmt == '*') {
++fmt;
/* it's the next argument */
precision = va_arg(args, int);
}
if (precision < 0)
precision = 0;
}
/* get the conversion qualifier */
qualifier = -1;
if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L' ||
*fmt == 'Z' || *fmt == 'z' || *fmt == 't') {
qualifier = *fmt;
++fmt;
if (qualifier == 'l' && *fmt == 'l') {
qualifier = 'L';
++fmt;
}
}
/* default base */
base = 10;
switch (*fmt) {
case 'c':
if (!(flags & LEFT)) {
while (--field_width > 0)
ADDCH(str, ' ');
}
ADDCH(str, (unsigned char) va_arg(args, int));
while (--field_width > 0)
ADDCH(str, ' ');
continue;
case 's':
/* U-Boot uses UTF-16 strings in the EFI context only. */
#if CONFIG_IS_ENABLED(EFI_LOADER) && !defined(API_BUILD)
if (qualifier == 'l') {
str = string16(str, end, va_arg(args, u16 *),
field_width, precision, flags);
} else
#endif
{
str = string(str, end, va_arg(args, char *),
field_width, precision, flags);
}
continue;
case 'p':
str = pointer(fmt + 1, str, end,
va_arg(args, void *),
field_width, precision, flags);
if (IS_ERR(str))
return PTR_ERR(str);
/* Skip all alphanumeric pointer suffixes */
while (isalnum(fmt[1]))
fmt++;
continue;
case 'n':
if (qualifier == 'l') {
long *ip = va_arg(args, long *);
*ip = (str - buf);
} else {
int *ip = va_arg(args, int *);
*ip = (str - buf);
}
continue;
case '%':
ADDCH(str, '%');
continue;
/* integer number formats - set up the flags and "break" */
case 'o':
base = 8;
break;
case 'x':
flags |= SMALL;
case 'X':
base = 16;
break;
case 'd':
case 'i':
flags |= SIGN;
case 'u':
break;
default:
ADDCH(str, '%');
if (*fmt)
ADDCH(str, *fmt);
else
--fmt;
continue;
}
if (qualifier == 'L') /* "quad" for 64 bit variables */
num = va_arg(args, unsigned long long);
else if (qualifier == 'l') {
num = va_arg(args, unsigned long);
if (flags & SIGN)
num = (signed long) num;
} else if (qualifier == 'Z' || qualifier == 'z') {
num = va_arg(args, size_t);
} else if (qualifier == 't') {
num = va_arg(args, ptrdiff_t);
} else if (qualifier == 'h') {
num = (unsigned short) va_arg(args, int);
if (flags & SIGN)
num = (signed short) num;
} else {
num = va_arg(args, unsigned int);
if (flags & SIGN)
num = (signed int) num;
}
str = number(str, end, num, base, field_width, precision,
flags);
}
if (size > 0) {
ADDCH(str, '\0');
if (str > end)
end[-1] = '\0';
--str;
}
/* the trailing null byte doesn't count towards the total */
return str - buf;
}
int vsnprintf(char *buf, size_t size, const char *fmt,
va_list args)
{
return vsnprintf_internal(buf, size, fmt, args);
}
int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
{
int i;
i = vsnprintf(buf, size, fmt, args);
if (likely(i < size))
return i;
if (size != 0)
return size - 1;
return 0;
}
int snprintf(char *buf, size_t size, const char *fmt, ...)
{
va_list args;
int i;
va_start(args, fmt);
i = vsnprintf(buf, size, fmt, args);
va_end(args);
return i;
}
int scnprintf(char *buf, size_t size, const char *fmt, ...)
{
va_list args;
int i;
va_start(args, fmt);
i = vscnprintf(buf, size, fmt, args);
va_end(args);
return i;
}
/**
* Format a string and place it in a buffer (va_list version)
*
* @param buf The buffer to place the result into
* @param fmt The format string to use
* @param args Arguments for the format string
*
* The function returns the number of characters written
* into @buf. Use vsnprintf() or vscnprintf() in order to avoid
* buffer overflows.
*
* If you're not already dealing with a va_list consider using sprintf().
*/
int vsprintf(char *buf, const char *fmt, va_list args)
{
return vsnprintf_internal(buf, INT_MAX, fmt, args);
}
int sprintf(char *buf, const char *fmt, ...)
{
va_list args;
int i;
va_start(args, fmt);
i = vsprintf(buf, fmt, args);
va_end(args);
return i;
}
#if CONFIG_IS_ENABLED(PRINTF)
int printf(const char *fmt, ...)
{
va_list args;
uint i;
char printbuffer[CONFIG_SYS_PBSIZE];
va_start(args, fmt);
/*
* For this to work, printbuffer must be larger than
* anything we ever want to print.
*/
i = vscnprintf(printbuffer, sizeof(printbuffer), fmt, args);
va_end(args);
/* Handle error */
if (i <= 0)
return i;
/* Print the string */
puts(printbuffer);
return i;
}
int vprintf(const char *fmt, va_list args)
{
uint i;
char printbuffer[CONFIG_SYS_PBSIZE];
/*
* For this to work, printbuffer must be larger than
* anything we ever want to print.
*/
i = vscnprintf(printbuffer, sizeof(printbuffer), fmt, args);
/* Handle error */
if (i <= 0)
return i;
/* Print the string */
puts(printbuffer);
return i;
}
#endif
char *simple_itoa(ulong i)
{
/* 21 digits plus null terminator, good for 64-bit or smaller ints */
static char local[22];
char *p = &local[21];
*p
do {
*p-- = '0' + i % 10;
i /= 10;
} while (i > 0);
return p + 1;
}
/* We don't seem to have %'d in U-Boot */
void print_grouped_ull(unsigned long long int_val, int digits)
{
char str[21], *s;
int grab = 3;
digits = (digits + 2) / 3;
sprintf(str, "%*llu", digits * 3, int_val);
for (s = str; *s; s += grab) {
if (s != str)
putc(s[-1] != ' ' ? ',' : ' ');
printf("%.*s", grab, s);
grab = 3;
}
}
bool str2off(const char *p, loff_t *num)
{
char *endptr;
*num = simple_strtoull(p, &endptr, 16);
return *p != '\0' && *endptr == '\0';
}
bool str2long(const char *p, ulong *num)
{
char *endptr;
*num = simple_strtoul(p, &endptr, 16);
return *p != '\0' && *endptr == '\0';
}
char *strmhz(char *buf, unsigned long hz)
{
long l, n;
long m;
n = DIV_ROUND_CLOSEST(hz, 1000) / 1000L;
l = sprintf(buf, "%ld", n);
hz -= n * 1000000L;
m = DIV_ROUND_CLOSEST(hz, 1000L);
if (m != 0)
sprintf(buf + l, ".%03ld", m);
return buf;
}
|
require 'migrate'
class RenameBugsToNotes < ActiveRecord::Migration
def self.up
rename_enumeration "map_bug_status_enum", "note_status_enum"
rename_enumeration "map_bug_event_enum", "note_event_enum"
rename_table :map_bugs, :notes
rename_index :notes, "map_bugs_pkey", "notes_pkey"
rename_index :notes, "<API key>", "<API key>"
rename_index :notes, "<API key>", "<API key>"
rename_index :notes, "map_bugs_tile_idx", "<API key>"
remove_foreign_key :map_bug_comment, [:bug_id], :map_bugs, [:id]
rename_column :map_bug_comment, :author_id, :commenter_id
remove_foreign_key :map_bug_comment, [:commenter_id], :users, [:id]
rename_column :map_bug_comment, :commenter_id, :author_id
rename_table :map_bug_comment, :note_comments
rename_column :note_comments, :bug_id, :note_id
rename_index :note_comments, "<API key>", "note_comments_pkey"
rename_index :note_comments, "<API key>", "<API key>"
add_foreign_key :note_comments, [:note_id], :notes, [:id]
add_foreign_key :note_comments, [:author_id], :users, [:id]
end
def self.down
remove_foreign_key :note_comments, [:author_id], :users, [:id]
remove_foreign_key :note_comments, [:note_id], :notes, [:id]
rename_index :note_comments, "<API key>", "<API key>"
rename_index :notes, "note_comments_pkey", "<API key>"
rename_column :note_comments, :note_id, :bug_id
rename_table :note_comments, :map_bug_comment
rename_column :map_bug_comment, :author_id, :commenter_id
add_foreign_key :map_bug_comment, [:commenter_id], :users, [:id]
rename_column :map_bug_comment, :commenter_id, :author_id
add_foreign_key :map_bug_comment, [:bug_id], :notes, [:id]
rename_index :notes, "<API key>", "map_bugs_tile_idx"
rename_index :notes, "<API key>", "<API key>"
rename_index :notes, "<API key>", "<API key>"
rename_index :notes, "notes_pkey", "map_bugs_pkey"
rename_table :notes, :map_bugs
rename_enumeration "note_event_enum", "map_bug_event_enum"
rename_enumeration "note_status_enum", "map_bug_status_enum"
end
end
|
extern void gen_model_h (lf *file, insn_table *isa);
extern void gen_model_c (lf *file, insn_table *isa);
|
#if TARGET_OS_IPHONE
#import <CoreGraphics/CoreGraphics.h>
#import <Foundation/Foundation.h>
#import <WebKitLegacy/WebFrameIOS.h>
@interface WebSelectionRect : NSObject <NSCopying> {
CGRect m_rect;
WKWritingDirection m_writingDirection;
BOOL m_isLineBreak;
BOOL m_isFirstOnLine;
BOOL m_isLastOnLine;
BOOL m_containsStart;
BOOL m_containsEnd;
BOOL m_isInFixedPosition;
BOOL m_isHorizontal;
}
@property (nonatomic, assign) CGRect rect;
@property (nonatomic, assign) WKWritingDirection writingDirection;
@property (nonatomic, assign) BOOL isLineBreak;
@property (nonatomic, assign) BOOL isFirstOnLine;
@property (nonatomic, assign) BOOL isLastOnLine;
@property (nonatomic, assign) BOOL containsStart;
@property (nonatomic, assign) BOOL containsEnd;
@property (nonatomic, assign) BOOL isInFixedPosition;
@property (nonatomic, assign) BOOL isHorizontal;
+ (WebSelectionRect *)selectionRect;
+ (CGRect)startEdge:(NSArray *)rects;
+ (CGRect)endEdge:(NSArray *)rects;
@end
#endif // TARGET_OS_IPHONE
|
<?php
// security - hide paths
if (!defined('ADODB_DIR')) die();
/*
MSSQL has moved most performance info to Performance Monitor
*/
class perf_mssql extends adodb_perf{
var $sql1 = 'cast(sql1 as text)';
var $createTableSQL = "CREATE TABLE adodb_logsql (
created datetime NOT NULL,
sql0 varchar(250) NOT NULL,
sql1 varchar(4000) NOT NULL,
params varchar(3000) NOT NULL,
tracer varchar(500) NOT NULL,
timer decimal(16,6) NOT NULL
)";
var $settings = array(
'Ratios',
'data cache hit ratio' => array('RATIO',
"select round((a.cntr_value*100.0)/b.cntr_value,2) from master.dbo.sysperfinfo a, master.dbo.sysperfinfo b where a.counter_name = 'Buffer cache hit ratio' and b.counter_name='Buffer cache hit ratio base'",
'=WarnCacheRatio'),
'prepared sql hit ratio' => array('RATIO',
array('dbcc cachestats','Prepared',1,100),
''),
'adhoc sql hit ratio' => array('RATIO',
array('dbcc cachestats','Adhoc',1,100),
''),
'IO',
'data reads' => array('IO',
"select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page reads/sec'"),
'data writes' => array('IO',
"select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page writes/sec'"),
'Data Cache',
'data cache size' => array('DATAC',
"select cntr_value*8192 from master.dbo.sysperfinfo where counter_name = 'Total Pages' and object_name='SQLServer:Buffer Manager'",
'' ),
'data cache blocksize' => array('DATAC',
"select 8192",'page size'),
'Connections',
'current connections' => array('SESS',
'=sp_who',
''),
'max connections' => array('SESS',
"SELECT @@MAX_CONNECTIONS",
''),
false
);
function perf_mssql(&$conn)
{
if ($conn->dataProvider == 'odbc') {
$this->sql1 = 'sql1';
//$this->explain = false;
}
$this->conn =& $conn;
}
function Explain($sql,$partial=false)
{
$save = $this->conn->LogSQL(false);
if ($partial) {
$sqlq = $this->conn->qstr($sql.'%');
$arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
if ($arr) {
foreach($arr as $row) {
$sql = reset($row);
if (crc32($sql) == $partial) break;
}
}
}
$s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
$this->conn->Execute("SET SHOWPLAN_ALL ON;");
$sql = str_replace('?',"''",$sql);
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs =& $this->conn->Execute($sql);
//adodb_printr($rs);
$ADODB_FETCH_MODE = $save;
if ($rs) {
$rs->MoveNext();
$s .= '<table bgcolor=white border=0 cellpadding="1" callspacing=0><tr><td nowrap align=center> Rows<td nowrap align=center> IO<td nowrap align=center> CPU<td align=left> Plan</tr>';
while (!$rs->EOF) {
$s .= '<tr><td>'.round($rs->fields[8],1).'<td>'.round($rs->fields[9],3).'<td align=right>'.round($rs->fields[10],3).'<td nowrap><pre>'.htmlspecialchars($rs->fields[0])."</td></pre></tr>\n"; ## NOTE CORRUPT </td></pre> tag is intentional!!!!
$rs->MoveNext();
}
$s .= '</table>';
$rs->NextRecordSet();
}
$this->conn->Execute("SET SHOWPLAN_ALL OFF;");
$this->conn->LogSQL($save);
$s .= $this->Tracer($sql);
return $s;
}
function Tables()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
//$this->conn->debug=1;
$s = '<table border=1 bgcolor=white><tr><td><b>tablename</b></td><td><b>size_in_k</b></td><td><b>index size</b></td><td><b>reserved size</b></td></tr>';
$rs1 = $this->conn->Execute("select distinct name from sysobjects where xtype='U'");
if ($rs1) {
while (!$rs1->EOF) {
$tab = $rs1->fields[0];
$tabq = $this->conn->qstr($tab);
$rs2 = $this->conn->Execute("sp_spaceused $tabq");
if ($rs2) {
$s .= '<tr><td>'.$tab.'</td><td align=right>'.$rs2->fields[3].'</td><td align=right>'.$rs2->fields[4].'</td><td align=right>'.$rs2->fields[2].'</td></tr>';
$rs2->Close();
}
$rs1->MoveNext();
}
$rs1->Close();
}
$ADODB_FETCH_MODE = $save;
return $s.'</table>';
}
function sp_who()
{
$arr = $this->conn->GetArray('sp_who');
return sizeof($arr);
}
function HealthCheck($cli=false)
{
$this->conn->Execute('dbcc traceon(3604)');
$html = adodb_perf::HealthCheck($cli);
$this->conn->Execute('dbcc traceoff(3604)');
return $html;
}
}
?>
|
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <asm/spu.h>
#include <asm/spu_csa.h>
#include "spufs.h"
struct spu_context *alloc_spu_context(void)
{
struct spu_context *ctx;
ctx = kzalloc(sizeof *ctx, GFP_KERNEL);
if (!ctx)
goto out;
/* Binding to physical processor deferred
* until spu_activate().
*/
spu_init_csa(&ctx->csa);
if (!ctx->csa.lscsa) {
goto out_free;
}
spin_lock_init(&ctx->mmio_lock);
kref_init(&ctx->kref);
init_rwsem(&ctx->state_sema);
init_MUTEX(&ctx->run_sema);
init_waitqueue_head(&ctx->ibox_wq);
init_waitqueue_head(&ctx->wbox_wq);
init_waitqueue_head(&ctx->stop_wq);
init_waitqueue_head(&ctx->mfc_wq);
ctx->state = SPU_STATE_SAVED;
ctx->ops = &spu_backing_ops;
ctx->owner = get_task_mm(current);
goto out;
out_free:
kfree(ctx);
ctx = NULL;
out:
return ctx;
}
void destroy_spu_context(struct kref *kref)
{
struct spu_context *ctx;
ctx = container_of(kref, struct spu_context, kref);
down_write(&ctx->state_sema);
spu_deactivate(ctx);
up_write(&ctx->state_sema);
spu_fini_csa(&ctx->csa);
kfree(ctx);
}
struct spu_context * get_spu_context(struct spu_context *ctx)
{
kref_get(&ctx->kref);
return ctx;
}
int put_spu_context(struct spu_context *ctx)
{
return kref_put(&ctx->kref, &destroy_spu_context);
}
/* give up the mm reference when the context is about to be destroyed */
void spu_forget(struct spu_context *ctx)
{
struct mm_struct *mm;
spu_acquire_saved(ctx);
mm = ctx->owner;
ctx->owner = NULL;
mmput(mm);
spu_release(ctx);
}
void spu_acquire(struct spu_context *ctx)
{
down_read(&ctx->state_sema);
}
void spu_release(struct spu_context *ctx)
{
up_read(&ctx->state_sema);
}
void spu_unmap_mappings(struct spu_context *ctx)
{
if (ctx->local_store)
unmap_mapping_range(ctx->local_store, 0, LS_SIZE, 1);
if (ctx->mfc)
unmap_mapping_range(ctx->mfc, 0, 0x4000, 1);
if (ctx->cntl)
unmap_mapping_range(ctx->cntl, 0, 0x4000, 1);
if (ctx->signal1)
unmap_mapping_range(ctx->signal1, 0, 0x4000, 1);
if (ctx->signal2)
unmap_mapping_range(ctx->signal2, 0, 0x4000, 1);
}
int <API key>(struct spu_context *ctx)
{
int ret = 0;
down_read(&ctx->state_sema);
if (ctx->state == SPU_STATE_RUNNABLE) {
ctx->spu->prio = current->prio;
return 0;
}
up_read(&ctx->state_sema);
down_write(&ctx->state_sema);
/* ctx is about to be freed, can't acquire any more */
if (!ctx->owner) {
ret = -EINVAL;
goto out;
}
if (ctx->state == SPU_STATE_SAVED) {
ret = spu_activate(ctx, 0);
if (ret)
goto out;
ctx->state = SPU_STATE_RUNNABLE;
}
downgrade_write(&ctx->state_sema);
/* On success, we return holding the lock */
return ret;
out:
/* Release here, to simplify calling code. */
up_write(&ctx->state_sema);
return ret;
}
void spu_acquire_saved(struct spu_context *ctx)
{
down_read(&ctx->state_sema);
if (ctx->state == SPU_STATE_SAVED)
return;
up_read(&ctx->state_sema);
down_write(&ctx->state_sema);
if (ctx->state == SPU_STATE_RUNNABLE) {
spu_deactivate(ctx);
ctx->state = SPU_STATE_SAVED;
}
downgrade_write(&ctx->state_sema);
}
|
#include "ScriptMgr.h"
#include "Chat.h"
#include "DatabaseEnv.h"
#include "Item.h"
#include "Language.h"
#include "Mail.h"
#include "ObjectMgr.h"
#include "Pet.h"
#include "Player.h"
#include "RBAC.h"
#include "WorldSession.h"
class send_commandscript : public CommandScript
{
public:
send_commandscript() : CommandScript("send_commandscript") { }
std::vector<ChatCommand> GetCommands() const override
{
static std::vector<ChatCommand> sendCommandTable =
{
{ "items", rbac::<API key>, true, &<API key>, "" },
{ "mail", rbac::<API key>, true, &<API key>, "" },
{ "message", rbac::<API key>, true, &<API key>, "" },
{ "money", rbac::<API key>, true, &<API key>, "" },
};
static std::vector<ChatCommand> commandTable =
{
{ "send", rbac::<API key>, false, nullptr, "", sendCommandTable },
};
return commandTable;
}
// Send mail by command
static bool <API key>(ChatHandler* handler, char const* args)
{
// format: name "subject text" "mail text"
Player* target;
ObjectGuid targetGuid;
std::string targetName;
if (!handler->extractPlayerTarget((char*)args, &target, &targetGuid, &targetName))
return false;
char* tail1 = strtok(nullptr, "");
if (!tail1)
return false;
char const* msgSubject = handler->extractQuotedArg(tail1);
if (!msgSubject)
return false;
char* tail2 = strtok(nullptr, "");
if (!tail2)
return false;
char const* msgText = handler->extractQuotedArg(tail2);
if (!msgText)
return false;
// msgSubject, msgText isn't NUL after prev. check
std::string subject = msgSubject;
std::string text = msgText;
// from console, use non-existing sender
MailSender sender(MAIL_NORMAL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetGUID().GetCounter() : 0, MAIL_STATIONERY_GM);
@todo Fix poor design
SQLTransaction trans = CharacterDatabase.BeginTransaction();
MailDraft(subject, text)
.SendMailTo(trans, MailReceiver(target, targetGuid.GetCounter()), sender);
CharacterDatabase.CommitTransaction(trans);
std::string nameLink = handler->playerLink(targetName);
handler->PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str());
return true;
}
// Send items by mail
static bool <API key>(ChatHandler* handler, char const* args)
{
// format: name "subject text" "mail text" item1[:count1] item2[:count2] ... item12[:count12]
Player* receiver;
ObjectGuid receiverGuid;
std::string receiverName;
if (!handler->extractPlayerTarget((char*)args, &receiver, &receiverGuid, &receiverName))
return false;
char* tail1 = strtok(nullptr, "");
if (!tail1)
return false;
char const* msgSubject = handler->extractQuotedArg(tail1);
if (!msgSubject)
return false;
char* tail2 = strtok(nullptr, "");
if (!tail2)
return false;
char const* msgText = handler->extractQuotedArg(tail2);
if (!msgText)
return false;
// msgSubject, msgText isn't NUL after prev. check
std::string subject = msgSubject;
std::string text = msgText;
// extract items
typedef std::pair<uint32, uint32> ItemPair;
typedef std::list< ItemPair > ItemPairs;
ItemPairs items;
// get all tail string
char* tail = strtok(nullptr, "");
// get from tail next item str
while (char* itemStr = strtok(tail, " "))
{
// and get new tail
tail = strtok(nullptr, "");
// parse item str
char const* itemIdStr = strtok(itemStr, ":");
char const* itemCountStr = strtok(nullptr, " ");
uint32 itemId = atoi(itemIdStr);
if (!itemId)
return false;
ItemTemplate const* item_proto = sObjectMgr->GetItemTemplate(itemId);
if (!item_proto)
{
handler->PSendSysMessage(<API key>, itemId);
handler->SetSentErrorMessage(true);
return false;
}
uint32 itemCount = itemCountStr ? atoi(itemCountStr) : 1;
if (itemCount < 1 || (item_proto->MaxCount > 0 && itemCount > uint32(item_proto->MaxCount)))
{
handler->PSendSysMessage(<API key>, itemCount, itemId);
handler->SetSentErrorMessage(true);
return false;
}
while (itemCount > item_proto->GetMaxStackSize())
{
items.push_back(ItemPair(itemId, item_proto->GetMaxStackSize()));
itemCount -= item_proto->GetMaxStackSize();
}
items.push_back(ItemPair(itemId, itemCount));
if (items.size() > MAX_MAIL_ITEMS)
{
handler->PSendSysMessage(<API key>, MAX_MAIL_ITEMS);
handler->SetSentErrorMessage(true);
return false;
}
}
// from console show nonexisting sender
MailSender sender(MAIL_NORMAL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetGUID().GetCounter() : 0, MAIL_STATIONERY_GM);
// fill mail
MailDraft draft(subject, text);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
for (ItemPairs::const_iterator itr = items.begin(); itr != items.end(); ++itr)
{
if (Item* item = Item::CreateItem(itr->first, itr->second, handler->GetSession() ? handler->GetSession()->GetPlayer() : 0))
{
item->SaveToDB(trans); // Save to prevent being lost at next mail load. If send fails, the item will be deleted.
draft.AddItem(item);
}
}
draft.SendMailTo(trans, MailReceiver(receiver, receiverGuid.GetCounter()), sender);
CharacterDatabase.CommitTransaction(trans);
std::string nameLink = handler->playerLink(receiverName);
handler->PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str());
return true;
}
Send money by mail
static bool <API key>(ChatHandler* handler, char const* args)
{
format: name "subject text" "mail text" money
Player* receiver;
ObjectGuid receiverGuid;
std::string receiverName;
if (!handler->extractPlayerTarget((char*)args, &receiver, &receiverGuid, &receiverName))
return false;
char* tail1 = strtok(nullptr, "");
if (!tail1)
return false;
char* msgSubject = handler->extractQuotedArg(tail1);
if (!msgSubject)
return false;
char* tail2 = strtok(nullptr, "");
if (!tail2)
return false;
char* msgText = handler->extractQuotedArg(tail2);
if (!msgText)
return false;
char* moneyStr = strtok(nullptr, "");
int32 money = moneyStr ? atoi(moneyStr) : 0;
if (money <= 0)
return false;
// msgSubject, msgText isn't NUL after prev. check
std::string subject = msgSubject;
std::string text = msgText;
// from console show nonexisting sender
MailSender sender(MAIL_NORMAL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetGUID().GetCounter() : 0, MAIL_STATIONERY_GM);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
MailDraft(subject, text)
.AddMoney(money)
.SendMailTo(trans, MailReceiver(receiver, receiverGuid.GetCounter()), sender);
CharacterDatabase.CommitTransaction(trans);
std::string nameLink = handler->playerLink(receiverName);
handler->PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str());
return true;
}
Send a message to a player in game
static bool <API key>(ChatHandler* handler, char const* args)
{
- Find the player
Player* player;
if (!handler->extractPlayerTarget((char*)args, &player))
return false;
char* msgStr = strtok(nullptr, "");
if (!msgStr)
return false;
- Check if player is logging out.
if (player->GetSession()->isLogingOut())
{
handler->SendSysMessage(<API key>);
handler->SetSentErrorMessage(true);
return false;
}
- Send the message
// Use <API key> for fastest delivery.
player->GetSession()-><API key>("%s", msgStr);
player->GetSession()-><API key>("|cffff0000[Message from administrator]:|r");
// Confirmation message
std::string nameLink = handler->GetNameLink(player);
handler->PSendSysMessage(LANG_SENDMESSAGE, nameLink.c_str(), msgStr);
return true;
}
};
void <API key>()
{
new send_commandscript();
}
|
## This file is part of Invenio.
## Invenio is free software; you can redistribute it and/or
## published by the Free Software Foundation; either version 2 of the
## Invenio is distributed in the hope that it will be useful, but
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Invenio Access Control Config. """
__revision__ = \
"$Id$"
# pylint: disable=C0301
from invenio import config
from invenio.config import CFG_SITE_NAME, CFG_SITE_URL, CFG_SITE_LANG, \
CFG_SITE_SECURE_URL, <API key>, CFG_CERN_SITE, \
CFG_OPENAIRE_SITE, CFG_SITE_RECORD, CFG_INSPIRE_SITE, \
<API key>
from invenio.messages import <API key>
class <API key>(Exception):
"""Just an Exception to discover if it's a FireRole problem"""
pass
# VALUES TO BE EXPORTED
# CURRENTLY USED BY THE FILES <API key>.py <API key>.py webaccessadmin_lib.py
# name of the role giving superadmin rights
SUPERADMINROLE = 'superadmin'
# name of the webaccess webadmin role
WEBACCESSADMINROLE = 'webaccessadmin'
# name of the action allowing roles to access the web administrator interface
WEBACCESSACTION = 'cfgwebaccess'
# name of the action allowing roles to access the web administrator interface
VIEWRESTRCOLL = 'viewrestrcoll'
# name of the action allowing roles to delegate the rights to other roles
# ex: libraryadmin to delegate libraryworker
DELEGATEADDUSERROLE = 'accdelegaterole'
# max number of users to display in the drop down selects
MAXSELECTUSERS = 25
# max number of users to display in a page (mainly for user area)
MAXPAGEUSERS = 25
# default role definition, source:
<API key> = 'deny all'
# default role definition, compiled:
<API key> = (False, ())
# default role definition, compiled and serialized:
<API key> = None
# List of tags containing (multiple) emails of users who should authorize
# to access the corresponding record regardless of collection restrictions.
if CFG_CERN_SITE:
CFG_ACC_GRANT_<API key> = ['859__f', '270__m']
else:
CFG_ACC_GRANT_<API key> = ['8560_f']
if CFG_CERN_SITE:
<API key> = ['506__m']
else:
<API key> = []
# Use external source for access control?
# <API key> -- this is a dictionary with the enabled login method.
# The key is the name of the login method and the value is an instance of
# of the login method (see /help/admin/<API key>#5). Set the value
# to None if you wish to use the local Invenio authentication method.
# <API key> -- set this to the key in <API key>
# that should be considered as default login method
# <API key> -- set this to the login method name of an SSO
# login method, if any, otherwise set this to None.
# <API key> -- if <API key> was not None
# set this to the URL that should be contacted to perform an SSO logout
from invenio.external_<API key> import ExternalAuthRobot
if CFG_CERN_SITE:
from invenio import <API key> as ea_sso
<API key> = "CERN"
<API key> = <API key>
<API key> = 'https://login.cern.ch/adfs/ls/?wa=wsignout1.0'
<API key> = {
<API key> : ea_sso.ExternalAuthSSO(),
}
elif CFG_OPENAIRE_SITE:
<API key> = 'Local'
<API key> = False
<API key> = None
<API key> = {
"Local": None,
"OpenAIRE": ExternalAuthRobot(<API key>=True, use_zlib=False, <API key>="id"),
}
elif CFG_INSPIRE_SITE:
# INSPIRE specific robot configuration
<API key> = 'Local'
<API key> = False
<API key> = None
<API key> = {
"Local": None,
"Robot": ExternalAuthRobot(<API key>=True, use_zlib=False, check_user_ip=2, <API key>='personid'),
"ZRobot": ExternalAuthRobot(<API key>=True, use_zlib=True, check_user_ip=2, <API key>='personid')
}
else:
<API key> = 'Local'
<API key> = False
<API key> = None
<API key> = {
"Local": None,
"Robot": ExternalAuthRobot(<API key>=True, use_zlib=False),
"ZRobot": ExternalAuthRobot(<API key>=True, use_zlib=True)
}
# <API key>
# Temporary email address for logging in with an OpenID/OAuth provider which
# doesn't supply email address
<API key> = "%s@NOEMAIL"
# <API key>
# <API key>
# <API key>
# Choose which providers you want to use. Some providers don't supply e mail
# address, if you choose them, the users will be registered with an temporary
# email address like <API key> % randomstring
# Order of the login buttons can be changed by <API key>
# in invenio.websession_config
<API key> = [
'google',
'yahoo',
'aol',
'wordpress',
'myvidoop',
'openid',
'verisign',
'myopenid',
'myspace',
'livejournal',
'blogger'
]
<API key> = [
'twitter',
'linkedin',
'flickr'
]
<API key> = [
'facebook',
'yammer',
'foursquare',
'googleoauth2',
'instagram',
'orcid'
]
# <API key>
# identifier: (required) identifier url. {0} will be replaced by username (an
# input).
# trust_email: (optional, default: False) Some providers let their users
# change their emails on login page. If the provider doesn't let the user,
# set it True.
<API key> = {
'openid': {
'identifier': '{0}'
},
'myvidoop': {
'identifier': '{0}.myvidoop.com'
},
'google': {
'identifier': 'https:
'trust_email': True
},
'wordpress': {
'identifier': '{0}.wordpress.com'
},
'aol': {
'identifier': 'openid.aol.com/{0}',
'trust_email': True
},
'myopenid': {
'identifier': '{0}.myopenid.com'
},
'yahoo': {
'identifier': 'yahoo.com',
'trust_email': True
},
'verisign': {
'identifier': '{0}.pip.verisignlabs.com'
},
'myspace': {
'identifier': 'www.myspace.com/{0}'
},
'livejournal': {
'identifier': '{0}.livejournal.com'
},
'blogger': {
'identifier': '{0}'
}
}
# CFG_O<API key>
# !!IMPORTANT!!
# While creating an app in the provider site, the callback uri (redirect uri)
# must be in the form of :
# CFG_SITE_SECURE_URL/youraccount/login?login_method=oauth1&provider=PROVIDERNAME
# consumer_key: required
# Consumer key taken from provider.
# consumer_secret: required
# Consumer secret taken from provider.
# authorize_url: required
# The url to redirect the user for authorization
# <API key>: optional
# Additional parameters for authorize_url (ie. scope)
# request_token_url: required
# The url to get request token
# access_token_url: required
# The url to exchange the request token with the access token
# request_url: optional
# The url to gather the user information
# request_parameters: optional
# Additional parameters for request_url
# email, nickname: optional
# id: required
# The location where these properties in the response returned from the
# provider.
# example:
# if the response is:
# 'user': {
# 'user_name': 'ABC',
# 'contact': [
# 'email': 'abc@def.com'
# 'user_id': 'XXX',
# then:
# email must be : ['user', 'contact', 0, 'email']
# id must be: ['user_id']
# nickname must be: ['user', 'user_name']
# debug: optional
# When debug key is set to 1, after login process, the json object
# returned from provider is displayed on the screen. It may be used
# for finding where the id, email or nickname is.
CFG_O<API key> = {
'twitter': {
'consumer_key' : '',
'consumer_secret' : '',
'request_token_url' : 'https://api.twitter.com/oauth/request_token',
'access_token_url' : 'https://api.twitter.com/oauth/access_token',
'authorize_url' : 'https://api.twitter.com/oauth/authorize',
'id': ['user_id'],
'nickname': ['screen_name']
},
'flickr': {
'consumer_key' : '',
'consumer_secret' : '',
'request_token_url' : 'http:
'access_token_url' : 'http:
'authorize_url' : 'http:
'<API key>: {
'perms': 'read'
},
'nickname': ['username'],
'id': ['user_nsid']
},
'linkedin': {
'consumer_key' : '',
'consumer_secret' : '',
'request_token_url' : 'https://api.linkedin.com/uas/oauth/requestToken',
'access_token_url' : 'https://api.linkedin.com/uas/oauth/accessToken',
'authorize_url' : 'https:
'request_url': 'http://api.linkedin.com/v1/people/~:(id)',
'request_parameters': {
'format': 'json'
},
'id': ['id']
}
}
# CFG_O<API key>
# !!IMPORTANT!!
# While creating an app in the provider site, the callback uri (redirect uri)
# must be in the form of :
# CFG_SITE_SECURE_URL/youraccount/login?login_method=oauth2&provider=PROVIDERNAME
# consumer_key: required
# Consumer key taken from provider.
# consumer_secret: required
# Consumer secret taken from provider.
# authorize_url: required
# The url to redirect the user for authorization
# <API key>:
# Additional parameters for authorize_url (like scope)
# access_token_url: required
# The url to get the access token.
# request_url: required
# The url to gather the user information.
# {access_token} will be replaced by access token
# email, nickname: optional
# id: required
# The location where these properties in the response returned from the
# provider.
# !! See the example in CFG_O<API key> !!
# debug: optional
# When debug key is set to 1, after login process, the json object
# returned from provider is displayed on the screen. It may be used
# for finding where the id, email or nickname is.
CFG_O<API key> = {
'facebook': {
'<TwitterConsumerkey>',
'consumer_<API key>,
'access_token_url': 'https://graph.facebook.com/oauth/access_token',
'authorize_url': 'https:
'<API key>: {
'scope': 'email'
},
'request_url' : 'https://graph.facebook.com/me?access_token={access_token}',
'email': ['email'],
'id': ['id'],
'nickname': ['username']
},
'foursquare': {
'consumer_key': '',
'consumer_secret': '',
'access_token_url': 'https://foursquare.com/oauth2/access_token',
'authorize_url': 'https://foursquare.com/oauth2/authorize',
'request_url': 'https://api.foursquare.com/v2/users/self?oauth_token={access_token}',
'id': ['response', 'user', 'id'],
'email': ['response', 'user', 'contact' ,'email']
},
'yammer': {
'consumer_key': '',
'consumer_secret': '',
'access_token_url': 'https:
'authorize_url': 'https:
'request_url': 'https:
'email':['user', 'contact', 'email_addresses', 0, 'address'],
'id': ['user', 'id'],
'nickname': ['user', 'name']
},
'googleoauth2': {
'consumer_key': '',
'consumer_secret': '',
'access_token_url': 'https://accounts.google.com/o/oauth2/token',
'authorize_url': 'https://accounts.google.com/o/oauth2/auth',
'<API key>: {
'scope': 'https:
},
'request_url': 'https:
'email':['email'],
'id': ['id']
},
'instagram': {
'consumer_key': '',
'consumer_secret': '',
'access_token_url': 'https://api.instagram.com/oauth/access_token',
'authorize_url': 'https://api.instagram.com/oauth/authorize/',
'<API key>: {
'scope': 'basic'
},
'id': ['user', 'id'],
'nickname': ['user', 'username']
},
'orcid': {
'consumer_key': '',
'consumer_secret': '',
'authorize_url': 'http://sandbox-1.orcid.org/oauth/authorize',
'access_token_url': 'http://api.sandbox-1.orcid.org/oauth/token',
'request_url': 'http://api.sandbox-1.orcid.org/{id}/orcid-profile',
'<API key>: {
'scope': '/orcid-profile/read-limited',
'response_type': 'code',
'access_type': 'offline',
},
'id': ['orcid'],
}
}
## Let's override OpenID/OAuth1/OAuth2 configuration from invenio(-local).conf
<API key> = config.<API key>
<API key> = config.<API key>
<API key> = config.<API key>
if config.<API key>:
for provider, configuration in config.<API key>.items():
if provider in <API key>:
<API key>[provider].update(configuration)
else:
<API key>[provider] = configuration
if config.CFG_O<API key>:
for provider, configuration in config.CFG_O<API key>.items():
if provider in CFG_O<API key>:
CFG_O<API key>[provider].update(configuration)
else:
CFG_O<API key>[provider] = configuration
if config.CFG_O<API key>:
for provider, configuration in config.CFG_O<API key>.items():
if provider in CFG_O<API key>:
CFG_O<API key>[provider].update(configuration)
else:
CFG_O<API key>[provider] = configuration
# If OpenID authentication is enabled, add 'openid' to login methods
<API key> = bool(<API key>)
if <API key>:
from invenio.external_<API key> import ExternalOpenID
<API key>['openid'] = ExternalOpenID(<API key>=True)
# If OAuth1 authentication is enabled, add 'oauth1' to login methods.
CFG_O<API key> = bool(<API key>)
if <API key>:
from invenio.external_<API key> import ExternalOAuth1
<API key>['oauth1'] = ExternalOAuth1(<API key>=True)
# If OAuth2 authentication is enabled, add 'oauth2' to login methods.
CFG_O<API key> = bool(<API key>)
if CFG_O<API key>:
from invenio.external_<API key> import ExternalOAuth2
<API key>['oauth2'] = ExternalOAuth2(<API key>=True)
## If using SSO, this is the number of seconds after which the keep-alive
## SSO handler is pinged again to provide fresh SSO information.
<API key> = 600
# default data for the <API key> function
# Note: by default the definition is set to deny any. This won't be a problem
# because userid directly connected with roles will still be allowed.
# roles
# name description definition
DEF_ROLES = ((SUPERADMINROLE, 'superuser with all rights', 'deny any'),
(WEBACCESSADMINROLE, 'WebAccess administrator', 'deny any'),
('anyuser', 'Any user', 'allow any'),
('basketusers', 'Users who can use baskets', 'allow any'),
('loanusers', 'Users who can use loans', 'allow any'),
('groupusers', 'Users who can use groups', 'allow any'),
('alertusers', 'Users who can use alerts', 'allow any'),
('messageusers', 'Users who can use messages', 'allow any'),
('holdingsusers', 'Users who can view holdings', 'allow any'),
('statisticsusers', 'Users who can view statistics', 'allow any'),
('claimpaperusers', 'Users who can perform changes to their own paper attributions without the need for an operator\'s approval', 'allow any'),
('claimpaperoperators', 'Users who can perform changes to _all_ paper attributions without the need for an operator\'s approval', 'deny any'),
('paperclaimviewers', 'Users who can view "claim my paper" facilities.', 'allow all'),
('<API key>', 'Users who can view "attribute this paper" facilities', 'allow all'),
('<API key>', 'Users who can see attribution links in the search', 'allow all'),
)
# Demo site roles
DEF_DEMO_ROLES = (('photocurator', 'Photo collection curator', 'deny any'),
('thesesviewer', 'Theses and Drafts viewer', 'allow group "Theses and Drafts viewers"'),
('ALEPHviewer', 'ALEPH viewer', 'allow group "ALEPH viewers"'),
('ISOLDEnotesviewer', 'ISOLDE Internal Notes viewer', 'allow group "ISOLDE Internal Notes viewers"'), ('thesescurator', 'Theses collection curator', 'deny any'),
('swordcurator', 'BibSword client curator', 'deny any'),
('referee_DEMOBOO_*', 'Book collection curator', 'deny any'),
('<API key>', 'Restricted pictures viewer', 'deny any'),
('curator', 'Curator', 'deny any'),
('basketusers', 'Users who can use baskets', 'deny email "hyde@cds.cern.ch"\nallow any'),
('claimpaperusers', 'Users who can perform changes to their own paper attributions without the need for an operator\'s approval', 'deny email "hyde@cds.cern.ch"\nallow any'),
('submit_DEMOJRN_*', 'Users who can submit (and modify) "Atlantis Times" articles', 'deny all'),
('atlantiseditor', 'Users who can configure "Atlantis Times" journal', 'deny all'),
('commentmoderator', 'Users who can moderate comments', 'deny all'),
('poetrycommentreader', 'Users who can view comments in Poetry collection', 'deny all'))
DEF_DEMO_USER_ROLES = (('jekyll@cds.cern.ch', 'thesesviewer'),
('balthasar.montague@cds.cern.ch', 'ALEPHviewer'),
('dorian.gray@cds.cern.ch', 'ISOLDEnotesviewer'),
('jekyll@cds.cern.ch', 'swordcurator'),
('jekyll@cds.cern.ch', 'claimpaperusers'),
('dorian.gray@cds.cern.ch', 'referee_DEMOBOO_*'),
('balthasar.montague@cds.cern.ch', 'curator'),
('romeo.montague@cds.cern.ch', '<API key>'),
('romeo.montague@cds.cern.ch', 'swordcurator'),
('romeo.montague@cds.cern.ch', 'thesescurator'),
('juliet.capulet@cds.cern.ch', '<API key>'),
('juliet.capulet@cds.cern.ch', 'photocurator'),
('romeo.montague@cds.cern.ch', 'submit_DEMOJRN_*'),
('juliet.capulet@cds.cern.ch', 'submit_DEMOJRN_*'),
('balthasar.montague@cds.cern.ch', 'atlantiseditor'),
('romeo.montague@cds.cern.ch', 'poetrycommentreader'))
# users
# list of e-mail addresses
DEF_USERS = []
# actions
# name desc allowedkeywords optional
DEF_ACTIONS = (
('cfgwebsearch', 'configure WebSearch', '', 'no'),
('cfgbibformat', 'configure BibFormat', '', 'no'),
('cfgbibknowledge', 'configure BibKnowledge', '', 'no'),
('cfgwebsubmit', 'configure WebSubmit', '', 'no'),
('cfgbibrank', 'configure BibRank', '', 'no'),
('cfgwebcomment', 'configure WebComment', '', 'no'),
('cfgweblinkback', 'configure WebLinkback' , '', 'no'),
('cfgoaiharvest', 'configure OAI Harvest', '', 'no'),
('cfgoairepository', 'configure OAI Repository', '', 'no'),
('cfgbibindex', 'configure BibIndex', '', 'no'),
('cfgbibexport', 'configure BibExport', '', 'no'),
('cfgrobotkeys', 'configure Robot keys', 'login_method,robot', 'yes'),
('cfgbibsort', 'configure BibSort', '', 'no'),
('runbibindex', 'run BibIndex', '', 'no'),
('runbibupload', 'run BibUpload', '', 'no'),
('runwebcoll', 'run webcoll', 'collection', 'yes'),
('runbibformat', 'run BibFormat', 'format', 'yes'),
('runbibclassify', 'run BibClassify', 'taxonomy', 'yes'),
('runbibtaskex', 'run BibTaskEx example', '', 'no'),
('runbibrank', 'run BibRank', '', 'no'),
('runoaiharvest', 'run oaiharvest task', '', 'no'),
('runoairepository', 'run <API key> task', '', 'no'),
('runbibedit', 'run Record Editor', 'collection', 'yes'),
('runbibeditmulti', 'run Multi-Record Editor', '', 'no'),
('runbibdocfile', 'run Document File Manager', '', 'no'),
('runbibmerge', 'run Record Merger', '', 'no'),
('runbibswordclient', 'run BibSword client', '', 'no'),
('runwebstatadmin', 'run WebStadAdmin', '', 'no'),
('runinveniogc', 'run InvenioGC', '', 'no'),
('runbibexport', 'run BibExport', '', 'no'),
('referee', 'referee document type doctype/category categ', 'doctype,categ', 'yes'),
('submit', 'use webSubmit', 'doctype,act,categ', 'yes'),
('viewrestrdoc', 'view restricted document', 'status', 'no'),
('viewrestrcomment', 'view restricted comment', 'status', 'no'),
(WEBACCESSACTION, 'configure WebAccess', '', 'no'),
(DELEGATEADDUSERROLE, 'delegate subroles inside WebAccess', 'role', 'no'),
(VIEWRESTRCOLL, 'view restricted collection', 'collection', 'no'),
('cfgwebjournal', 'configure WebJournal', 'name,with_editor_rights', 'no'),
('viewcomment', 'view comments', 'collection', 'no'),
('viewlinkbacks', 'view linkbacks', 'collection', 'no'),
('sendcomment', 'send comments', 'collection', 'no'),
('attachcommentfile', 'attach files to comments', 'collection', 'no'),
('<API key>', 'upload files to drop box during submission', '', 'no'),
('cfgbibexport', 'configure BibExport', '', 'no'),
('runbibexport', 'run BibExport', '', 'no'),
('usebaskets', 'use baskets', '', 'no'),
('useloans', 'use loans', '', 'no'),
('usegroups', 'use groups', '', 'no'),
('usealerts', 'use alerts', '', 'no'),
('usemessages', 'use messages', '', 'no'),
('viewholdings', 'view holdings', 'collection', 'yes'),
('viewstatistics', 'view statistics', 'collection', 'yes'),
('runbibcirculation', 'run BibCirculation', '', 'no'),
('moderatecomments', 'moderate comments', 'collection', 'no'),
('moderatelinkbacks', 'moderate linkbacks', 'collection', 'no'),
('runbatchuploader', 'run batchuploader', 'collection', 'yes'),
('runbibtasklet', 'run BibTaskLet', '', 'no'),
('<API key>', 'View the Claim Paper interface', '', 'no'),
('<API key>', 'Clam papers to his own personID', '', 'no'),
('<API key>', 'Claim papers for others', '', 'no'),
('<API key>', 'Change data associated to his own person ID', '', 'no'),
('<API key>', 'Change data of any person ID', '', 'no'),
('runbibtasklet', 'run BibTaskLet', '', 'no'),
('cfgbibsched', 'configure BibSched', '', 'no')
)
# Default authorizations
# role action arguments
DEF_AUTHS = (('basketusers', 'usebaskets', {}),
('loanusers', 'useloans', {}),
('groupusers', 'usegroups', {}),
('alertusers', 'usealerts', {}),
('messageusers', 'usemessages', {}),
('holdingsusers', 'viewholdings', {}),
('statisticsusers', 'viewstatistics', {}),
('claimpaperusers', '<API key>', {}),
('claimpaperoperators', '<API key>', {}),
('claimpaperusers', '<API key>', {}),
('claimpaperoperators', '<API key>', {}),
('claimpaperoperators', '<API key>', {}),
('claimpaperusers', '<API key>', {}),
('claimpaperoperators', '<API key>', {}),
('claimpaperoperators', '<API key>', {}),
)
# Demo site authorizations
# role action arguments
DEF_DEMO_AUTHS = (
('photocurator', 'runwebcoll', {'collection': 'Pictures'}),
('<API key>', 'viewrestrdoc', {'status': 'restricted_picture'}),
('thesesviewer', VIEWRESTRCOLL, {'collection': 'Theses'}),
('thesesviewer', VIEWRESTRCOLL, {'collection': 'Drafts'}),
('ALEPHviewer', VIEWRESTRCOLL, {'collection': 'ALEPH Theses'}),
('ALEPHviewer', VIEWRESTRCOLL, {'collection': 'ALEPH Internal Notes'}),
('ISOLDEnotesviewer', VIEWRESTRCOLL, {'collection': 'ISOLDE Internal Notes'}),
('referee_DEMOBOO_*', 'referee', {'doctype': 'DEMOBOO', 'categ': '*'}),
('curator', 'cfgbibknowledge', {}),
('curator', 'runbibedit', {}),
('curator', 'runbibeditmulti', {}),
('curator', 'runbibmerge', {}),
('swordcurator', 'runbibswordclient', {}),
('thesescurator', 'runbibedit', {'collection': 'Theses'}),
('thesescurator', VIEWRESTRCOLL, {'collection': 'Theses'}),
('photocurator', 'runbibedit', {'collection': 'Pictures'}),
('referee_DEMOBOO_*', 'runbibedit', {'collection': 'Books'}),
('submit_DEMOJRN_*', 'submit', {'doctype': 'DEMOJRN', 'act': 'SBI', 'categ': '*'}),
('submit_DEMOJRN_*', 'submit', {'doctype': 'DEMOJRN', 'act': 'MBI', 'categ': '*'}),
('submit_DEMOJRN_*', 'cfgwebjournal', {'name': 'AtlantisTimes', 'with_editor_rights': 'no'}),
('atlantiseditor', 'cfgwebjournal', {'name': 'AtlantisTimes', 'with_editor_rights': 'yes'}),
('referee_DEMOBOO_*', 'runbatchuploader', {'collection': 'Books'}),
('poetrycommentreader', 'viewcomment', {'collection': 'Poetry'}),
('atlantiseditor', VIEWRESTRCOLL, {'collection': 'Atlantis Times Drafts'}),
('anyuser', 'submit', {'doctype': 'DEMOART', 'act': 'SBI', 'categ': 'ARTICLE'}),
)
_ = <API key>(CFG_SITE_LANG)
# Activities (i.e. actions) for which exists an administrative web interface.
<API key> = {
'runbibedit' : (_("Run Record Editor"), "%s/%s/edit/?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)),
'runbibeditmulti' : (_("Run Multi-Record Editor"), "%s/%s/multiedit/?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)),
'runbibdocfile' : (_("Run Document File Manager"), "%s/%s/managedocfiles?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)),
'runbibmerge' : (_("Run Record Merger"), "%s/%s/merge/?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)),
'runbibswordclient' : (_("Run BibSword client"), "%s/bibsword/?ln=%%s" % CFG_SITE_URL),
'cfgbibknowledge' : (_("Configure BibKnowledge"), "%s/kb?ln=%%s" % CFG_SITE_URL),
'cfgbibformat' : (_("Configure BibFormat"), "%s/admin/bibformat/bibformatadmin.py?ln=%%s" % CFG_SITE_URL),
'cfgoaiharvest' : (_("Configure OAI Harvest"), "%s/admin/oaiharvest/oaiharvestadmin.py?ln=%%s" % CFG_SITE_URL),
'cfgoairepository' : (_("Configure OAI Repository"), "%s/admin/oairepository/oairepositoryadmin.py?ln=%%s" % CFG_SITE_URL),
'cfgbibindex' : (_("Configure BibIndex"), "%s/admin/bibindex/bibindexadmin.py?ln=%%s" % CFG_SITE_URL),
'cfgbibrank' : (_("Configure BibRank"), "%s/admin/bibrank/bibrankadmin.py?ln=%%s" % CFG_SITE_URL),
'cfgwebaccess' : (_("Configure WebAccess"), "%s/admin/webaccess/webaccessadmin.py?ln=%%s" % CFG_SITE_URL),
'cfgwebcomment' : (_("Configure WebComment"), "%s/admin/webcomment/webcommentadmin.py?ln=%%s" % CFG_SITE_URL),
'cfgweblinkback' : (_("Configure WebLinkback"), "%s/admin/weblinkback/weblinkbackadmin.py?ln=%%s" % CFG_SITE_URL),
'cfgwebsearch' : (_("Configure WebSearch"), "%s/admin/websearch/websearchadmin.py?ln=%%s" % CFG_SITE_URL),
'cfgwebsubmit' : (_("Configure WebSubmit"), "%s/admin/websubmit/websubmitadmin.py?ln=%%s" % CFG_SITE_URL),
'cfgwebjournal' : (_("Configure WebJournal"), "%s/admin/webjournal/webjournaladmin.py?ln=%%s" % CFG_SITE_URL),
'cfgbibsort' : (_("Configure BibSort"), "%s/admin/bibsort/bibsortadmin.py?ln=%%s" % CFG_SITE_URL),
'runbibcirculation' : (_("Run BibCirculation"), "%s/admin/bibcirculation/bibcirculationadmin.py?ln=%%s" % CFG_SITE_URL),
'runbatchuploader' : (_("Run Batch Uploader"), "%s/batchuploader/metadata?ln=%%s" % CFG_SITE_URL),
'<API key>' : (_("Run Person/Author Manager"), "%s/person/search?ln=%%s" % CFG_SITE_URL)
}
CFG_WEBACCESS_MSGS = {
0: 'Try to <a href="%s/youraccount/login?referer=%%s">login</a> with another account.' % (CFG_SITE_SECURE_URL),
1: '<br />If you think this is not correct, please contact: <a href="mailto:%s">%s</a>' % (<API key>, <API key>),
2: '<br />If you have any questions, please write to <a href="mailto:%s">%s</a>' % (<API key>, <API key>),
3: 'Guest users are not allowed, please <a href="%s/youraccount/login">login</a>.' % CFG_SITE_SECURE_URL,
4: 'The site is temporarily closed for maintenance. Please come back soon.',
5: 'Authorization failure',
6: '%s temporarily closed' % CFG_SITE_NAME,
7: 'This functionality is temporarily closed due to server maintenance. Please use only the search engine in the meantime.',
8: 'Functionality temporarily closed'
}
<API key> = {
0: 'Authorization granted',
1: 'You are not authorized to perform this action.',
2: 'You are not authorized to perform any action.',
3: 'The action %s does not exist.',
4: 'Unexpected error occurred.',
5: 'Missing mandatory keyword argument(s) for this action.',
6: 'Guest accounts are not authorized to perform this action.',
7: 'Not enough arguments, user ID and action name required.',
8: 'Incorrect keyword argument(s) for this action.',
9: """Account '%s' is not yet activated.""",
10: """You were not authorized by the authentication method '%s'.""",
11: """The selected login method '%s' is not the default method for this account, please try another one.""",
12: """Selected login method '%s' does not exist.""",
13: """Could not register '%s' account.""",
14: """Could not login using '%s', because this user is unknown.""",
15: """Could not login using your '%s' account, because you have introduced a wrong password.""",
16: """External authentication troubles using '%s' (maybe temporary network problems).""",
17: """You have not yet confirmed the email address for the '%s' authentication method.""",
18: """The administrator has not yet activated your account for the '%s' authentication method.""",
19: """The site is having troubles in sending you an email for confirming your email address. The error has been logged and will be taken care of as soon as possible.""",
20: """No roles are authorized to perform action %s with the given parameters.""",
21: """Verification cancelled""",
22: """Verification failed. Please try again or use another provider to login""",
23: """Verification failed. It is probably because the configuration isn't set properly. Please contact with the <a href="mailto:%s">administator</a>""" % <API key>
}
#There are three status key that must be here: OK, REMOVED and REVOKED
#the value doesn't matter at all
<API key> = {
'OK':'OK',
'REMOVED':'REMOVED',
'REVOKED':'REVOKED',
'WARNING':'WARNING'
}
|
<?php
namespace TYPO3\CMS\Workspaces\Tests\Unit\Controller\Remote;
use Prophecy\Argument;
use Prophecy\Prophecy\ObjectProphecy;
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\FileReference;
use TYPO3\CMS\Core\Resource\ProcessedFile;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* RemoteServer test
*/
class RemoteServerTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
{
/**
* @var \TYPO3\CMS\Workspaces\Controller\Remote\RemoteServer
*/
protected $subject;
/**
* @var FileReference[]|ObjectProphecy[]
*/
protected $<API key>;
/**
* Set up
*/
protected function setUp()
{
parent::setUp();
$this->subject = $this->getAccessibleMock(\TYPO3\CMS\Workspaces\Controller\Remote\RemoteServer::class, ['__none']);
}
/**
* Tear down.
*/
protected function tearDown()
{
parent::tearDown();
unset($this->subject);
unset($this-><API key>);
}
/**
* @return array
*/
public function <API key>()
{
return [
// without thumbnails
'unchanged wo/thumbnails' => ['1,2,3,4', '1,2,3,4', false, null],
'front addition wo/thumbnails' => ['1,2,3,4', '99,1,2,3,4', false, [
'live' => '/img/1.png /img/2.png /img/3.png /img/4.png',
'differences' => '<ins>/img/99.png </ins>/img/1.png /img/2.png /img/3.png /img/4.png',
]],
'end addition wo/thumbnails' => ['1,2,3,4', '1,2,3,4,99', false, [
'live' => '/img/1.png /img/2.png /img/3.png /img/4.png',
'differences' => '/img/1.png /img/2.png /img/3.png /img/4.png <ins>/img/99.png </ins>',
]],
'reorder wo/thumbnails' => ['1,2,3,4', '1,3,2,4', false, [
'live' => '/img/1.png /img/2.png /img/3.png /img/4.png',
'differences' => '/img/1.png <ins>/img/3.png </ins>/img/2.png <del>/img/3.png </del>/img/4.png',
]],
'move to end wo/thumbnails' => ['1,2,3,4', '2,3,4,1', false, [
'live' => '/img/1.png /img/2.png /img/3.png /img/4.png',
'differences' => '<del>/img/1.png </del>/img/2.png /img/3.png /img/4.png <ins>/img/1.png </ins>',
]],
'move to front wo/thumbnails' => ['1,2,3,4', '4,1,2,3', false, [
'live' => '/img/1.png /img/2.png /img/3.png /img/4.png',
'differences' => '<ins>/img/4.png </ins>/img/1.png /img/2.png /img/3.png <del>/img/4.png </del>',
]],
'keep last wo/thumbnails' => ['1,2,3,4', '4', false, [
'live' => '/img/1.png /img/2.png /img/3.png /img/4.png',
'differences' => '<del>/img/1.png /img/2.png /img/3.png </del>/img/4.png',
]],
// with thumbnails
'unchanged w/thumbnails' => ['1,2,3,4', '1,2,3,4', true, null],
'front addition w/thumbnails' => ['1,2,3,4', '99,1,2,3,4', true, [
'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />',
'differences' => '<ins><img src="/tmb/99.png" /> </ins><img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />',
]],
'end addition w/thumbnails' => ['1,2,3,4', '1,2,3,4,99', true, [
'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />',
'differences' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" /> <ins><img src="/tmb/99.png" /> </ins>',
]],
'reorder w/thumbnails' => ['1,2,3,4', '1,3,2,4', true, [
'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />',
'differences' => '<img src="/tmb/1.png" /> <ins><img src="/tmb/3.png" /> </ins><img src="/tmb/2.png" /> <del><img src="/tmb/3.png" /> </del><img src="/tmb/4.png" />',
]],
'move to end w/thumbnails' => ['1,2,3,4', '2,3,4,1', true, [
'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />',
'differences' => '<del><img src="/tmb/1.png" /> </del><img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" /> <ins><img src="/tmb/1.png" /> </ins>',
]],
'move to front w/thumbnails' => ['1,2,3,4', '4,1,2,3', true, [
'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />',
'differences' => '<ins><img src="/tmb/4.png" /> </ins><img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <del><img src="/tmb/4.png" /> </del>',
]],
'keep last w/thumbnails' => ['1,2,3,4', '4', true, [
'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />',
'differences' => '<del><img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> </del><img src="/tmb/4.png" />',
]],
];
}
/**
* @param string $<API key>
* @param string $<API key>
* @param $useThumbnails
* @param array|null $expected
* @dataProvider <API key>
* @test
*/
public function <API key>($<API key>, $<API key>, $useThumbnails, array $expected = null)
{
$liveFileReferences = $this-><API key>($<API key>);
$<API key> = $this-><API key>($<API key>);
$result = $this->subject->_call(
'<API key>',
$liveFileReferences,
$<API key>,
$useThumbnails
);
$this->assertSame($expected, $result);
}
/**
* @param string $idList List of ids
* @return FileReference[]|ObjectProphecy[]
*/
protected function <API key>($idList)
{
$<API key> = [];
$ids = GeneralUtility::trimExplode(',', $idList, true);
foreach ($ids as $id) {
$<API key>[$id] = $this-><API key>($id);
}
return $<API key>;
}
/**
* @param int $id
* @return ObjectProphecy|FileReference
*/
protected function <API key>($id)
{
if (isset($this-><API key>[$id])) {
return $this-><API key>[$id];
}
$<API key> = $this->prophesize(ProcessedFile::class);
$<API key>->getPublicUrl(Argument::cetera())->willReturn('/tmb/' . $id . '.png');
$fileProphecy = $this->prophesize(File::class);
$fileProphecy->process(Argument::cetera())->willReturn($<API key>->reveal());
$<API key> = $this->prophesize(FileReference::class);
$<API key>->getUid()->willReturn($id);
$<API key>->getOriginalFile()->willReturn($fileProphecy->reveal());
$<API key>->getPublicUrl(Argument::cetera())->willReturn('/img/' . $id . '.png');
$this-><API key>[$id] = $<API key>->reveal();
return $this-><API key>[$id];
}
}
|
<?php
namespace VuFind\Record\FallbackLoader;
use SerialsSolutions\Summon\Zend2 as Connector;
use VuFind\Db\Table\Resource;
use VuFindSearch\Backend\Summon\Backend;
use VuFindSearch\ParamBag;
class Summon implements <API key>
{
/**
* Resource table
*
* @var Resource
*/
protected $table;
/**
* Summon backend
*
* @var Backend
*/
protected $backend;
/**
* Constructor
*
* @param Resource $table Resource database table object
* @param Backend $backend Summon search backend
*/
public function __construct(Resource $table, Backend $backend)
{
$this->table = $table;
$this->backend = $backend;
}
/**
* Given an array of IDs that failed to load, try to find them using a
* fallback mechanism.
*
* @param array $ids IDs to load
*
* @return array
*/
public function load($ids)
{
$retVal = [];
foreach ($ids as $id) {
foreach ($this->fetchSingleRecord($id) as $record) {
$this->updateRecord($record, $id);
$retVal[] = $record;
}
}
return $retVal;
}
/**
* Fetch a single record (null if not found).
*
* @param string $id ID to load
*
* @return \VuFindSearch\Response\<API key>
*/
protected function fetchSingleRecord($id)
{
$resource = $this->table->findResource($id, 'Summon');
if ($resource && ($extra = json_decode($resource->extra_metadata, true))) {
$bookmark = $extra['bookmark'] ?? '';
if (strlen($bookmark) > 0) {
$params = new ParamBag(
['summonIdType' => Connector::IDENTIFIER_BOOKMARK]
);
return $this->backend->retrieve($bookmark, $params);
}
}
return new \VuFindSearch\Backend\Summon\Response\RecordCollection([]);
}
/**
* When a record ID has changed, update the record driver and database to
* reflect the changes.
*
* @param \VuFind\RecordDriver\AbstractBase $record Record to update
* @param string $previousId Old ID of record
*
* @return void
*/
protected function updateRecord($record, $previousId)
{
// Update the record driver with knowledge of the previous identifier...
$record->setPreviousUniqueId($previousId);
// Update the database to replace the obsolete identifier...
$this->table->updateRecordId($previousId, $record->getUniqueId(), 'Summon');
}
}
|
<?php
$content = "";
$content .= '<div id="' . str_replace('_', '-', $box_id . 'Content') . '" class="sideBoxContent">' . "\n";
$content .= '<ul class="list-links orderHistList">' . "\n" ;
foreach ($customer_orders as $row) {
$content .= '
<li>
<a href="' . zen_href_link(zen_get_info_page($row['id']), 'products_id=' . $row['id']) . '">' . $row['name'] . '</a>
<a href="' . zen_href_link($_GET['main_page'], <API key>(array('action')) . 'action=cust_order&pid=' . $row['id']) . '"><i class="fa fa-cart-arrow-down"></i></a>
</li>
';
}
$content .= '</ul>' . "\n" ;
$content .= '</div>';
|
#include "expire-tiles.hpp"
#include "options.hpp"
#include <iterator>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdexcept>
#include <boost/format.hpp>
#include <set>
#define EARTH_CIRCUMFERENCE (40075016.68)
namespace {
void run_test(const char* test_name, void (*testfunc)())
{
try
{
fprintf(stderr, "%s\n", test_name);
testfunc();
}
catch(const std::exception& e)
{
fprintf(stderr, "%s\n", e.what());
fprintf(stderr, "FAIL\n");
exit(EXIT_FAILURE);
}
fprintf(stderr, "PASS\n");
}
#define RUN_TEST(x) run_test(#x, &(x))
#define ASSERT_EQ(a, b) { if (!((a) == (b))) { throw std::runtime_error((boost::format("Expecting %1% == %2%, but %3% != %4%") % #a % #b % (a) % (b)).str()); } }
struct xyz {
int z, x, y;
xyz(int z_, int x_, int y_) : z(z_), x(x_), y(y_) {}
bool operator==(const xyz &other) const {
return ((z == other.z) &&
(x == other.x) &&
(y == other.y));
}
bool operator<(const xyz &other) const {
return ((z < other.z) ||
((z == other.z) &&
((x < other.x) ||
((x == other.x) &&
(y < other.y)))));
}
void to_bbox(double &x0, double &y0,
double &x1, double &y1) const {
const double datum = 0.5 * (1 << z);
const double scale = EARTH_CIRCUMFERENCE / (1 << z);
x0 = (x - datum) * scale;
y0 = (datum - (y + 1)) * scale;
x1 = ((x + 1) - datum) * scale;
y1 = (datum - y) * scale;
}
void to_centroid(double &x0, double &y0) const {
const double datum = 0.5 * (1 << z);
const double scale = EARTH_CIRCUMFERENCE / (1 << z);
x0 = ((x + 0.5) - datum) * scale;
y0 = (datum - (y + 0.5)) * scale;
}
};
std::ostream &operator<<(std::ostream &out, const xyz &tile) {
out << tile.z << "/" << tile.x << "/" << tile.y;
return out;
}
struct tile_output_set : public expire_tiles::tile_output {
tile_output_set() {}
virtual ~tile_output_set() {}
virtual void output_dirty_tile(int x, int y, int zoom, int min_zoom) {
int y_min, x_iter, y_iter, x_max, y_max, out_zoom, zoom_diff;
if (zoom > min_zoom) out_zoom = zoom;
else out_zoom = min_zoom;
zoom_diff = out_zoom - zoom;
y_min = y << zoom_diff;
x_max = (x + 1) << zoom_diff;
y_max = (y + 1) << zoom_diff;
for (x_iter = x << zoom_diff; x_iter < x_max; x_iter++) {
for (y_iter = y_min; y_iter < y_max; y_iter++) {
m_tiles.insert(xyz(out_zoom, x_iter, y_iter));
}
}
}
std::set<xyz> m_tiles;
};
void <API key>() {
options_t opt;
opt.expire_tiles_zoom = 1;
opt.<API key> = 1;
expire_tiles et(&opt);
tile_output_set set;
// as big a bbox as possible at the origin to dirty all four
// quadrants of the world.
et.from_bbox(-10000, -10000, 10000, 10000);
et.output_and_destroy(&set);
ASSERT_EQ(set.m_tiles.size(), 4);
std::set<xyz>::iterator itr = set.m_tiles.begin();
ASSERT_EQ(*itr, xyz(1, 0, 0)); ++itr;
ASSERT_EQ(*itr, xyz(1, 0, 1)); ++itr;
ASSERT_EQ(*itr, xyz(1, 1, 0)); ++itr;
ASSERT_EQ(*itr, xyz(1, 1, 1)); ++itr;
}
void <API key>() {
options_t opt;
opt.expire_tiles_zoom = 3;
opt.<API key> = 3;
expire_tiles et(&opt);
tile_output_set set;
// as big a bbox as possible at the origin to dirty all four
// quadrants of the world.
et.from_bbox(-10000, -10000, 10000, 10000);
et.output_and_destroy(&set);
ASSERT_EQ(set.m_tiles.size(), 4);
std::set<xyz>::iterator itr = set.m_tiles.begin();
ASSERT_EQ(*itr, xyz(3, 3, 3)); ++itr;
ASSERT_EQ(*itr, xyz(3, 3, 4)); ++itr;
ASSERT_EQ(*itr, xyz(3, 4, 3)); ++itr;
ASSERT_EQ(*itr, xyz(3, 4, 4)); ++itr;
}
void <API key>() {
options_t opt;
opt.expire_tiles_zoom = 18;
opt.<API key> = 18;
expire_tiles et(&opt);
tile_output_set set;
// dirty a smaller bbox this time, as at z18 the scale is
// pretty small.
et.from_bbox(-1, -1, 1, 1);
et.output_and_destroy(&set);
ASSERT_EQ(set.m_tiles.size(), 4);
std::set<xyz>::iterator itr = set.m_tiles.begin();
ASSERT_EQ(*itr, xyz(18, 131071, 131071)); ++itr;
ASSERT_EQ(*itr, xyz(18, 131071, 131072)); ++itr;
ASSERT_EQ(*itr, xyz(18, 131072, 131071)); ++itr;
ASSERT_EQ(*itr, xyz(18, 131072, 131072)); ++itr;
}
std::set<xyz> generate_random(int zoom, size_t count) {
size_t num = 0;
std::set<xyz> set;
const int coord_mask = (1 << zoom) - 1;
while (num < count) {
xyz item(zoom, rand() & coord_mask, rand() & coord_mask);
if (set.count(item) == 0) {
set.insert(item);
++num;
}
}
return set;
}
void <API key>(const std::set<xyz> &a,
const std::set<xyz> &b) {
ASSERT_EQ(a.size(), b.size());
std::set<xyz>::const_iterator a_itr = a.begin();
std::set<xyz>::const_iterator b_itr = b.begin();
while ((a_itr != a.end()) &&
(b_itr != b.end())) {
ASSERT_EQ(*a_itr, *b_itr);
++a_itr;
++b_itr;
}
}
void expire_centroids(const std::set<xyz> &check_set,
expire_tiles &et) {
for (std::set<xyz>::const_iterator itr = check_set.begin();
itr != check_set.end(); ++itr) {
double x0 = 0.0, y0 = 0.0;
itr->to_centroid(x0, y0);
et.from_bbox(x0, y0, x0, y0);
}
}
// tests that expiring a set of tile centroids means that
// those tiles get expired.
void test_expire_set() {
options_t opt;
int zoom = 18;
opt.expire_tiles_zoom = zoom;
opt.<API key> = zoom;
for (int i = 0; i < 100; ++i) {
expire_tiles et(&opt);
tile_output_set set;
std::set<xyz> check_set = generate_random(zoom, 100);
expire_centroids(check_set, et);
et.output_and_destroy(&set);
<API key>(set.m_tiles, check_set);
}
}
// this tests that, after expiring a random set of tiles
// in one expire_tiles object and a different set in
// another, when they are merged together they are the
// same as if the union of the sets of tiles had been
// expired.
void test_expire_merge() {
options_t opt;
int zoom = 18;
opt.expire_tiles_zoom = zoom;
opt.<API key> = zoom;
for (int i = 0; i < 100; ++i) {
expire_tiles et(&opt), et1(&opt), et2(&opt);
tile_output_set set;
std::set<xyz> check_set1 = generate_random(zoom, 100);
expire_centroids(check_set1, et1);
std::set<xyz> check_set2 = generate_random(zoom, 100);
expire_centroids(check_set2, et2);
et.merge_and_destroy(et1);
et.merge_and_destroy(et2);
std::set<xyz> check_set;
std::set_union(check_set1.begin(), check_set1.end(),
check_set2.begin(), check_set2.end(),
std::inserter(check_set, check_set.end()));
et.output_and_destroy(&set);
<API key>(set.m_tiles, check_set);
}
}
// tests that merging two identical sets results in
// the same set. this guarantees that we check some
// pathways of the merging which possibly could be
// skipped by the random tile set in the previous
// test.
void <API key>() {
options_t opt;
int zoom = 18;
opt.expire_tiles_zoom = zoom;
opt.<API key> = zoom;
for (int i = 0; i < 100; ++i) {
expire_tiles et(&opt), et1(&opt), et2(&opt);
tile_output_set set;
std::set<xyz> check_set = generate_random(zoom, 100);
expire_centroids(check_set, et1);
expire_centroids(check_set, et2);
et.merge_and_destroy(et1);
et.merge_and_destroy(et2);
et.output_and_destroy(&set);
<API key>(set.m_tiles, check_set);
}
}
// makes sure that we're testing the case where some
// tiles are in both.
void <API key>() {
options_t opt;
int zoom = 18;
opt.expire_tiles_zoom = zoom;
opt.<API key> = zoom;
for (int i = 0; i < 100; ++i) {
expire_tiles et(&opt), et1(&opt), et2(&opt);
tile_output_set set;
std::set<xyz> check_set1 = generate_random(zoom, 100);
expire_centroids(check_set1, et1);
std::set<xyz> check_set2 = generate_random(zoom, 100);
expire_centroids(check_set2, et2);
std::set<xyz> check_set3 = generate_random(zoom, 100);
expire_centroids(check_set3, et1);
expire_centroids(check_set3, et2);
et.merge_and_destroy(et1);
et.merge_and_destroy(et2);
std::set<xyz> check_set;
std::set_union(check_set1.begin(), check_set1.end(),
check_set2.begin(), check_set2.end(),
std::inserter(check_set, check_set.end()));
std::set_union(check_set1.begin(), check_set1.end(),
check_set3.begin(), check_set3.end(),
std::inserter(check_set, check_set.end()));
et.output_and_destroy(&set);
<API key>(set.m_tiles, check_set);
}
}
// checks that the set union still works when we expire
// large contiguous areas of tiles (i.e: ensure that we
// handle the "complete" flag correctly).
void <API key>() {
options_t opt;
int zoom = 18;
opt.expire_tiles_zoom = zoom;
opt.<API key> = zoom;
for (int i = 0; i < 100; ++i) {
expire_tiles et(&opt), et1(&opt), et2(&opt), et0(&opt);
tile_output_set set, set0;
// et1&2 are two halves of et0's box
et0.from_bbox(-10000, -10000, 10000, 10000);
et1.from_bbox(-10000, -10000, 0, 10000);
et2.from_bbox( 0, -10000, 10000, 10000);
et.merge_and_destroy(et1);
et.merge_and_destroy(et2);
et.output_and_destroy(&set);
et0.output_and_destroy(&set0);
<API key>(set.m_tiles, set0.m_tiles);
}
}
} // anonymous namespace
int main(int argc, char *argv[])
{
srand(0);
//try each test if any fail we will exit
RUN_TEST(<API key>);
RUN_TEST(<API key>);
RUN_TEST(<API key>);
RUN_TEST(test_expire_set);
RUN_TEST(test_expire_merge);
RUN_TEST(<API key>);
RUN_TEST(<API key>);
RUN_TEST(<API key>);
//passed
return 0;
}
|
#if defined HAVE_FMA4_SUPPORT || defined HAVE_AVX_SUPPORT
# include <init-arch.h>
# include <math.h>
# include <math_private.h>
extern double <API key> (double, double);
extern double __ieee754_atan2_avx (double, double);
# ifdef HAVE_FMA4_SUPPORT
extern double <API key> (double, double);
# else
# undef HAS_FMA4
# define HAS_FMA4 0
# define <API key> ((void *) 0)
# endif
libm_ifunc (__ieee754_atan2,
HAS_FMA4 ? <API key>
: (HAS_AVX ? __ieee754_atan2_avx : <API key>));
strong_alias (__ieee754_atan2, __atan2_finite)
# define __ieee754_atan2 <API key>
#endif
#include <sysdeps/ieee754/dbl-64/e_atan2.c>
|
#!/bin/bash
# Test the init code
source "$REG_DIR/scaffold"
function opts
{
cat << DONE
-a
-n
DONE
}
cmd setup_git_repo
opts | while read opt ; do
cmd reset_git_repo
cmd guilt init $opt
cmd list_files
shouldfail guilt init $opt
cmd list_files
done
cmd git branch other
cmd git checkout other
cmd guilt init
cmd list_files
shouldfail guilt init
cmd list_files
|
<?php
/**
* Customizer settings for this theme.
*
* @package WordPress
* @subpackage Twenty_Twenty
* @since Twenty Twenty 1.0
*/
if ( ! class_exists( '<API key>' ) ) {
/**
* CUSTOMIZER SETTINGS
*
* @since Twenty Twenty 1.0
*/
class <API key> {
/**
* Register customizer options.
*
* @since Twenty Twenty 1.0
*
* @param <API key> $wp_customize Theme Customizer object.
*/
public static function register( $wp_customize ) {
/**
* Site Title & Description.
* */
$wp_customize->get_setting( 'blogname' )->transport = 'postMessage';
$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
$wp_customize->selective_refresh->add_partial(
'blogname',
array(
'selector' => '.site-title a',
'render_callback' => '<API key>',
)
);
$wp_customize->selective_refresh->add_partial(
'blogdescription',
array(
'selector' => '.site-description',
'render_callback' => '<API key>',
)
);
$wp_customize->selective_refresh->add_partial(
'custom_logo',
array(
'selector' => '.header-titles [class*=site-]:not(.site-description)',
'render_callback' => '<API key>',
)
);
$wp_customize->selective_refresh->add_partial(
'retina_logo',
array(
'selector' => '.header-titles [class*=site-]:not(.site-description)',
'render_callback' => '<API key>',
)
);
/**
* Site Identity
*/
$wp_customize->add_setting(
'retina_logo',
array(
'capability' => 'edit_theme_options',
'sanitize_callback' => array( __CLASS__, 'sanitize_checkbox' ),
'transport' => 'postMessage',
)
);
$wp_customize->add_control(
'retina_logo',
array(
'type' => 'checkbox',
'section' => 'title_tagline',
'priority' => 10,
'label' => __( 'Retina logo', 'twentytwenty' ),
'description' => __( 'Scales the logo to half its uploaded size, making it sharp on high-res screens.', 'twentytwenty' ),
)
);
// Header & Footer Background Color.
$wp_customize->add_setting(
'<API key>',
array(
'default' => '#ffffff',
'sanitize_callback' => 'sanitize_hex_color',
'transport' => 'postMessage',
)
);
$wp_customize->add_control(
new <API key>(
$wp_customize,
'<API key>',
array(
'label' => __( 'Header & Footer Background Color', 'twentytwenty' ),
'section' => 'colors',
)
)
);
// Enable picking an accent color.
$wp_customize->add_setting(
'accent_hue_active',
array(
'capability' => 'edit_theme_options',
'sanitize_callback' => array( __CLASS__, 'sanitize_select' ),
'transport' => 'postMessage',
'default' => 'default',
)
);
$wp_customize->add_control(
'accent_hue_active',
array(
'type' => 'radio',
'section' => 'colors',
'label' => __( 'Primary Color', 'twentytwenty' ),
'choices' => array(
'default' => _x( 'Default', 'color', 'twentytwenty' ),
'custom' => _x( 'Custom', 'color', 'twentytwenty' ),
),
)
);
/**
* Implementation for the accent color.
* This is different to all other color options because of the accessibility enhancements.
* The control is a hue-only colorpicker, and there is a separate setting that holds values
* for other colors calculated based on the selected hue and various background-colors on the page.
*
* @since Twenty Twenty 1.0
*/
// Add the setting for the hue colorpicker.
$wp_customize->add_setting(
'accent_hue',
array(
'default' => 344,
'type' => 'theme_mod',
'sanitize_callback' => 'absint',
'transport' => 'postMessage',
)
);
// Add setting to hold colors derived from the accent hue.
$wp_customize->add_setting(
'<API key>',
array(
'default' => array(
'content' => array(
'text' => '#000000',
'accent' => '#cd2653',
'secondary' => '#6d6d6d',
'borders' => '#dcd7ca',
),
'header-footer' => array(
'text' => '#000000',
'accent' => '#cd2653',
'secondary' => '#6d6d6d',
'borders' => '#dcd7ca',
),
),
'type' => 'theme_mod',
'transport' => 'postMessage',
'sanitize_callback' => array( __CLASS__, '<API key>' ),
)
);
// Add the hue-only colorpicker for the accent color.
$wp_customize->add_control(
new <API key>(
$wp_customize,
'accent_hue',
array(
'section' => 'colors',
'settings' => 'accent_hue',
'description' => __( 'Apply a custom color for links, buttons, featured images.', 'twentytwenty' ),
'mode' => 'hue',
'active_callback' => function() use ( $wp_customize ) {
return ( 'custom' === $wp_customize->get_setting( 'accent_hue_active' )->value() );
},
)
)
);
// Update background color with postMessage, so inline CSS output is updated as well.
$wp_customize->get_setting( 'background_color' )->transport = 'postMessage';
/**
* Theme Options
*/
$wp_customize->add_section(
'options',
array(
'title' => __( 'Theme Options', 'twentytwenty' ),
'priority' => 40,
'capability' => 'edit_theme_options',
)
);
$wp_customize->add_setting(
'<API key>',
array(
'capability' => 'edit_theme_options',
'default' => true,
'sanitize_callback' => array( __CLASS__, 'sanitize_checkbox' ),
)
);
$wp_customize->add_control(
'<API key>',
array(
'type' => 'checkbox',
'section' => 'options',
'priority' => 10,
'label' => __( 'Show search in header', 'twentytwenty' ),
)
);
$wp_customize->add_setting(
'show_author_bio',
array(
'capability' => 'edit_theme_options',
'default' => true,
'sanitize_callback' => array( __CLASS__, 'sanitize_checkbox' ),
)
);
$wp_customize->add_control(
'show_author_bio',
array(
'type' => 'checkbox',
'section' => 'options',
'priority' => 10,
'label' => __( 'Show author bio', 'twentytwenty' ),
)
);
$wp_customize->add_setting(
'blog_content',
array(
'capability' => 'edit_theme_options',
'default' => 'full',
'sanitize_callback' => array( __CLASS__, 'sanitize_select' ),
)
);
$wp_customize->add_control(
'blog_content',
array(
'type' => 'radio',
'section' => 'options',
'priority' => 10,
'label' => __( 'On archive pages, posts show:', 'twentytwenty' ),
'choices' => array(
'full' => __( 'Full text', 'twentytwenty' ),
'summary' => __( 'Summary', 'twentytwenty' ),
),
)
);
/**
* Template: Cover Template.
*/
$wp_customize->add_section(
'<API key>',
array(
'title' => __( 'Cover Template', 'twentytwenty' ),
'capability' => 'edit_theme_options',
'description' => __( 'Settings for the "Cover Template" page template. Add a featured image to use as background.', 'twentytwenty' ),
'priority' => 42,
)
);
$wp_customize->add_setting(
'<API key>',
array(
'capability' => 'edit_theme_options',
'default' => true,
'sanitize_callback' => array( __CLASS__, 'sanitize_checkbox' ),
'transport' => 'postMessage',
)
);
$wp_customize->add_control(
'<API key>',
array(
'type' => 'checkbox',
'section' => '<API key>',
'label' => __( 'Fixed Background Image', 'twentytwenty' ),
'description' => __( 'Creates a parallax effect when the visitor scrolls.', 'twentytwenty' ),
)
);
$wp_customize->selective_refresh->add_partial(
'<API key>',
array(
'selector' => '.cover-header',
'type' => 'cover_fixed',
)
);
$wp_customize->add_setting(
'<API key>',
array(
'sanitize_callback' => '<API key>',
)
);
$wp_customize->add_control(
new <API key>(
$wp_customize,
'<API key>',
array(
'section' => '<API key>',
)
)
);
$wp_customize->add_setting(
'<API key>',
array(
'default' => <API key>( 'content', 'accent' ),
'sanitize_callback' => 'sanitize_hex_color',
)
);
$wp_customize->add_control(
new <API key>(
$wp_customize,
'<API key>',
array(
'label' => __( 'Overlay Background Color', 'twentytwenty' ),
'description' => __( 'The color used for the overlay. Defaults to the accent color.', 'twentytwenty' ),
'section' => '<API key>',
)
)
);
$wp_customize->add_setting(
'<API key>',
array(
'default' => '#ffffff',
'sanitize_callback' => 'sanitize_hex_color',
)
);
$wp_customize->add_control(
new <API key>(
$wp_customize,
'<API key>',
array(
'label' => __( 'Overlay Text Color', 'twentytwenty' ),
'description' => __( 'The color used for the text in the overlay.', 'twentytwenty' ),
'section' => '<API key>',
)
)
);
$wp_customize->add_setting(
'<API key>',
array(
'default' => 80,
'sanitize_callback' => 'absint',
'transport' => 'postMessage',
)
);
$wp_customize->add_control(
'<API key>',
array(
'label' => __( 'Overlay Opacity', 'twentytwenty' ),
'description' => __( 'Make sure that the contrast is high enough so that the text is readable.', 'twentytwenty' ),
'section' => '<API key>',
'type' => 'range',
'input_attrs' => <API key>(),
)
);
$wp_customize->selective_refresh->add_partial(
'<API key>',
array(
'selector' => '.cover-color-overlay',
'type' => 'cover_opacity',
)
);
}
/**
* Sanitization callback for the "<API key>" setting.
*
* @since Twenty Twenty 1.0
*
* @param array $value The value we want to sanitize.
* @return array Returns sanitized value. Each item in the array gets sanitized separately.
*/
public static function <API key>( $value ) {
// Make sure the value is an array. Do not typecast, use empty array as fallback.
$value = is_array( $value ) ? $value : array();
// Loop values.
foreach ( $value as $area => $values ) {
foreach ( $values as $context => $color_val ) {
$value[ $area ][ $context ] = sanitize_hex_color( $color_val );
}
}
return $value;
}
/**
* Sanitize select.
*
* @since Twenty Twenty 1.0
*
* @param string $input The input from the setting.
* @param object $setting The selected setting.
* @return string The input from the setting or the default setting.
*/
public static function sanitize_select( $input, $setting ) {
$input = sanitize_key( $input );
$choices = $setting->manager->get_control( $setting->id )->choices;
return ( array_key_exists( $input, $choices ) ? $input : $setting->default );
}
/**
* Sanitize boolean for checkbox.
*
* @since Twenty Twenty 1.0
*
* @param bool $checked Whether or not a box is checked.
* @return bool
*/
public static function sanitize_checkbox( $checked ) {
return ( ( isset( $checked ) && true === $checked ) ? true : false );
}
}
// Setup the Theme Customizer settings and controls.
add_action( 'customize_register', array( '<API key>', 'register' ) );
}
/**
* PARTIAL REFRESH FUNCTIONS
* */
if ( ! function_exists( '<API key>' ) ) {
/**
* Render the site title for the selective refresh partial.
*
* @since Twenty Twenty 1.0
*/
function <API key>() {
bloginfo( 'name' );
}
}
if ( ! function_exists( '<API key>' ) ) {
/**
* Render the site description for the selective refresh partial.
*
* @since Twenty Twenty 1.0
*/
function <API key>() {
bloginfo( 'description' );
}
}
if ( ! function_exists( '<API key>' ) ) {
/**
* Render the site logo for the selective refresh partial.
*
* Doing it this way so we don't have issues with `render_callback`'s arguments.
*
* @since Twenty Twenty 1.0
*/
function <API key>() {
<API key>();
}
}
/**
* Input attributes for cover overlay opacity option.
*
* @since Twenty Twenty 1.0
*
* @return array Array containing attribute names and their values.
*/
function <API key>() {
/**
* Filters the input attributes for opacity.
*
* @since Twenty Twenty 1.0
*
* @param array $attrs {
* The attributes.
*
* @type int $min Minimum value.
* @type int $max Maximum value.
* @type int $step Interval between numbers.
* }
*/
return apply_filters(
'<API key>',
array(
'min' => 0,
'max' => 90,
'step' => 5,
)
);
}
|
#ifndef DECLINFO_H
#define DECLINFO_H
#include <stdio.h>
#include <qcstring.h>
extern void parseFuncDecl(const QCString &decl,
bool objC,
QCString &clName,
QCString &type,
QCString &name,
QCString &args,
QCString &funcTempList,
QCString &exceptions
);
#endif
|
class CreateArticlePage
include PageObject
page_url '<%=params[:article_name]%>'
a(:doesnotexist_msg, text: 'Look for pages within Wikipedia that link to this title')
end
|
#include <linux/bitops.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include "dmxdev.h"
#include "dvbdev.h"
#include "dvb_demux.h"
#include "dvb_frontend.h"
#include "dvb-bt8xx.h"
#include "bt878.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off debugging (default:off).");
#define dprintk( args... ) \
do { \
if (debug) printk(KERN_DEBUG args); \
} while (0)
static void dvb_bt8xx_task(unsigned long data)
{
struct dvb_bt8xx_card *card = (struct dvb_bt8xx_card *)data;
//printk("%d ", card->bt->finished_block);
while (card->bt->last_block != card->bt->finished_block) {
(card->bt->TS_Size ? <API key> : dvb_dmx_swfilter)
(&card->demux,
&card->bt->buf_cpu[card->bt->last_block *
card->bt->block_bytes],
card->bt->block_bytes);
card->bt->last_block = (card->bt->last_block + 1) %
card->bt->block_count;
}
}
static int <API key>(struct dvb_demux_feed *dvbdmxfeed)
{
struct dvb_demux *dvbdmx = dvbdmxfeed->demux;
struct dvb_bt8xx_card *card = dvbdmx->priv;
int rc;
dprintk("dvb_bt8xx: start_feed\n");
if (!dvbdmx->dmx.frontend)
return -EINVAL;
down(&card->lock);
card->nfeeds++;
rc = card->nfeeds;
if (card->nfeeds == 1)
bt878_start(card->bt, card->gpio_mode,
card->op_sync_orin, card->irq_err_ignore);
up(&card->lock);
return rc;
}
static int dvb_bt8xx_stop_feed(struct dvb_demux_feed *dvbdmxfeed)
{
struct dvb_demux *dvbdmx = dvbdmxfeed->demux;
struct dvb_bt8xx_card *card = dvbdmx->priv;
dprintk("dvb_bt8xx: stop_feed\n");
if (!dvbdmx->dmx.frontend)
return -EINVAL;
down(&card->lock);
card->nfeeds
if (card->nfeeds == 0)
bt878_stop(card->bt);
up(&card->lock);
return 0;
}
static int is_pci_slot_eq(struct pci_dev* adev, struct pci_dev* bdev)
{
if ((adev->subsystem_vendor == bdev->subsystem_vendor) &&
(adev->subsystem_device == bdev->subsystem_device) &&
(adev->bus->number == bdev->bus->number) &&
(PCI_SLOT(adev->devfn) == PCI_SLOT(bdev->devfn)))
return 1;
return 0;
}
static struct bt878 __init *dvb_bt8xx_878_match(unsigned int bttv_nr, struct pci_dev* bttv_pci_dev)
{
unsigned int card_nr;
/* Hmm, n squared. Hope n is small */
for (card_nr = 0; card_nr < bt878_num; card_nr++) {
if (is_pci_slot_eq(bt878[card_nr].dev, bttv_pci_dev))
return &bt878[card_nr];
}
return NULL;
}
static int <API key>(struct dvb_frontend* fe)
{
static u8 mt352_clock_config [] = { 0x89, 0x38, 0x38 };
static u8 mt352_reset [] = { 0x50, 0x80 };
static u8 mt352_adc_ctl_1_cfg [] = { 0x8E, 0x40 };
static u8 mt352_agc_cfg [] = { 0x67, 0x28, 0x20 };
static u8 mt352_gpp_ctl_cfg [] = { 0x8C, 0x33 };
static u8 <API key>[] = { 0x75, 0x32 };
mt352_write(fe, mt352_clock_config, sizeof(mt352_clock_config));
udelay(2000);
mt352_write(fe, mt352_reset, sizeof(mt352_reset));
mt352_write(fe, mt352_adc_ctl_1_cfg, sizeof(mt352_adc_ctl_1_cfg));
mt352_write(fe, mt352_agc_cfg, sizeof(mt352_agc_cfg));
mt352_write(fe, mt352_gpp_ctl_cfg, sizeof(mt352_gpp_ctl_cfg));
mt352_write(fe, <API key>, sizeof(<API key>));
return 0;
}
static int <API key>(struct dvb_frontend* fe, struct <API key>* params, u8* pllbuf)
{
u32 div;
unsigned char bs = 0;
unsigned char cp = 0;
#define IF_FREQUENCYx6 217 /* 6 * 36.16666666667MHz */
div = (((params->frequency + 83333) * 3) / 500000) + IF_FREQUENCYx6;
if (params->frequency < 542000000) cp = 0xb4;
else if (params->frequency < 771000000) cp = 0xbc;
else cp = 0xf4;
if (params->frequency == 0) bs = 0x03;
else if (params->frequency < 443250000) bs = 0x02;
else bs = 0x08;
pllbuf[0] = 0xc0; // Note: non-linux standard PLL i2c address
pllbuf[1] = div >> 8;
pllbuf[2] = div & 0xff;
pllbuf[3] = cp;
pllbuf[4] = bs;
return 0;
}
static struct mt352_config <API key> = {
.demod_address = 0x0f,
.demod_init = <API key>,
.pll_set = <API key>,
};
static int cx24108_pll_set(struct dvb_frontend* fe, struct <API key>* params)
{
u32 freq = params->frequency;
int i, a, n, pump;
u32 band, pll;
u32 osci[]={950000,1019000,1075000,1178000,1296000,1432000,
1576000,1718000,1856000,2036000,2150000};
u32 bandsel[]={0,0x00020000,0x00040000,0x00100800,0x00101000,
0x00102000,0x00104000,0x00108000,0x00110000,
0x00120000,0x00140000};
#define XTAL 1011100 /* Hz, really 1.0111 MHz and a /10 prescaler */
printk("cx24108 debug: entering SetTunerFreq, freq=%d\n",freq);
/* This is really the bit driving the tuner chip cx24108 */
if(freq<950000) freq=950000; /* kHz */
if(freq>2150000) freq=2150000; /* satellite IF is 950..2150MHz */
/* decide which VCO to use for the input frequency */
for(i=1;(i<sizeof(osci)/sizeof(osci[0]))&&(osci[i]<freq);i++);
printk("cx24108 debug: select vco #%d (f=%d)\n",i,freq);
band=bandsel[i];
/* the gain values must be set by SetSymbolrate */
/* compute the pll divider needed, from Conexant data sheet,
resolved for (n*32+a), remember f(vco) is f(receive) *2 or *4,
depending on the divider bit. It is set to /4 on the 2 lowest
bands */
n=((i<=2?2:1)*freq*10L)/(XTAL/100);
a=n%32; n/=32; if(a==0) n
pump=(freq<(osci[i-1]+osci[i])/2);
pll=0xf8000000|
((pump?1:2)<<(14+11))|
((n&0x1ff)<<(5+11))|
((a&0x1f)<<11);
/* everything is shifted left 11 bits to left-align the bits in the
32bit word. Output to the tuner goes MSB-aligned, after all */
printk("cx24108 debug: pump=%d, n=%d, a=%d\n",pump,n,a);
cx24110_pll_write(fe,band);
/* set vga and vca to their widest-band settings, as a precaution.
SetSymbolrate might not be called to set this up */
cx24110_pll_write(fe,0x500c0000);
cx24110_pll_write(fe,0x83f1f800);
cx24110_pll_write(fe,pll);
/* writereg(client,0x56,0x7f);*/
return 0;
}
static int pinnsat_pll_init(struct dvb_frontend* fe)
{
return 0;
}
static struct cx24110_config pctvsat_config = {
.demod_address = 0x55,
.pll_init = pinnsat_pll_init,
.pll_set = cx24108_pll_set,
};
static int <API key>(struct dvb_frontend* fe, struct <API key>* params)
{
struct dvb_bt8xx_card *card = (struct dvb_bt8xx_card *) fe->dvb->priv;
u8 cfg, cpump, band_select;
u8 data[4];
u32 div;
struct i2c_msg msg = { .addr = 0x60, .flags = 0, .buf = data, .len = sizeof(data) };
div = (36000000 + params->frequency + 83333) / 166666;
cfg = 0x88;
if (params->frequency < 175000000) cpump = 2;
else if (params->frequency < 390000000) cpump = 1;
else if (params->frequency < 470000000) cpump = 2;
else if (params->frequency < 750000000) cpump = 2;
else cpump = 3;
if (params->frequency < 175000000) band_select = 0x0e;
else if (params->frequency < 470000000) band_select = 0x05;
else band_select = 0x03;
data[0] = (div >> 8) & 0x7f;
data[1] = div & 0xff;
data[2] = ((div >> 10) & 0x60) | cfg;
data[3] = cpump | band_select;
i2c_transfer(card->i2c_adapter, &msg, 1);
return (div * 166666 - 36000000);
}
static int <API key>(struct dvb_frontend* fe, const struct firmware **fw, char* name)
{
struct dvb_bt8xx_card* bt = (struct dvb_bt8xx_card*) fe->dvb->priv;
return request_firmware(fw, name, &bt->bt->dev->dev);
}
static struct sp887x_config <API key> = {
.demod_address = 0x70,
.pll_set = <API key>,
.request_firmware = <API key>,
};
static int <API key>(struct dvb_frontend* fe)
{
static u8 mt352_clock_config [] = { 0x89, 0x38, 0x2d };
static u8 mt352_reset [] = { 0x50, 0x80 };
static u8 mt352_adc_ctl_1_cfg [] = { 0x8E, 0x40 };
static u8 mt352_agc_cfg [] = { 0x67, 0x10, 0x23, 0x00, 0xFF, 0xFF,
0x00, 0xFF, 0x00, 0x40, 0x40 };
static u8 mt352_av771_extra[] = { 0xB5, 0x7A };
static u8 <API key>[] = { 0x75, 0x32 };
mt352_write(fe, mt352_clock_config, sizeof(mt352_clock_config));
udelay(2000);
mt352_write(fe, mt352_reset, sizeof(mt352_reset));
mt352_write(fe, mt352_adc_ctl_1_cfg, sizeof(mt352_adc_ctl_1_cfg));
mt352_write(fe, mt352_agc_cfg,sizeof(mt352_agc_cfg));
udelay(2000);
mt352_write(fe, mt352_av771_extra,sizeof(mt352_av771_extra));
mt352_write(fe, <API key>, sizeof(<API key>));
return 0;
}
static int <API key>(struct dvb_frontend* fe, struct <API key>* params, u8* pllbuf)
{
u32 div;
unsigned char bs = 0;
unsigned char cp = 0;
#define IF_FREQUENCYx6 217 /* 6 * 36.16666666667MHz */
div = (((params->frequency + 83333) * 3) / 500000) + IF_FREQUENCYx6;
if (params->frequency < 150000000) cp = 0xB4;
else if (params->frequency < 173000000) cp = 0xBC;
else if (params->frequency < 250000000) cp = 0xB4;
else if (params->frequency < 400000000) cp = 0xBC;
else if (params->frequency < 420000000) cp = 0xF4;
else if (params->frequency < 470000000) cp = 0xFC;
else if (params->frequency < 600000000) cp = 0xBC;
else if (params->frequency < 730000000) cp = 0xF4;
else cp = 0xFC;
if (params->frequency < 150000000) bs = 0x01;
else if (params->frequency < 173000000) bs = 0x01;
else if (params->frequency < 250000000) bs = 0x02;
else if (params->frequency < 400000000) bs = 0x02;
else if (params->frequency < 420000000) bs = 0x02;
else if (params->frequency < 470000000) bs = 0x02;
else if (params->frequency < 600000000) bs = 0x08;
else if (params->frequency < 730000000) bs = 0x08;
else bs = 0x08;
pllbuf[0] = 0xc2; // Note: non-linux standard PLL i2c address
pllbuf[1] = div >> 8;
pllbuf[2] = div & 0xff;
pllbuf[3] = cp;
pllbuf[4] = bs;
return 0;
}
static struct mt352_config <API key> = {
.demod_address = 0x0f,
.demod_init = <API key>,
.pll_set = <API key>,
};
static struct dst_config dst_config = {
.demod_address = 0x55,
};
static int <API key>(struct dvb_frontend* fe, const struct firmware **fw, char* name)
{
struct dvb_bt8xx_card* bt = (struct dvb_bt8xx_card*) fe->dvb->priv;
return request_firmware(fw, name, &bt->bt->dev->dev);
}
static void or51211_setmode(struct dvb_frontend * fe, int mode)
{
struct dvb_bt8xx_card *bt = fe->dvb->priv;
bttv_write_gpio(bt->bttv_nr, 0x0002, mode); /* Reset */
msleep(20);
}
static void or51211_reset(struct dvb_frontend * fe)
{
struct dvb_bt8xx_card *bt = fe->dvb->priv;
/* RESET DEVICE
* reset is controled by GPIO-0
* when set to 0 causes reset and when to 1 for normal op
* must remain reset for 128 clock cycles on a 50Mhz clock
* also PRM1 PRM2 & PRM4 are controled by GPIO-1,GPIO-2 & GPIO-4
* We assume that the reset has be held low long enough or we
* have been reset by a power on. When the driver is unloaded
* reset set to 0 so if reloaded we have been reset.
*/
/* reset & PRM1,2&4 are outputs */
int ret = bttv_gpio_enable(bt->bttv_nr, 0x001F, 0x001F);
if (ret != 0) {
printk(KERN_WARNING "or51211: Init Error - Can't Reset DVR "
"(%i)\n", ret);
}
bttv_write_gpio(bt->bttv_nr, 0x001F, 0x0000); /* Reset */
msleep(20);
/* Now set for normal operation */
bttv_write_gpio(bt->bttv_nr, 0x0001F, 0x0001);
/* wait for operation to begin */
msleep(500);
}
static void or51211_sleep(struct dvb_frontend * fe)
{
struct dvb_bt8xx_card *bt = fe->dvb->priv;
bttv_write_gpio(bt->bttv_nr, 0x0001, 0x0000);
}
static struct or51211_config or51211_config = {
.demod_address = 0x15,
.request_firmware = <API key>,
.setmode = or51211_setmode,
.reset = or51211_reset,
.sleep = or51211_sleep,
};
static int <API key>(struct dvb_frontend* fe, struct <API key>* params)
{
struct dvb_bt8xx_card *card = (struct dvb_bt8xx_card *) fe->dvb->priv;
u8 buf[4];
u32 div;
struct i2c_msg msg = { .addr = 0x60, .flags = 0, .buf = buf, .len = sizeof(buf) };
div = (params->frequency + 36166667) / 166667;
buf[0] = (div >> 8) & 0x7F;
buf[1] = div & 0xFF;
buf[2] = 0x85;
if ((params->frequency >= 47000000) && (params->frequency < 153000000))
buf[3] = 0x01;
else if ((params->frequency >= 153000000) && (params->frequency < 430000000))
buf[3] = 0x02;
else if ((params->frequency >= 430000000) && (params->frequency < 824000000))
buf[3] = 0x0C;
else if ((params->frequency >= 824000000) && (params->frequency < 863000000))
buf[3] = 0x8C;
else
return -EINVAL;
i2c_transfer(card->i2c_adapter, &msg, 1);
return 0;
}
static struct nxt6000_config <API key> = {
.demod_address = 0x0a,
.clock_inversion = 1,
.pll_set = <API key>,
};
static void frontend_init(struct dvb_bt8xx_card *card, u32 type)
{
int ret;
struct dst_state* state = NULL;
switch(type) {
#ifdef <API key>
case <API key>:
card->fe = mt352_attach(&<API key>, card->i2c_adapter);
if (card->fe != NULL) {
card->fe->ops->info.frequency_min = 174000000;
card->fe->ops->info.frequency_max = 862000000;
break;
}
break;
#endif
#ifdef BTTV_TWINHAN_VP3021
case BTTV_TWINHAN_VP3021:
#else
case BTTV_NEBULA_DIGITV:
#endif
card->fe = nxt6000_attach(&<API key>, card->i2c_adapter);
if (card->fe != NULL) {
break;
}
break;
case BTTV_AVDVBT_761:
card->fe = sp887x_attach(&<API key>, card->i2c_adapter);
if (card->fe != NULL) {
break;
}
break;
case BTTV_AVDVBT_771:
card->fe = mt352_attach(&<API key>, card->i2c_adapter);
if (card->fe != NULL) {
card->fe->ops->info.frequency_min = 174000000;
card->fe->ops->info.frequency_max = 862000000;
break;
}
break;
case BTTV_TWINHAN_DST:
/* DST is not a frontend driver !!! */
state = (struct dst_state *) kmalloc(sizeof (struct dst_state), GFP_KERNEL);
/* Setup the Card */
state->config = &dst_config;
state->i2c = card->i2c_adapter;
state->bt = card->bt;
/* DST is not a frontend, attaching the ASIC */
if ((dst_attach(state, &card->dvb_adapter)) == NULL) {
printk("%s: Could not find a Twinhan DST.\n", __FUNCTION__);
break;
}
card->fe = &state->frontend;
/* Attach other DST peripherals if any */
/* Conditional Access device */
if (state->dst_hw_cap & DST_TYPE_HAS_CA) {
ret = dst_ca_attach(state, &card->dvb_adapter);
}
if (card->fe != NULL) {
break;
}
break;
case BTTV_PINNACLESAT:
card->fe = cx24110_attach(&pctvsat_config, card->i2c_adapter);
if (card->fe != NULL) {
break;
}
break;
case BTTV_PC_HDTV:
card->fe = or51211_attach(&or51211_config, card->i2c_adapter);
if (card->fe != NULL) {
break;
}
break;
}
if (card->fe == NULL) {
printk("dvb-bt8xx: A frontend driver was not found for device %04x/%04x subsystem %04x/%04x\n",
card->bt->dev->vendor,
card->bt->dev->device,
card->bt->dev->subsystem_vendor,
card->bt->dev->subsystem_device);
} else {
if (<API key>(&card->dvb_adapter, card->fe)) {
printk("dvb-bt8xx: Frontend registration failed!\n");
if (card->fe->ops->release)
card->fe->ops->release(card->fe);
card->fe = NULL;
}
}
}
static int __init dvb_bt8xx_load_card(struct dvb_bt8xx_card *card, u32 type)
{
int result;
if ((result = <API key>(&card->dvb_adapter, card->card_name,
THIS_MODULE)) < 0) {
printk("dvb_bt8xx: <API key> failed (errno = %d)\n", result);
return result;
}
card->dvb_adapter.priv = card;
card->bt->adapter = card->i2c_adapter;
memset(&card->demux, 0, sizeof(struct dvb_demux));
card->demux.dmx.capabilities = DMX_TS_FILTERING | <API key> | <API key>;
card->demux.priv = card;
card->demux.filternum = 256;
card->demux.feednum = 256;
card->demux.start_feed = <API key>;
card->demux.stop_feed = dvb_bt8xx_stop_feed;
card->demux.write_to_decoder = NULL;
if ((result = dvb_dmx_init(&card->demux)) < 0) {
printk("dvb_bt8xx: dvb_dmx_init failed (errno = %d)\n", result);
<API key>(&card->dvb_adapter);
return result;
}
card->dmxdev.filternum = 256;
card->dmxdev.demux = &card->demux.dmx;
card->dmxdev.capabilities = 0;
if ((result = dvb_dmxdev_init(&card->dmxdev, &card->dvb_adapter)) < 0) {
printk("dvb_bt8xx: dvb_dmxdev_init failed (errno = %d)\n", result);
dvb_dmx_release(&card->demux);
<API key>(&card->dvb_adapter);
return result;
}
card->fe_hw.source = DMX_FRONTEND_0;
if ((result = card->demux.dmx.add_frontend(&card->demux.dmx, &card->fe_hw)) < 0) {
printk("dvb_bt8xx: dvb_dmx_init failed (errno = %d)\n", result);
dvb_dmxdev_release(&card->dmxdev);
dvb_dmx_release(&card->demux);
<API key>(&card->dvb_adapter);
return result;
}
card->fe_mem.source = DMX_MEMORY_FE;
if ((result = card->demux.dmx.add_frontend(&card->demux.dmx, &card->fe_mem)) < 0) {
printk("dvb_bt8xx: dvb_dmx_init failed (errno = %d)\n", result);
card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_hw);
dvb_dmxdev_release(&card->dmxdev);
dvb_dmx_release(&card->demux);
<API key>(&card->dvb_adapter);
return result;
}
if ((result = card->demux.dmx.connect_frontend(&card->demux.dmx, &card->fe_hw)) < 0) {
printk("dvb_bt8xx: dvb_dmx_init failed (errno = %d)\n", result);
card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_mem);
card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_hw);
dvb_dmxdev_release(&card->dmxdev);
dvb_dmx_release(&card->demux);
<API key>(&card->dvb_adapter);
return result;
}
dvb_net_init(&card->dvb_adapter, &card->dvbnet, &card->demux.dmx);
tasklet_init(&card->bt->tasklet, dvb_bt8xx_task, (unsigned long) card);
frontend_init(card, type);
return 0;
}
static int dvb_bt8xx_probe(struct device *dev)
{
struct bttv_sub_device *sub = to_bttv_sub_dev(dev);
struct dvb_bt8xx_card *card;
struct pci_dev* bttv_pci_dev;
int ret;
if (!(card = kmalloc(sizeof(struct dvb_bt8xx_card), GFP_KERNEL)))
return -ENOMEM;
memset(card, 0, sizeof(*card));
init_MUTEX(&card->lock);
card->bttv_nr = sub->core->nr;
strncpy(card->card_name, sub->core->name, sizeof(sub->core->name));
card->i2c_adapter = &sub->core->i2c_adap;
switch(sub->core->type)
{
case BTTV_PINNACLESAT:
card->gpio_mode = 0x0400c060;
/* should be: BT878_A_GAIN=0,BT878_A_PWRDN,BT878_DA_DPM,BT878_DA_SBR,
BT878_DA_IOM=1,BT878_DA_APP to enable serial highspeed mode. */
card->op_sync_orin = 0;
card->irq_err_ignore = 0;
break;
#ifdef <API key>
case <API key>:
#endif
card->gpio_mode = 0x0400C060;
card->op_sync_orin = 0;
card->irq_err_ignore = 0;
/* 26, 15, 14, 6, 5
* A_PWRDN DA_DPM DA_SBR DA_IOM_DA
* DA_APP(parallel) */
break;
#ifdef BTTV_TWINHAN_VP3021
case BTTV_TWINHAN_VP3021:
#else
case BTTV_NEBULA_DIGITV:
#endif
case BTTV_AVDVBT_761:
card->gpio_mode = (1 << 26) | (1 << 14) | (1 << 5);
card->op_sync_orin = 0;
card->irq_err_ignore = 0;
/* A_PWRDN DA_SBR DA_APP (high speed serial) */
break;
case BTTV_AVDVBT_771: //case 0x07711461:
card->gpio_mode = 0x0400402B;
card->op_sync_orin = <API key>;
card->irq_err_ignore = 0;
/* A_PWRDN DA_SBR DA_APP[0] PKTP=10 RISC_ENABLE FIFO_ENABLE*/
break;
case BTTV_TWINHAN_DST:
card->gpio_mode = 0x2204f2c;
card->op_sync_orin = <API key>;
card->irq_err_ignore = BT878_APABORT | BT878_ARIPERR |
BT878_APPERR | BT878_AFBUS;
/* 25,21,14,11,10,9,8,3,2 then
* 0x33 = 5,4,1,0
* A_SEL=SML, DA_MLB, DA_SBR,
* DA_SDR=f, fifo trigger = 32 DWORDS
* IOM = 0 == audio A/D
* DPM = 0 == digital audio mode
* == async data parallel port
* then 0x33 (13 is set by start_capture)
* DA_APP = async data parallel port,
* ACAP_EN = 1,
* RISC+FIFO ENABLE */
break;
case BTTV_PC_HDTV:
card->gpio_mode = 0x0100EC7B;
card->op_sync_orin = 0;
card->irq_err_ignore = 0;
break;
default:
printk(KERN_WARNING "dvb_bt8xx: Unknown bttv card type: %d.\n",
sub->core->type);
kfree(card);
return -ENODEV;
}
dprintk("dvb_bt8xx: identified card%d as %s\n", card->bttv_nr, card->card_name);
if (!(bttv_pci_dev = bttv_get_pcidev(card->bttv_nr))) {
printk("dvb_bt8xx: no pci device for card %d\n", card->bttv_nr);
kfree(card);
return -EFAULT;
}
if (!(card->bt = dvb_bt8xx_878_match(card->bttv_nr, bttv_pci_dev))) {
printk("dvb_bt8xx: unable to determine DMA core of card %d,\n",
card->bttv_nr);
printk("dvb_bt8xx: if you have the ALSA bt87x audio driver "
"installed, try removing it.\n");
kfree(card);
return -EFAULT;
}
init_MUTEX(&card->bt->gpio_lock);
card->bt->bttv_nr = sub->core->nr;
if ( (ret = dvb_bt8xx_load_card(card, sub->core->type)) ) {
kfree(card);
return ret;
}
dev_set_drvdata(dev, card);
return 0;
}
static int dvb_bt8xx_remove(struct device *dev)
{
struct dvb_bt8xx_card *card = dev_get_drvdata(dev);
dprintk("dvb_bt8xx: unloading card%d\n", card->bttv_nr);
bt878_stop(card->bt);
tasklet_kill(&card->bt->tasklet);
dvb_net_release(&card->dvbnet);
card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_mem);
card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_hw);
dvb_dmxdev_release(&card->dmxdev);
dvb_dmx_release(&card->demux);
if (card->fe) <API key>(card->fe);
<API key>(&card->dvb_adapter);
kfree(card);
return 0;
}
static struct bttv_sub_driver driver = {
.drv = {
.name = "dvb-bt8xx",
.probe = dvb_bt8xx_probe,
.remove = dvb_bt8xx_remove,
/* FIXME:
* .shutdown = dvb_bt8xx_shutdown,
* .suspend = dvb_bt8xx_suspend,
* .resume = dvb_bt8xx_resume,
*/
},
};
static int __init dvb_bt8xx_init(void)
{
return bttv_sub_register(&driver, "dvb");
}
static void __exit dvb_bt8xx_exit(void)
{
bttv_sub_unregister(&driver);
}
module_init(dvb_bt8xx_init);
module_exit(dvb_bt8xx_exit);
MODULE_DESCRIPTION("Bt8xx based DVB adapter driver");
MODULE_AUTHOR("Florian Schirmer <jolt@tuxbox.org>");
MODULE_LICENSE("GPL");
|
/** @internal
** @file <API key>.cpp
** @author Andrea Vedaldi
** @author Mikael Rousson (Python wrapping)
** @brief SIFT descriptor - MEX
**/
#include "../py_vlfeat.h"
extern "C" {
#include <vl/mathop.h>
#include <vl/sift.h>
}
#include <math.h>
#include <assert.h>
#include <iostream>
/* option codes */
enum
{
opt_magnif, opt_verbose
};
VL_INLINE void <API key>(vl_sift_pix* dst, vl_sift_pix* src)
{
int const BO = 8; /* number of orientation bins */
int const BP = 4; /* number of spatial bins */
int i, j, t;
for (j = 0; j < BP; ++j) {
int jp = BP - 1 - j;
for (i = 0; i < BP; ++i) {
int o = BO * i + BP * BO * j;
int op = BO * i + BP * BO * jp;
dst[op] = src[o];
for (t = 1; t < BO; ++t)
dst[BO - t + op] = src[t + o];
}
}
}
PyObject * <API key>(
PyArrayObject & in_grad,
PyArrayObject & in_frames)
{
// TODO: check types and dim
// "GRAD must be a 2xMxN matrix of class SINGLE."
assert(in_grad.descr->type_num == PyArray_FLOAT);
assert(in_frames.descr->type_num == PyArray_FLOAT64);
assert(in_grad.flags & NPY_FORTRAN);
assert(in_frames.flags & NPY_FORTRAN);
int verbose = 0;
int opt;
// TODO: check if we need to do a copy of the grad array
float * grad_array;
vl_sift_pix *grad;
int M, N;
double magnif = -1;
double *ikeys = 0;
int nikeys = 0;
int i, j;
// get frames nb and data pointer
nikeys = in_frames.dimensions[1];
ikeys = (double *) in_frames.data;
// TODO: deal with optional params
// while ((opt = uNextOption(in, nin, options, &next, &optarg)) >= 0) {
// switch (opt) {
// case opt_verbose :
// ++ verbose ;
// break ;
// case opt_magnif :
// if (!uIsRealScalar(optarg) || (magnif = *mxGetPr(optarg)) < 0) {
// mexErrMsgTxt("MAGNIF must be a non-negative scalar.") ;
// break ;
// default :
// assert(0) ;
// break ;
// TODO: convert to Python
//grad_array = mxDuplicateArray(in[IN_GRAD]); (copy?)
grad = (float*) in_grad.data; //mxGetData(grad_array);
M = in_grad.dimensions[1];
N = in_grad.dimensions[2];
/* transpose angles */
for (i = 1; i < 2 * M * N; i += 2) {
grad[i] = VL_PI / 2 - grad[i];
}
PyArrayObject * _descr;
{
VlSiftFilt *filt = 0;
vl_uint8 *descr = 0;
/* create a filter to process the image */
filt = vl_sift_new(M, N, -1, -1, 0);
if (magnif >= 0)
vl_sift_set_magnif(filt, magnif);
if (verbose) {
printf("siftdescriptor: filter settings:\n");
printf(
"siftdescriptor: magnif = %g\n",
vl_sift_get_magnif(filt));
printf("siftdescriptor: num of frames = %d\n", nikeys);
}
{
npy_intp dims[2];
dims[0] = 128;
dims[1] = nikeys;
_descr = (PyArrayObject*) <API key>(
&PyArray_Type, <API key>(PyArray_UBYTE),
2, dims, NULL, NULL, NPY_F_CONTIGUOUS, NULL);
descr = (vl_uint8*) _descr->data;
}
/* ...............................................................
* Process each octave
* ............................................................ */
for (i = 0; i < nikeys; ++i) {
vl_sift_pix buf[128], rbuf[128];
double y = *ikeys++;
double x = *ikeys++;
double s = *ikeys++;
double th = VL_PI / 2 - *ikeys++;
<API key>(filt, grad, buf, M, N, x, y, s, th);
<API key>(rbuf, buf);
for (j = 0; j < 128; ++j) {
double x = 512.0 * rbuf[j];
x = (x < 255.0) ? x : 255.0;
*descr++ = (vl_uint8) (x);
}
}
/* cleanup */
// mxDestroyArray(grad_array);
vl_sift_delete(filt);
} /* job done */
return PyArray_Return(_descr);
}
|
/*global ActiveXObject */
;(function($) {
"use strict";
/**
* Feature detection
*/
var feature = {};
feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
feature.formdata = window.FormData !== undefined;
var hasProp = !!$.fn.prop;
// attr2 uses prop when it can but checks the return type for
// an expected string. this accounts for the case where a form
// contains inputs with names like "action" or "method"; in those
// cases "prop" returns the element
$.fn.attr2 = function() {
if ( ! hasProp )
return this.attr.apply(this, arguments);
var val = this.prop.apply(this, arguments);
if ( ( val && val.jquery ) || typeof val === 'string' )
return val;
return this.attr.apply(this, arguments);
};
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
/*jshint scripturl:true */
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
var method, action, url, $form = this;
if (typeof options == 'function') {
options = { success: options };
}
method = this.attr2('method');
action = this.attr2('action');
url = (typeof action === 'string') ? $.trim(action) : '';
url = url || window.location.href || '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^
}
options = $.extend(true, {
url: url,
success: $.ajaxSettings.success,
type: method || 'GET',
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var traditional = options.traditional;
if ( traditional === undefined ) {
traditional = $.ajaxSettings.traditional;
}
var elements = [];
var qx, a = this.formToArray(options.semantic, elements);
if (options.data) {
options.extraData = options.data;
qx = $.param(options.data, traditional);
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('<API key>', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via <API key> trigger');
return this;
}
var q = $.param(a, traditional);
if (qx) {
q = ( q ? (q + '&' + qx) : qx );
}
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else {
options.data = q; // data is the query string for 'post'
}
var callbacks = [];
if (options.resetForm) {
callbacks.push(function() { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function() { $form.clearForm(options.includeHidden); });
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || this ; // jQuery 1.4+ supports scope context
for (var i=0, max=callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};
if (options.error) {
var oldError = options.error;
options.error = function(xhr, status, error) {
var context = options.context || this;
oldError.apply(context, [xhr, status, error, $form]);
};
}
if (options.complete) {
var oldComplete = options.complete;
options.complete = function(xhr, status) {
var context = options.context || this;
oldComplete.apply(context, [xhr, status, $form]);
};
}
// are there files to upload?
// [value] (issue #113), also see comment:
// https://github.com/malsup/form/commit/<SHA1-like>#<API key>
var fileInputs = $('input[type=file]:enabled[value!=""]', this);
var hasFileInputs = fileInputs.length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
var fileAPI = feature.fileapi && feature.formdata;
log("fileAPI :" + fileAPI);
var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
var jqxhr;
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, function() {
jqxhr = fileUploadIframe(a);
});
}
else {
jqxhr = fileUploadIframe(a);
}
}
else if ((hasFileInputs || multipart) && fileAPI) {
jqxhr = fileUploadXhr(a);
}
else {
jqxhr = $.ajax(options);
}
$form.removeData('jqxhr').data('jqxhr', jqxhr);
// clear element array
for (var k=0; k < elements.length; k++)
elements[k] = null;
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// utility fn for deep serialization
function deepSerialize(extraData){
var serialized = $.param(extraData).split('&');
var len = serialized.length;
var result = [];
var i, part;
for (i=0; i < len; i++) {
// #252; undo param space replacement
serialized[i] = serialized[i].replace(/\+/g,' ');
part = serialized[i].split('=');
// #278; use array instead of object storage, favoring array serializations
result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
}
return result;
}
// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();
for (var i=0; i < a.length; i++) {
formdata.append(a[i].name, a[i].value);
}
if (options.extraData) {
var serializedData = deepSerialize(options.extraData);
for (i=0; i < serializedData.length; i++)
if (serializedData[i])
formdata.append(serializedData[i][0], serializedData[i][1]);
}
options.data = null;
var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: method || 'POST'
});
if (options.uploadProgress) {
// workaround because jqXHR does not expose upload property
s.xhr = function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
}, false);
}
return xhr;
};
}
s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function(xhr, o) {
o.data = formdata;
if(beforeSend)
beforeSend.call(this, xhr, o);
};
return $.ajax(s);
}
// private function for handling file uploads (hat tip to YAHOO!)
function fileUploadIframe(a) {
var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
var deferred = $.Deferred();
if (a) {
// ensure that every serialized input is still enabled
for (i=0; i < elements.length; i++) {
el = $(elements[i]);
if ( hasProp )
el.prop('disabled', false);
else
el.removeAttr('disabled');
}
}
s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
id = 'jqFormIO' + (new Date().getTime());
if (s.iframeTarget) {
$io = $(s.iframeTarget);
n = $io.attr2('name');
if (!n)
$io.attr2('name', id);
else
id = n;
}
else {
$io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
}
io = $io[0];
xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
<API key>: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function(status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;
try { // #214, #257
if (io.contentWindow.document.execCommand) {
io.contentWindow.document.execCommand('Stop');
}
}
catch(ignore) {}
$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
if (s.error)
s.error.call(s.context, xhr, e, status);
if (g)
$.event.trigger("ajaxError", [xhr, s, e]);
if (s.complete)
s.complete.call(s.context, xhr, e);
}
};
g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && 0 === $.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active
}
deferred.reject();
return deferred;
}
if (xhr.aborted) {
deferred.reject();
return deferred;
}
// add submitting element to data if we know it
sub = form.clk;
if (sub) {
n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n+'.x'] = form.clk_x;
s.extraData[n+'.y'] = form.clk_y;
}
}
}
var <API key> = 1;
var SERVER_ABORT = 2;
function getDoc(frame) {
var doc = null;
// IE8 cascading access check
try {
if (frame.contentWindow) {
doc = frame.contentWindow.document;
}
} catch(err) {
// IE8 access denied under ssl & missing protocol
log('cannot get iframe.contentWindow document: ' + err);
}
if (doc) { // successful getting content
return doc;
}
try { // simply checking may throw in ie8 under ssl or mismatched protocol
doc = frame.contentDocument ? frame.contentDocument : frame.document;
} catch(err) {
// last attempt
log('cannot get iframe.contentDocument: ' + err);
doc = frame.document;
}
return doc;
}
// Rails CSRF hack (thanks to Yvan Barthelemy)
var csrf_token = $('meta[name=csrf-token]').attr('content');
var csrf_param = $('meta[name=csrf-param]').attr('content');
if (csrf_param && csrf_token) {
s.extraData = s.extraData || {};
s.extraData[csrf_param] = csrf_token;
}
// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr2('target'), a = $form.attr2('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (!method) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.<API key> && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(<API key>); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
if (s.extraData.hasOwnProperty(n)) {
// if using the $.param format that allows for multiple values with the same name
if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
extraInputs.push(
$('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value)
.appendTo(form)[0]);
} else {
extraInputs.push(
$('<input type="hidden" name="'+n+'">').val(s.extraData[n])
.appendTo(form)[0]);
}
}
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
if (io.attachEvent)
io.attachEvent('onload', cb);
else
io.addEventListener('load', cb, false);
}
setTimeout(checkState,15);
try {
form.submit();
} catch(err) {
// just in case form has element with name/id of 'submit'
var submitFn = document.createElement('form').submit;
submitFn.apply(form);
}
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50, callbackProcessed;
function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
doc = getDoc(io);
if(!doc) {
log('cannot access response document');
e = SERVER_ABORT;
}
if (e === <API key> && xhr) {
xhr.abort('timeout');
deferred.reject(xhr, 'timeout');
return;
}
else if (e == SERVER_ABORT && xhr) {
xhr.abort('server abort');
deferred.reject(xhr, 'error', 'server abort');
return;
}
if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut)
return;
}
if (io.detachEvent)
io.detachEvent('onload', cb);
else
io.removeEventListener('load', cb, false);
var status = 'success', errMsg;
try {
if (timedOut) {
throw 'timeout';
}
var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml='+isXml);
if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}
//log('response detected');
var docRoot = doc.body ? doc.body : doc.documentElement;
xhr.responseText = docRoot ? docRoot.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml)
s.dataType = 'xml';
xhr.getResponseHeader = function(header){
var headers = {'content-type': s.dataType};
return headers[header];
};
// support for XHR 'status' & 'statusText' emulation :
if (docRoot) {
xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
}
var dt = (s.dataType || '').toLowerCase();
var scr = /(json|script|text)/.test(dt);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.<API key>('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
// support for XHR 'status' & 'statusText' emulation :
xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.<API key>('pre')[0];
var b = doc.<API key>('body')[0];
if (pre) {
xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
}
else if (b) {
xhr.responseText = b.textContent ? b.textContent : b.innerText;
}
}
}
else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
xhr.responseXML = toXml(xhr.responseText);
}
try {
data = httpData(xhr, dt, s);
}
catch (err) {
status = 'parsererror';
xhr.error = errMsg = (err || status);
}
}
catch (err) {
log('error caught: ',err);
status = 'error';
xhr.error = errMsg = (err || status);
}
if (xhr.aborted) {
log('upload aborted');
status = null;
}
if (xhr.status) { // we've set xhr.status
status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (status === 'success') {
if (s.success)
s.success.call(s.context, data, 'success', xhr);
deferred.resolve(xhr.responseText, 'success', xhr);
if (g)
$.event.trigger("ajaxSuccess", [xhr, s]);
}
else if (status) {
if (errMsg === undefined)
errMsg = xhr.statusText;
if (s.error)
s.error.call(s.context, xhr, status, errMsg);
deferred.reject(xhr, 'error', errMsg);
if (g)
$.event.trigger("ajaxError", [xhr, s, errMsg]);
}
if (g)
$.event.trigger("ajaxComplete", [xhr, s]);
if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}
if (s.complete)
s.complete.call(s.context, xhr, status);
callbackProcessed = true;
if (s.timeout)
clearTimeout(timeoutHandle);
// clean up
setTimeout(function() {
if (!s.iframeTarget)
$io.remove();
xhr.responseXML = null;
}, 100);
}
var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function(s) {
/*jslint evil:true */
return window['eval']('(' + s + ')');
};
var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.nodeName === 'parsererror') {
if ($.error)
$.error('parsererror');
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};
return deferred;
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function(options) {
options = options || {};
options.delegation = options.delegation && $.isFunction($.fn.on);
// in jQuery 1.3+ we can fix mistakes with the ready state
if (!options.delegation && this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s,o.c).ajaxForm(options);
});
return this;
}
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
if ( options.delegation ) {
$(document)
.off('submit.form-plugin', this.selector, doAjaxSubmit)
.off('click.form-plugin', this.selector, <API key>)
.on('submit.form-plugin', this.selector, options, doAjaxSubmit)
.on('click.form-plugin', this.selector, options, <API key>);
return this;
}
return this.ajaxFormUnbind()
.bind('submit.form-plugin', options, doAjaxSubmit)
.bind('click.form-plugin', options, <API key>);
};
// private event handlers
function doAjaxSubmit(e) {
/*jshint validthis:true */
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}
function <API key>(e) {
/*jshint validthis:true */
var target = e.target;
var $el = $(target);
if (!($el.is("[type=submit],[type=image]"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest('[type=submit]');
if (t.length === 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX !== undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') {
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
}
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic, elements) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.<API key>('*') : form.elements;
if (!els) {
return a;
}
var i,j,n,v,el,max,jmax;
for(i=0, max=els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n || el.disabled) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(form.clk == el) {
a.push({name: n, value: $(el).val(), type: el.type });
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
if (elements)
elements.push(el);
for(j=0, jmax=v.length; j < jmax; j++) {
a.push({name: n, value: v[j]});
}
}
else if (feature.fileapi && el.type == 'file') {
if (elements)
elements.push(el);
var files = el.files;
if (files.length) {
for (j=0; j < files.length; j++) {
a.push({name: n, value: files[j], type: el.type});
}
}
else {
// #180
a.push({ name: n, value: '', type: el.type });
}
}
else if (v !== null && typeof v != 'undefined') {
if (elements)
elements.push(el);
a.push({name: n, value: v, type: el.type, required: el.required});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({name: n, value: $input.val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++) {
a.push({name: n, value: v[i]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: this.name, value: v});
}
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
if (v.constructor == Array)
$.merge(val, v);
else
val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function(includeHidden) {
return this.each(function() {
$('input,select,textarea', this).clearFields(includeHidden);
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
else if (t == "file") {
if (/MSIE/.test(navigator.userAgent)) {
$(this).replaceWith($(this).clone(true));
} else {
$(this).val('');
}
}
else if (includeHidden) {
// includeHidden can be the value true, or it can be a selector string
// indicating a special test; for example:
// $('#myForm').clearForm('.special:hidden')
// the above would clean hidden inputs that have the class of 'special'
if ( (includeHidden === true && /hidden/.test(t)) ||
(typeof includeHidden == 'string' && $(this).is(includeHidden)) )
this.value = '';
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
}
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
// expose debug var
$.fn.ajaxSubmit.debug = false;
// helper fn for console logging
function log() {
if (!$.fn.ajaxSubmit.debug)
return;
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
})(jQuery);
|
<?php
if (isset($_POST['gdsr_action']) && $_POST['gdsr_action'] == 'save') {
$gdsr_options["bot_message"] = $_POST['gdsr_bot_message'];
$gdsr_options["no_votes_percentage"] = $_POST['<API key>'];
$gdsr_options["cached_loading"] = isset($_POST['gdsr_cached_loading']) ? 1 : 0;
$gdsr_options["include_opacity"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["update_report_usage"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["thumbs_active"] = isset($_POST['gdsr_thumbs_act']) ? 1 : 0;
$gdsr_options["wp_query_handler"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["disable_ie6_check"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["news_feed_active"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["widgets_hidempty"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["encoding"] = $_POST['gdsr_encoding'];
$gdsr_options["admin_rows"] = $_POST['gdsr_admin_rows'];
$gdsr_options["gfx_generator_auto"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["external_rating_css"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["css_cache_active"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["external_css"] = isset($_POST['gdsr_external_css']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["admin_advanced"] = isset($_POST['gdsr_admin_advanced']) ? 1 : 0;
$gdsr_options["admin_placement"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["admin_defaults"] = isset($_POST['gdsr_admin_defaults']) ? 1 : 0;
$gdsr_options["admin_import"] = isset($_POST['gdsr_admin_import']) ? 1 : 0;
$gdsr_options["admin_export"] = isset($_POST['gdsr_admin_export']) ? 1 : 0;
$gdsr_options["admin_setup"] = isset($_POST['gdsr_admin_setup']) ? 1 : 0;
$gdsr_options["admin_ips"] = isset($_POST['gdsr_admin_ips']) ? 1 : 0;
$gdsr_options["admin_views"] = isset($_POST['gdsr_admin_views']) ? 1 : 0;
$gdsr_options["prefetch_data"] = isset($_POST['gdsr_prefetch_data']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["cache_active"] = isset($_POST['gdsr_cache_active']) ? 1 : 0;
$gdsr_options["cache_forced"] = isset($_POST['gdsr_cache_forced']) ? 1 : 0;
$gdsr_options["cache_cleanup_auto"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["cache_cleanup_days"] = $_POST['<API key>'];
$gdsr_options["wait_show_article"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["wait_show_comment"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["wait_show_multis"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["wait_loader_article"] = $_POST['<API key>'];
$gdsr_options["wait_loader_comment"] = $_POST['<API key>'];
$gdsr_options["wait_loader_multis"] = $_POST['<API key>'];
$gdsr_options["wait_text_article"] = $_POST['<API key>'];
$gdsr_options["wait_text_comment"] = $_POST['<API key>'];
$gdsr_options["wait_text_multis"] = $_POST['<API key>'];
$gdsr_options["wait_class_article"] = $_POST['<API key>'];
$gdsr_options["wait_class_comment"] = $_POST['<API key>'];
$gdsr_options["wait_class_multis"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['gdsr_grs_format'];
$gdsr_options["<API key>"] = $_POST['gdsr_grs_location'];
$gdsr_options["<API key>"] = $_POST['gdsr_grs_datasource'];
$gdsr_options["<API key>"] = isset($_POST['gdsr_grs']) ? 1 : 0;
$gdsr_options["debug_wpquery"] = isset($_POST['gdsr_debug_wpquery']) ? 1 : 0;
$gdsr_options["debug_active"] = isset($_POST['gdsr_debug_active']) ? 1 : 0;
$gdsr_options["debug_inline"] = isset($_POST['gdsr_debug_inline']) ? 1 : 0;
$gdsr_options["use_nonce"] = isset($_POST['gdsr_use_nonce']) ? 1 : 0;
$gdsr_options["ajax_jsonp"] = isset($_POST['gdsr_ajax_jsonp']) ? 1 : 0;
$gdsr_options["ip_filtering"] = isset($_POST['gdsr_ip_filtering']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["widget_articles"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["widget_top"] = isset($_POST['gdsr_widget_top']) ? 1 : 0;
$gdsr_options["widget_comments"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["display_pages"] = isset($_POST['gdsr_pages']) ? 1 : 0;
$gdsr_options["display_posts"] = isset($_POST['gdsr_posts']) ? 1 : 0;
$gdsr_options["display_archive"] = isset($_POST['gdsr_archive']) ? 1 : 0;
$gdsr_options["display_home"] = isset($_POST['gdsr_home']) ? 1 : 0;
$gdsr_options["display_search"] = isset($_POST['gdsr_search']) ? 1 : 0;
$gdsr_options["display_comment"] = isset($_POST['gdsr_dispcomment']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["moderation_active"] = isset($_POST['gdsr_modactive']) ? 1 : 0;
$gdsr_options["multis_active"] = isset($_POST['gdsr_multis']) ? 1 : 0;
$gdsr_options["timer_active"] = isset($_POST['gdsr_timer']) ? 1 : 0;
$gdsr_options["rss_active"] = isset($_POST['gdsr_rss']) ? 1 : 0;
$gdsr_options["save_user_agent"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["save_cookies"] = isset($_POST['gdsr_save_cookies']) ? 1 : 0;
$gdsr_options["ie_opacity_fix"] = isset($_POST['gdsr_ieopacityfix']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["integrate_dashboard"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["integrate_post_edit"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["integrate_tinymce"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["trend_last"] = $_POST['gdsr_trend_last'];
$gdsr_options["trend_over"] = $_POST['gdsr_trend_over'];
$gdsr_options["bayesian_minimal"] = $_POST['<API key>'];
$gdsr_options["bayesian_mean"] = $_POST['gdsr_bayesian_mean'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["default_timer_type"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "N";
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : 30;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "D";
$gdsr_options["default_timer_value"] = $gdsr_options["<API key>"].$gdsr_options["<API key>"];
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "N";
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : 30;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "D";
$gdsr_options["<API key>"] = $gdsr_options["<API key>"].$gdsr_options["<API key>"];
$gdsr_options["review_active"] = isset($_POST['gdsr_reviewactive']) ? 1 : 0;
$gdsr_options["comments_active"] = isset($_POST['gdsr_commentsactive']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["hide_empty_rating"] = isset($_POST['gdsr_haderating']) ? 1 : 0;
$gdsr_options["cookies"] = isset($_POST['gdsr_cookies']) ? 1 : 0;
$gdsr_options["cmm_cookies"] = isset($_POST['gdsr_cmm_cookies']) ? 1 : 0;
$gdsr_options["author_vote"] = isset($_POST['gdsr_authorvote']) ? 1 : 0;
$gdsr_options["cmm_author_vote"] = isset($_POST['gdsr_cmm_authorvote']) ? 1 : 0;
$gdsr_options["logged"] = isset($_POST['gdsr_logged']) ? 1 : 0;
$gdsr_options["cmm_logged"] = isset($_POST['gdsr_cmm_logged']) ? 1 : 0;
$gdsr_options["rss_datasource"] = $_POST['gdsr_rss_datasource'];
$gdsr_options["rss_style"] = $_POST['gdsr_rss_style'];
$gdsr_options["rss_size"] = $_POST['gdsr_rss_size'];
$gdsr_options["thumb_rss_style"] = $_POST['<API key>'];
$gdsr_options["thumb_rss_size"] = $_POST['gdsr_thumb_rss_size'];
$gdsr_options["rss_header_text"] = stripslashes(htmlentities($_POST['<API key>'], ENT_QUOTES, STARRATING_ENCODING));
$gdsr_options["style"] = $_POST['gdsr_style'];
$gdsr_options["style_ie6"] = $_POST['gdsr_style_ie6'];
$gdsr_options["size"] = $_POST['gdsr_size'];
$gdsr_options["header_text"] = stripslashes(htmlentities($_POST['gdsr_header_text'], ENT_QUOTES, STARRATING_ENCODING));
$gdsr_options["thumb_style"] = $_POST['gdsr_thumb_style'];
$gdsr_options["thumb_style_ie6"] = $_POST['<API key>'];
$gdsr_options["thumb_size"] = $_POST['gdsr_thumb_size'];
$gdsr_options["thumb_header_text"] = stripslashes(htmlentities($_POST['<API key>'], ENT_QUOTES, STARRATING_ENCODING));
$gdsr_options["thumb_cmm_style"] = $_POST['<API key>'];
$gdsr_options["thumb_cmm_style_ie6"] = $_POST['<API key>'];
$gdsr_options["thumb_cmm_size"] = $_POST['gdsr_thumb_cmm_size'];
$gdsr_options["<API key>"] = stripslashes(htmlentities($_POST['<API key>'], ENT_QUOTES, STARRATING_ENCODING));
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["srb_class_block"] = $_POST['gdsr_classblock'];
$gdsr_options["srb_class_text"] = $_POST['gdsr_classtext'];
$gdsr_options["srb_class_header"] = $_POST['gdsr_classheader'];
$gdsr_options["srb_class_stars"] = $_POST['gdsr_classstars'];
$gdsr_options["cmm_class_block"] = $_POST['gdsr_cmm_classblock'];
$gdsr_options["cmm_class_text"] = $_POST['gdsr_cmm_classtext'];
$gdsr_options["cmm_class_header"] = $_POST['<API key>'];
$gdsr_options["cmm_class_stars"] = $_POST['gdsr_cmm_classstars'];
$gdsr_options["mur_style"] = $_POST['gdsr_mur_style'];
$gdsr_options["mur_style_ie6"] = $_POST['gdsr_mur_style_ie6'];
$gdsr_options["mur_size"] = $_POST['gdsr_mur_size'];
$gdsr_options["mur_header_text"] = stripslashes(htmlentities($_POST['<API key>'], ENT_QUOTES, STARRATING_ENCODING));
$gdsr_options["mur_class_block"] = $_POST['gdsr_mur_classblock'];
$gdsr_options["mur_class_text"] = $_POST['gdsr_mur_classtext'];
$gdsr_options["mur_class_header"] = $_POST['<API key>'];
$gdsr_options["mur_class_button"] = $_POST['<API key>'];
$gdsr_options["mur_button_text"] = $_POST['gdsr_mur_submittext'];
$gdsr_options["mur_button_active"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["cmm_aggr_style"] = $_POST['gdsr_cmm_aggr_style'];
$gdsr_options["cmm_aggr_style_ie6"] = $_POST['<API key>'];
$gdsr_options["cmm_aggr_size"] = $_POST['gdsr_cmm_aggr_size'];
$gdsr_options["cmm_style"] = $_POST['gdsr_cmm_style'];
$gdsr_options["cmm_style_ie6"] = $_POST['gdsr_cmm_style_ie6'];
$gdsr_options["cmm_size"] = $_POST['gdsr_cmm_size'];
$gdsr_options["cmm_header_text"] = stripslashes(htmlentities($_POST['<API key>'], ENT_QUOTES, STARRATING_ENCODING));
$gdsr_options["review_style"] = $_POST['gdsr_review_style'];
$gdsr_options["review_style_ie6"] = $_POST['<API key>'];
$gdsr_options["review_size"] = $_POST['gdsr_review_size'];
$gdsr_options["review_stars"] = $_POST['gdsr_review_stars'];
$gdsr_options["review_header_text"] = stripslashes(htmlentities($_POST['<API key>'], ENT_QUOTES, STARRATING_ENCODING));
$gdsr_options["review_class_block"] = $_POST['<API key>'];
$gdsr_options["cmm_review_style"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "oxyen";
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "oxyen_gif";
$gdsr_options["cmm_review_size"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : 20;
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "";
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "";
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "";
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "";
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? $_POST['<API key>'] : "";
$gdsr_options["thumb_display_pages"] = isset($_POST['gdsr_thumb_pages']) ? 1 : 0;
$gdsr_options["thumb_display_posts"] = isset($_POST['gdsr_thumb_posts']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['gdsr_thumb_archive']) ? 1 : 0;
$gdsr_options["thumb_display_home"] = isset($_POST['gdsr_thumb_home']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['gdsr_thumb_search']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = isset($_POST['<API key>']) ? 1 : 0;
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["<API key>"] = $_POST['<API key>'];
$gdsr_options["css_last_changed"] = time();
update_option("gd-star-rating", $gdsr_options);
$bots = explode("\r\n", $_POST["gdsr_bots"]);
foreach($bots as $key => $value) {
if(trim($value) == "") {
unset($bots[$key]);
}
}
$bots = array_values($bots);
update_option("gd-star-rating-bots", $bots);
}
?>
|
#define pr_fmt(fmt) "%s:%d " fmt, __func__, __LINE__
#include <linux/bug.h>
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/types.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-mem2mem.h>
#include <media/videobuf2-core.h>
#include <media/<API key>.h>
#include <media/exynos-fimc.h>
#include "common.h"
#include "fimc-core.h"
#include "fimc-lite.h"
#include "fimc-lite-reg.h"
static int debug;
module_param(debug, int, 0644);
static const struct fimc_fmt fimc_lite_formats[] = {
{
.name = "YUV 4:2:2 packed, YCbYCr",
.fourcc = V4L2_PIX_FMT_YUYV,
.colorspace = <API key>,
.depth = { 16 },
.color = FIMC_FMT_YCBYCR422,
.memplanes = 1,
.mbus_code = <API key>,
.flags = FMT_FLAGS_YUV,
}, {
.name = "YUV 4:2:2 packed, CbYCrY",
.fourcc = V4L2_PIX_FMT_UYVY,
.colorspace = <API key>,
.depth = { 16 },
.color = FIMC_FMT_CBYCRY422,
.memplanes = 1,
.mbus_code = <API key>,
.flags = FMT_FLAGS_YUV,
}, {
.name = "YUV 4:2:2 packed, CrYCbY",
.fourcc = V4L2_PIX_FMT_VYUY,
.colorspace = <API key>,
.depth = { 16 },
.color = FIMC_FMT_CRYCBY422,
.memplanes = 1,
.mbus_code = <API key>,
.flags = FMT_FLAGS_YUV,
}, {
.name = "YUV 4:2:2 packed, YCrYCb",
.fourcc = V4L2_PIX_FMT_YVYU,
.colorspace = <API key>,
.depth = { 16 },
.color = FIMC_FMT_YCRYCB422,
.memplanes = 1,
.mbus_code = <API key>,
.flags = FMT_FLAGS_YUV,
}, {
.name = "RAW8 (GRBG)",
.fourcc = V4L2_PIX_FMT_SGRBG8,
.colorspace = <API key>,
.depth = { 8 },
.color = FIMC_FMT_RAW8,
.memplanes = 1,
.mbus_code = <API key>,
.flags = FMT_FLAGS_RAW_BAYER,
}, {
.name = "RAW10 (GRBG)",
.fourcc = <API key>,
.colorspace = <API key>,
.depth = { 16 },
.color = FIMC_FMT_RAW10,
.memplanes = 1,
.mbus_code = <API key>,
.flags = FMT_FLAGS_RAW_BAYER,
}, {
.name = "RAW12 (GRBG)",
.fourcc = <API key>,
.colorspace = <API key>,
.depth = { 16 },
.color = FIMC_FMT_RAW12,
.memplanes = 1,
.mbus_code = <API key>,
.flags = FMT_FLAGS_RAW_BAYER,
},
};
/**
* <API key> - lookup fimc color format by fourcc or media bus code
* @pixelformat: fourcc to match, ignored if null
* @mbus_code: media bus code to match, ignored if null
* @mask: the color format flags to match
* @index: index to the fimc_lite_formats array, ignored if negative
*/
static const struct fimc_fmt *<API key>(const u32 *pixelformat,
const u32 *mbus_code, unsigned int mask, int index)
{
const struct fimc_fmt *fmt, *def_fmt = NULL;
unsigned int i;
int id = 0;
if (index >= (int)ARRAY_SIZE(fimc_lite_formats))
return NULL;
for (i = 0; i < ARRAY_SIZE(fimc_lite_formats); ++i) {
fmt = &fimc_lite_formats[i];
if (mask && !(fmt->flags & mask))
continue;
if (pixelformat && fmt->fourcc == *pixelformat)
return fmt;
if (mbus_code && fmt->mbus_code == *mbus_code)
return fmt;
if (index == id)
def_fmt = fmt;
id++;
}
return def_fmt;
}
static int fimc_lite_hw_init(struct fimc_lite *fimc, bool isp_output)
{
struct fimc_source_info *si;
unsigned long flags;
if (fimc->sensor == NULL)
return -ENXIO;
if (fimc->inp_frame.fmt == NULL || fimc->out_frame.fmt == NULL)
return -EINVAL;
/* Get sensor configuration data from the sensor subdev */
si = <API key>(fimc->sensor);
if (!si)
return -EINVAL;
spin_lock_irqsave(&fimc->slock, flags);
<API key>(fimc, si);
<API key>(fimc, &fimc->inp_frame);
<API key>(fimc, &fimc->inp_frame);
<API key>(fimc, 0);
<API key>(fimc, &fimc->out_frame, !isp_output);
<API key>(fimc);
<API key>(fimc, fimc->test_pattern->val);
if (debug > 0)
flite_hw_dump_regs(fimc, __func__);
<API key>(&fimc->slock, flags);
return 0;
}
/*
* Reinitialize the driver so it is ready to start the streaming again.
* Set fimc->state to indicate stream off and the hardware shut down state.
* If not suspending (@suspend is false), return any buffers to videobuf2.
* Otherwise put any owned buffers onto the pending buffers queue, so they
* can be re-spun when the device is being resumed. Also perform FIMC
* software reset and disable streaming on the whole pipeline if required.
*/
static int fimc_lite_reinit(struct fimc_lite *fimc, bool suspend)
{
struct flite_buffer *buf;
unsigned long flags;
bool streaming;
spin_lock_irqsave(&fimc->slock, flags);
streaming = fimc->state & (1 << ST_SENSOR_STREAM);
fimc->state &= ~(1 << ST_FLITE_RUN | 1 << ST_FLITE_OFF |
1 << ST_FLITE_STREAM | 1 << ST_SENSOR_STREAM);
if (suspend)
fimc->state |= (1 << ST_FLITE_SUSPENDED);
else
fimc->state &= ~(1 << ST_FLITE_PENDING |
1 << ST_FLITE_SUSPENDED);
/* Release unused buffers */
while (!suspend && !list_empty(&fimc->pending_buf_q)) {
buf = <API key>(fimc);
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
}
/* If suspending put unused buffers onto pending queue */
while (!list_empty(&fimc->active_buf_q)) {
buf = <API key>(fimc);
if (suspend)
<API key>(fimc, buf);
else
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
}
<API key>(&fimc->slock, flags);
flite_hw_reset(fimc);
if (!streaming)
return 0;
return fimc_pipeline_call(&fimc->ve, set_stream, 0);
}
static int <API key>(struct fimc_lite *fimc, bool suspend)
{
unsigned long flags;
if (!fimc_lite_active(fimc))
return 0;
spin_lock_irqsave(&fimc->slock, flags);
set_bit(ST_FLITE_OFF, &fimc->state);
<API key>(fimc);
<API key>(&fimc->slock, flags);
wait_event_timeout(fimc->irq_queue,
!test_bit(ST_FLITE_OFF, &fimc->state),
(2*HZ/10)); /* 200 ms */
return fimc_lite_reinit(fimc, suspend);
}
/* Must be called with fimc.slock spinlock held. */
static void <API key>(struct fimc_lite *fimc)
{
<API key>(fimc, &fimc->inp_frame);
<API key>(fimc, &fimc->out_frame);
<API key>(fimc, fimc->test_pattern->val);
clear_bit(ST_FLITE_CONFIG, &fimc->state);
}
static irqreturn_t flite_irq_handler(int irq, void *priv)
{
struct fimc_lite *fimc = priv;
struct flite_buffer *vbuf;
unsigned long flags;
struct timeval *tv;
struct timespec ts;
u32 intsrc;
spin_lock_irqsave(&fimc->slock, flags);
intsrc = <API key>(fimc);
<API key>(fimc);
if (test_and_clear_bit(ST_FLITE_OFF, &fimc->state)) {
wake_up(&fimc->irq_queue);
goto done;
}
if (intsrc & <API key>) {
clear_bit(ST_FLITE_RUN, &fimc->state);
fimc->events.data_overflow++;
}
if (intsrc & <API key>) {
<API key>(fimc);
clear_bit(ST_FLITE_STREAM, &fimc->state);
wake_up(&fimc->irq_queue);
}
if (atomic_read(&fimc->out_path) != FIMC_IO_DMA)
goto done;
if ((intsrc & <API key>) &&
test_bit(ST_FLITE_RUN, &fimc->state) &&
!list_empty(&fimc->pending_buf_q)) {
vbuf = <API key>(fimc);
<API key>(fimc, vbuf);
<API key>(fimc, vbuf);
}
if ((intsrc & <API key>) &&
test_bit(ST_FLITE_RUN, &fimc->state) &&
!list_empty(&fimc->active_buf_q)) {
vbuf = <API key>(fimc);
ktime_get_ts(&ts);
tv = &vbuf->vb.v4l2_buf.timestamp;
tv->tv_sec = ts.tv_sec;
tv->tv_usec = ts.tv_nsec / NSEC_PER_USEC;
vbuf->vb.v4l2_buf.sequence = fimc->frame_count++;
<API key>(fimc, vbuf->index);
vb2_buffer_done(&vbuf->vb, VB2_BUF_STATE_DONE);
}
if (test_bit(ST_FLITE_CONFIG, &fimc->state))
<API key>(fimc);
if (list_empty(&fimc->pending_buf_q)) {
<API key>(fimc);
clear_bit(ST_FLITE_STREAM, &fimc->state);
}
done:
set_bit(ST_FLITE_RUN, &fimc->state);
<API key>(&fimc->slock, flags);
return IRQ_HANDLED;
}
static int start_streaming(struct vb2_queue *q, unsigned int count)
{
struct fimc_lite *fimc = q->drv_priv;
unsigned long flags;
int ret;
spin_lock_irqsave(&fimc->slock, flags);
fimc->buf_index = 0;
fimc->frame_count = 0;
<API key>(&fimc->slock, flags);
ret = fimc_lite_hw_init(fimc, false);
if (ret) {
fimc_lite_reinit(fimc, false);
return ret;
}
set_bit(ST_FLITE_PENDING, &fimc->state);
if (!list_empty(&fimc->active_buf_q) &&
!test_and_set_bit(ST_FLITE_STREAM, &fimc->state)) {
<API key>(fimc);
if (!test_and_set_bit(ST_SENSOR_STREAM, &fimc->state))
fimc_pipeline_call(&fimc->ve, set_stream, 1);
}
if (debug > 0)
flite_hw_dump_regs(fimc, __func__);
return 0;
}
static void stop_streaming(struct vb2_queue *q)
{
struct fimc_lite *fimc = q->drv_priv;
if (!fimc_lite_active(fimc))
return;
<API key>(fimc, false);
}
static int queue_setup(struct vb2_queue *vq, const struct v4l2_format *pfmt,
unsigned int *num_buffers, unsigned int *num_planes,
unsigned int sizes[], void *allocators[])
{
const struct <API key> *pixm = NULL;
struct fimc_lite *fimc = vq->drv_priv;
struct flite_frame *frame = &fimc->out_frame;
const struct fimc_fmt *fmt = frame->fmt;
unsigned long wh;
int i;
if (pfmt) {
pixm = &pfmt->fmt.pix_mp;
fmt = <API key>(&pixm->pixelformat, NULL, 0, -1);
wh = pixm->width * pixm->height;
} else {
wh = frame->f_width * frame->f_height;
}
if (fmt == NULL)
return -EINVAL;
*num_planes = fmt->memplanes;
for (i = 0; i < fmt->memplanes; i++) {
unsigned int size = (wh * fmt->depth[i]) / 8;
if (pixm)
sizes[i] = max(size, pixm->plane_fmt[i].sizeimage);
else
sizes[i] = size;
allocators[i] = fimc->alloc_ctx;
}
return 0;
}
static int buffer_prepare(struct vb2_buffer *vb)
{
struct vb2_queue *vq = vb->vb2_queue;
struct fimc_lite *fimc = vq->drv_priv;
int i;
if (fimc->out_frame.fmt == NULL)
return -EINVAL;
for (i = 0; i < fimc->out_frame.fmt->memplanes; i++) {
unsigned long size = fimc->payload[i];
if (vb2_plane_size(vb, i) < size) {
v4l2_err(&fimc->ve.vdev,
"User buffer too small (%ld < %ld)\n",
vb2_plane_size(vb, i), size);
return -EINVAL;
}
<API key>(vb, i, size);
}
return 0;
}
static void buffer_queue(struct vb2_buffer *vb)
{
struct flite_buffer *buf
= container_of(vb, struct flite_buffer, vb);
struct fimc_lite *fimc = vb2_get_drv_priv(vb->vb2_queue);
unsigned long flags;
spin_lock_irqsave(&fimc->slock, flags);
buf->paddr = <API key>(vb, 0);
buf->index = fimc->buf_index++;
if (fimc->buf_index >= fimc->reqbufs_count)
fimc->buf_index = 0;
if (!test_bit(ST_FLITE_SUSPENDED, &fimc->state) &&
!test_bit(ST_FLITE_STREAM, &fimc->state) &&
list_empty(&fimc->active_buf_q)) {
<API key>(fimc, buf);
<API key>(fimc, buf);
} else {
<API key>(fimc, buf);
}
if (vb2_is_streaming(&fimc->vb_queue) &&
!list_empty(&fimc->pending_buf_q) &&
!test_and_set_bit(ST_FLITE_STREAM, &fimc->state)) {
<API key>(fimc);
<API key>(&fimc->slock, flags);
if (!test_and_set_bit(ST_SENSOR_STREAM, &fimc->state))
fimc_pipeline_call(&fimc->ve, set_stream, 1);
return;
}
<API key>(&fimc->slock, flags);
}
static const struct vb2_ops fimc_lite_qops = {
.queue_setup = queue_setup,
.buf_prepare = buffer_prepare,
.buf_queue = buffer_queue,
.wait_prepare = <API key>,
.wait_finish = vb2_ops_wait_finish,
.start_streaming = start_streaming,
.stop_streaming = stop_streaming,
};
static void <API key>(struct fimc_lite *fimc)
{
unsigned long flags;
spin_lock_irqsave(&fimc->slock, flags);
memset(&fimc->events, 0, sizeof(fimc->events));
<API key>(&fimc->slock, flags);
}
static int fimc_lite_open(struct file *file)
{
struct fimc_lite *fimc = video_drvdata(file);
struct media_entity *me = &fimc->ve.vdev.entity;
int ret;
mutex_lock(&fimc->lock);
if (atomic_read(&fimc->out_path) != FIMC_IO_DMA) {
ret = -EBUSY;
goto unlock;
}
set_bit(ST_FLITE_IN_USE, &fimc->state);
ret = pm_runtime_get_sync(&fimc->pdev->dev);
if (ret < 0)
goto unlock;
ret = v4l2_fh_open(file);
if (ret < 0)
goto err_pm;
if (!<API key>(file) ||
atomic_read(&fimc->out_path) != FIMC_IO_DMA)
goto unlock;
mutex_lock(&me->parent->graph_mutex);
ret = fimc_pipeline_call(&fimc->ve, open, me, true);
/* Mark video pipeline ending at this video node as in use. */
if (ret == 0)
me->use_count++;
mutex_unlock(&me->parent->graph_mutex);
if (!ret) {
<API key>(fimc);
goto unlock;
}
v4l2_fh_release(file);
err_pm:
pm_runtime_put_sync(&fimc->pdev->dev);
clear_bit(ST_FLITE_IN_USE, &fimc->state);
unlock:
mutex_unlock(&fimc->lock);
return ret;
}
static int fimc_lite_release(struct file *file)
{
struct fimc_lite *fimc = video_drvdata(file);
struct media_entity *entity = &fimc->ve.vdev.entity;
mutex_lock(&fimc->lock);
if (<API key>(file) &&
atomic_read(&fimc->out_path) == FIMC_IO_DMA) {
if (fimc->streaming) {
<API key>(entity);
fimc->streaming = false;
}
<API key>(fimc, false);
fimc_pipeline_call(&fimc->ve, close);
clear_bit(ST_FLITE_IN_USE, &fimc->state);
mutex_lock(&entity->parent->graph_mutex);
entity->use_count
mutex_unlock(&entity->parent->graph_mutex);
}
_vb2_fop_release(file, NULL);
pm_runtime_put(&fimc->pdev->dev);
clear_bit(ST_FLITE_SUSPENDED, &fimc->state);
mutex_unlock(&fimc->lock);
return 0;
}
static const struct <API key> fimc_lite_fops = {
.owner = THIS_MODULE,
.open = fimc_lite_open,
.release = fimc_lite_release,
.poll = vb2_fop_poll,
.unlocked_ioctl = video_ioctl2,
.mmap = vb2_fop_mmap,
};
/*
* Format and crop negotiation helpers
*/
static const struct fimc_fmt *<API key>(struct fimc_lite *fimc,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *format)
{
struct flite_drvdata *dd = fimc->dd;
struct v4l2_mbus_framefmt *mf = &format->format;
const struct fimc_fmt *fmt = NULL;
if (format->pad == FLITE_SD_PAD_SINK) {
<API key>(&mf->width, 8, dd->max_width,
ffs(dd->out_width_align) - 1,
&mf->height, 0, dd->max_height, 0, 0);
fmt = <API key>(NULL, &mf->code, 0, 0);
if (WARN_ON(!fmt))
return NULL;
mf->colorspace = fmt->colorspace;
mf->code = fmt->mbus_code;
} else {
struct flite_frame *sink = &fimc->inp_frame;
struct v4l2_mbus_framefmt *sink_fmt;
struct v4l2_rect *rect;
if (format->which == <API key>) {
sink_fmt = <API key>(fh,
FLITE_SD_PAD_SINK);
mf->code = sink_fmt->code;
mf->colorspace = sink_fmt->colorspace;
rect = <API key>(fh,
FLITE_SD_PAD_SINK);
} else {
mf->code = sink->fmt->mbus_code;
mf->colorspace = sink->fmt->colorspace;
rect = &sink->rect;
}
/* Allow changing format only on sink pad */
mf->width = rect->width;
mf->height = rect->height;
}
mf->field = V4L2_FIELD_NONE;
v4l2_dbg(1, debug, &fimc->subdev, "code: %#x (%d), %dx%d\n",
mf->code, mf->colorspace, mf->width, mf->height);
return fmt;
}
static void fimc_lite_try_crop(struct fimc_lite *fimc, struct v4l2_rect *r)
{
struct flite_frame *frame = &fimc->inp_frame;
<API key>(&r->width, 0, frame->f_width, 0,
&r->height, 0, frame->f_height, 0, 0);
/* Adjust left/top if cropping rectangle got out of bounds */
r->left = clamp_t(u32, r->left, 0, frame->f_width - r->width);
r->left = round_down(r->left, fimc->dd->win_hor_offs_align);
r->top = clamp_t(u32, r->top, 0, frame->f_height - r->height);
v4l2_dbg(1, debug, &fimc->subdev, "(%d,%d)/%dx%d, sink fmt: %dx%d\n",
r->left, r->top, r->width, r->height,
frame->f_width, frame->f_height);
}
static void <API key>(struct fimc_lite *fimc, struct v4l2_rect *r)
{
struct flite_frame *frame = &fimc->out_frame;
struct v4l2_rect *crop_rect = &fimc->inp_frame.rect;
/* Scaling is not supported so we enforce compose rectangle size
same as size of the sink crop rectangle. */
r->width = crop_rect->width;
r->height = crop_rect->height;
/* Adjust left/top if the composing rectangle got out of bounds */
r->left = clamp_t(u32, r->left, 0, frame->f_width - r->width);
r->left = round_down(r->left, fimc->dd->out_hor_offs_align);
r->top = clamp_t(u32, r->top, 0, fimc->out_frame.f_height - r->height);
v4l2_dbg(1, debug, &fimc->subdev, "(%d,%d)/%dx%d, source fmt: %dx%d\n",
r->left, r->top, r->width, r->height,
frame->f_width, frame->f_height);
}
/*
* Video node ioctl operations
*/
static int fimc_lite_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct fimc_lite *fimc = video_drvdata(file);
strlcpy(cap->driver, FIMC_LITE_DRV_NAME, sizeof(cap->driver));
strlcpy(cap->card, FIMC_LITE_DRV_NAME, sizeof(cap->card));
snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s",
dev_name(&fimc->pdev->dev));
cap->device_caps = V4L2_CAP_STREAMING;
cap->capabilities = cap->device_caps | <API key>;
return 0;
}
static int <API key>(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
const struct fimc_fmt *fmt;
if (f->index >= ARRAY_SIZE(fimc_lite_formats))
return -EINVAL;
fmt = &fimc_lite_formats[f->index];
strlcpy(f->description, fmt->name, sizeof(f->description));
f->pixelformat = fmt->fourcc;
return 0;
}
static int <API key>(struct file *file, void *fh,
struct v4l2_format *f)
{
struct fimc_lite *fimc = video_drvdata(file);
struct <API key> *pixm = &f->fmt.pix_mp;
struct <API key> *plane_fmt = &pixm->plane_fmt[0];
struct flite_frame *frame = &fimc->out_frame;
const struct fimc_fmt *fmt = frame->fmt;
plane_fmt->bytesperline = (frame->f_width * fmt->depth[0]) / 8;
plane_fmt->sizeimage = plane_fmt->bytesperline * frame->f_height;
pixm->num_planes = fmt->memplanes;
pixm->pixelformat = fmt->fourcc;
pixm->width = frame->f_width;
pixm->height = frame->f_height;
pixm->field = V4L2_FIELD_NONE;
pixm->colorspace = fmt->colorspace;
return 0;
}
static int fimc_lite_try_fmt(struct fimc_lite *fimc,
struct <API key> *pixm,
const struct fimc_fmt **ffmt)
{
u32 bpl = pixm->plane_fmt[0].bytesperline;
struct flite_drvdata *dd = fimc->dd;
const struct fimc_fmt *inp_fmt = fimc->inp_frame.fmt;
const struct fimc_fmt *fmt;
if (WARN_ON(inp_fmt == NULL))
return -EINVAL;
/*
* We allow some flexibility only for YUV formats. In case of raw
* raw Bayer the FIMC-LITE's output format must match its camera
* interface input format.
*/
if (inp_fmt->flags & FMT_FLAGS_YUV)
fmt = <API key>(&pixm->pixelformat, NULL,
inp_fmt->flags, 0);
else
fmt = inp_fmt;
if (WARN_ON(fmt == NULL))
return -EINVAL;
if (ffmt)
*ffmt = fmt;
<API key>(&pixm->width, 8, dd->max_width,
ffs(dd->out_width_align) - 1,
&pixm->height, 0, dd->max_height, 0, 0);
if ((bpl == 0 || ((bpl * 8) / fmt->depth[0]) < pixm->width))
pixm->plane_fmt[0].bytesperline = (pixm->width *
fmt->depth[0]) / 8;
if (pixm->plane_fmt[0].sizeimage == 0)
pixm->plane_fmt[0].sizeimage = (pixm->width * pixm->height *
fmt->depth[0]) / 8;
pixm->num_planes = fmt->memplanes;
pixm->pixelformat = fmt->fourcc;
pixm->colorspace = fmt->colorspace;
pixm->field = V4L2_FIELD_NONE;
return 0;
}
static int <API key>(struct file *file, void *fh,
struct v4l2_format *f)
{
struct fimc_lite *fimc = video_drvdata(file);
return fimc_lite_try_fmt(fimc, &f->fmt.pix_mp, NULL);
}
static int <API key>(struct file *file, void *priv,
struct v4l2_format *f)
{
struct <API key> *pixm = &f->fmt.pix_mp;
struct fimc_lite *fimc = video_drvdata(file);
struct flite_frame *frame = &fimc->out_frame;
const struct fimc_fmt *fmt = NULL;
int ret;
if (vb2_is_busy(&fimc->vb_queue))
return -EBUSY;
ret = fimc_lite_try_fmt(fimc, &f->fmt.pix_mp, &fmt);
if (ret < 0)
return ret;
frame->fmt = fmt;
fimc->payload[0] = max((pixm->width * pixm->height * fmt->depth[0]) / 8,
pixm->plane_fmt[0].sizeimage);
frame->f_width = pixm->width;
frame->f_height = pixm->height;
return 0;
}
static int <API key>(struct fimc_lite *fimc)
{
struct v4l2_subdev *sd = &fimc->subdev;
struct v4l2_subdev_format sink_fmt, src_fmt;
struct media_pad *pad;
int ret;
while (1) {
/* Retrieve format at the sink pad */
pad = &sd->entity.pads[0];
if (!(pad->flags & MEDIA_PAD_FL_SINK))
break;
/* Don't call FIMC subdev operation to avoid nested locking */
if (sd == &fimc->subdev) {
struct flite_frame *ff = &fimc->out_frame;
sink_fmt.format.width = ff->f_width;
sink_fmt.format.height = ff->f_height;
sink_fmt.format.code = fimc->inp_frame.fmt->mbus_code;
} else {
sink_fmt.pad = pad->index;
sink_fmt.which = <API key>;
ret = v4l2_subdev_call(sd, pad, get_fmt, NULL,
&sink_fmt);
if (ret < 0 && ret != -ENOIOCTLCMD)
return -EPIPE;
}
/* Retrieve format at the source pad */
pad = <API key>(pad);
if (pad == NULL ||
media_entity_type(pad->entity) != <API key>)
break;
sd = <API key>(pad->entity);
src_fmt.pad = pad->index;
src_fmt.which = <API key>;
ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &src_fmt);
if (ret < 0 && ret != -ENOIOCTLCMD)
return -EPIPE;
if (src_fmt.format.width != sink_fmt.format.width ||
src_fmt.format.height != sink_fmt.format.height ||
src_fmt.format.code != sink_fmt.format.code)
return -EPIPE;
}
return 0;
}
static int fimc_lite_streamon(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct fimc_lite *fimc = video_drvdata(file);
struct media_entity *entity = &fimc->ve.vdev.entity;
int ret;
if (fimc_lite_active(fimc))
return -EBUSY;
ret = <API key>(entity, &fimc->ve.pipe->mp);
if (ret < 0)
return ret;
ret = <API key>(fimc);
if (ret < 0)
goto err_p_stop;
fimc->sensor = <API key>(&fimc->subdev.entity);
ret = vb2_ioctl_streamon(file, priv, type);
if (!ret) {
fimc->streaming = true;
return ret;
}
err_p_stop:
<API key>(entity);
return 0;
}
static int fimc_lite_streamoff(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct fimc_lite *fimc = video_drvdata(file);
int ret;
ret = vb2_ioctl_streamoff(file, priv, type);
if (ret < 0)
return ret;
<API key>(&fimc->ve.vdev.entity);
fimc->streaming = false;
return 0;
}
static int fimc_lite_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *reqbufs)
{
struct fimc_lite *fimc = video_drvdata(file);
int ret;
reqbufs->count = max_t(u32, FLITE_REQ_BUFS_MIN, reqbufs->count);
ret = vb2_ioctl_reqbufs(file, priv, reqbufs);
if (!ret)
fimc->reqbufs_count = reqbufs->count;
return ret;
}
/* Return 1 if rectangle a is enclosed in rectangle b, or 0 otherwise. */
static int enclosed_rectangle(struct v4l2_rect *a, struct v4l2_rect *b)
{
if (a->left < b->left || a->top < b->top)
return 0;
if (a->left + a->width > b->left + b->width)
return 0;
if (a->top + a->height > b->top + b->height)
return 0;
return 1;
}
static int <API key>(struct file *file, void *fh,
struct v4l2_selection *sel)
{
struct fimc_lite *fimc = video_drvdata(file);
struct flite_frame *f = &fimc->out_frame;
if (sel->type != <API key>)
return -EINVAL;
switch (sel->target) {
case <API key>:
case <API key>:
sel->r.left = 0;
sel->r.top = 0;
sel->r.width = f->f_width;
sel->r.height = f->f_height;
return 0;
case <API key>:
sel->r = f->rect;
return 0;
}
return -EINVAL;
}
static int <API key>(struct file *file, void *fh,
struct v4l2_selection *sel)
{
struct fimc_lite *fimc = video_drvdata(file);
struct flite_frame *f = &fimc->out_frame;
struct v4l2_rect rect = sel->r;
unsigned long flags;
if (sel->type != <API key> ||
sel->target != <API key>)
return -EINVAL;
<API key>(fimc, &rect);
if ((sel->flags & V4L2_SEL_FLAG_LE) &&
!enclosed_rectangle(&rect, &sel->r))
return -ERANGE;
if ((sel->flags & V4L2_SEL_FLAG_GE) &&
!enclosed_rectangle(&sel->r, &rect))
return -ERANGE;
sel->r = rect;
spin_lock_irqsave(&fimc->slock, flags);
f->rect = rect;
set_bit(ST_FLITE_CONFIG, &fimc->state);
<API key>(&fimc->slock, flags);
return 0;
}
static const struct v4l2_ioctl_ops fimc_lite_ioctl_ops = {
.vidioc_querycap = fimc_lite_querycap,
.<API key> = <API key>,
.<API key> = <API key>,
.<API key> = <API key>,
.<API key> = <API key>,
.vidioc_g_selection = <API key>,
.vidioc_s_selection = <API key>,
.vidioc_reqbufs = fimc_lite_reqbufs,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_prepare_buf = <API key>,
.vidioc_create_bufs = <API key>,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_streamon = fimc_lite_streamon,
.vidioc_streamoff = fimc_lite_streamoff,
};
/* Capture subdev media entity operations */
static int <API key>(struct media_entity *entity,
const struct media_pad *local,
const struct media_pad *remote, u32 flags)
{
struct v4l2_subdev *sd = <API key>(entity);
struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
unsigned int remote_ent_type = media_entity_type(remote->entity);
int ret = 0;
if (WARN_ON(fimc == NULL))
return 0;
v4l2_dbg(1, debug, sd, "%s: %s --> %s, flags: 0x%x. source_id: 0x%x\n",
__func__, remote->entity->name, local->entity->name,
flags, fimc-><API key>);
switch (local->index) {
case FLITE_SD_PAD_SINK:
if (remote_ent_type != <API key>) {
ret = -EINVAL;
break;
}
if (flags & <API key>) {
if (fimc-><API key> == 0)
fimc-><API key> = sd->grp_id;
else
ret = -EBUSY;
} else {
fimc-><API key> = 0;
fimc->sensor = NULL;
}
break;
case <API key>:
if (!(flags & <API key>))
atomic_set(&fimc->out_path, FIMC_IO_NONE);
else if (remote_ent_type == MEDIA_ENT_T_DEVNODE)
atomic_set(&fimc->out_path, FIMC_IO_DMA);
else
ret = -EINVAL;
break;
case <API key>:
if (!(flags & <API key>))
atomic_set(&fimc->out_path, FIMC_IO_NONE);
else if (remote_ent_type == <API key>)
atomic_set(&fimc->out_path, FIMC_IO_ISP);
else
ret = -EINVAL;
break;
default:
v4l2_err(sd, "Invalid pad index\n");
ret = -EINVAL;
}
mb();
return ret;
}
static const struct <API key> <API key> = {
.link_setup = <API key>,
};
static int <API key>(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct <API key> *code)
{
const struct fimc_fmt *fmt;
fmt = <API key>(NULL, NULL, 0, code->index);
if (!fmt)
return -EINVAL;
code->code = fmt->mbus_code;
return 0;
}
static struct v4l2_mbus_framefmt *<API key>(
struct v4l2_subdev_fh *fh, unsigned int pad)
{
if (pad != FLITE_SD_PAD_SINK)
pad = <API key>;
return <API key>(fh, pad);
}
static int <API key>(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt *mf = &fmt->format;
struct flite_frame *f = &fimc->inp_frame;
if (fmt->which == <API key>) {
mf = <API key>(fh, fmt->pad);
fmt->format = *mf;
return 0;
}
mutex_lock(&fimc->lock);
mf->colorspace = f->fmt->colorspace;
mf->code = f->fmt->mbus_code;
if (fmt->pad == FLITE_SD_PAD_SINK) {
/* full camera input frame size */
mf->width = f->f_width;
mf->height = f->f_height;
} else {
/* crop size */
mf->width = f->rect.width;
mf->height = f->rect.height;
}
mutex_unlock(&fimc->lock);
return 0;
}
static int <API key>(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt *mf = &fmt->format;
struct flite_frame *sink = &fimc->inp_frame;
struct flite_frame *source = &fimc->out_frame;
const struct fimc_fmt *ffmt;
v4l2_dbg(1, debug, sd, "pad%d: code: 0x%x, %dx%d\n",
fmt->pad, mf->code, mf->width, mf->height);
mutex_lock(&fimc->lock);
if ((atomic_read(&fimc->out_path) == FIMC_IO_ISP &&
sd->entity.stream_count > 0) ||
(atomic_read(&fimc->out_path) == FIMC_IO_DMA &&
vb2_is_busy(&fimc->vb_queue))) {
mutex_unlock(&fimc->lock);
return -EBUSY;
}
ffmt = <API key>(fimc, fh, fmt);
if (fmt->which == <API key>) {
struct v4l2_mbus_framefmt *src_fmt;
mf = <API key>(fh, fmt->pad);
*mf = fmt->format;
if (fmt->pad == FLITE_SD_PAD_SINK) {
unsigned int pad = <API key>;
src_fmt = <API key>(fh, pad);
*src_fmt = *mf;
}
mutex_unlock(&fimc->lock);
return 0;
}
if (fmt->pad == FLITE_SD_PAD_SINK) {
sink->f_width = mf->width;
sink->f_height = mf->height;
sink->fmt = ffmt;
/* Set sink crop rectangle */
sink->rect.width = mf->width;
sink->rect.height = mf->height;
sink->rect.left = 0;
sink->rect.top = 0;
/* Reset source format and crop rectangle */
source->rect = sink->rect;
source->f_width = mf->width;
source->f_height = mf->height;
}
mutex_unlock(&fimc->lock);
return 0;
}
static int <API key>(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct <API key> *sel)
{
struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
struct flite_frame *f = &fimc->inp_frame;
if ((sel->target != V4L2_SEL_TGT_CROP &&
sel->target != <API key>) ||
sel->pad != FLITE_SD_PAD_SINK)
return -EINVAL;
if (sel->which == <API key>) {
sel->r = *<API key>(fh, sel->pad);
return 0;
}
mutex_lock(&fimc->lock);
if (sel->target == V4L2_SEL_TGT_CROP) {
sel->r = f->rect;
} else {
sel->r.left = 0;
sel->r.top = 0;
sel->r.width = f->f_width;
sel->r.height = f->f_height;
}
mutex_unlock(&fimc->lock);
v4l2_dbg(1, debug, sd, "%s: (%d,%d) %dx%d, f_w: %d, f_h: %d\n",
__func__, f->rect.left, f->rect.top, f->rect.width,
f->rect.height, f->f_width, f->f_height);
return 0;
}
static int <API key>(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct <API key> *sel)
{
struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
struct flite_frame *f = &fimc->inp_frame;
int ret = 0;
if (sel->target != V4L2_SEL_TGT_CROP || sel->pad != FLITE_SD_PAD_SINK)
return -EINVAL;
mutex_lock(&fimc->lock);
fimc_lite_try_crop(fimc, &sel->r);
if (sel->which == <API key>) {
*<API key>(fh, sel->pad) = sel->r;
} else {
unsigned long flags;
spin_lock_irqsave(&fimc->slock, flags);
f->rect = sel->r;
/* Same crop rectangle on the source pad */
fimc->out_frame.rect = sel->r;
set_bit(ST_FLITE_CONFIG, &fimc->state);
<API key>(&fimc->slock, flags);
}
mutex_unlock(&fimc->lock);
v4l2_dbg(1, debug, sd, "%s: (%d,%d) %dx%d, f_w: %d, f_h: %d\n",
__func__, f->rect.left, f->rect.top, f->rect.width,
f->rect.height, f->f_width, f->f_height);
return ret;
}
static int <API key>(struct v4l2_subdev *sd, int on)
{
struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
unsigned long flags;
int ret;
/*
* Find sensor subdev linked to FIMC-LITE directly or through
* MIPI-CSIS. This is required for configuration where FIMC-LITE
* is used as a subdev only and feeds data internally to FIMC-IS.
* The pipeline links are protected through entity.stream_count
* so there is no need to take the media graph mutex here.
*/
fimc->sensor = <API key>(&sd->entity);
if (atomic_read(&fimc->out_path) != FIMC_IO_ISP)
return -ENOIOCTLCMD;
mutex_lock(&fimc->lock);
if (on) {
flite_hw_reset(fimc);
ret = fimc_lite_hw_init(fimc, true);
if (!ret) {
spin_lock_irqsave(&fimc->slock, flags);
<API key>(fimc);
<API key>(&fimc->slock, flags);
}
} else {
set_bit(ST_FLITE_OFF, &fimc->state);
spin_lock_irqsave(&fimc->slock, flags);
<API key>(fimc);
<API key>(&fimc->slock, flags);
ret = wait_event_timeout(fimc->irq_queue,
!test_bit(ST_FLITE_OFF, &fimc->state),
msecs_to_jiffies(200));
if (ret == 0)
v4l2_err(sd, "s_stream(0) timeout\n");
clear_bit(ST_FLITE_RUN, &fimc->state);
}
mutex_unlock(&fimc->lock);
return ret;
}
static int <API key>(struct v4l2_subdev *sd)
{
struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
flite_hw_dump_regs(fimc, __func__);
return 0;
}
static int <API key>(struct v4l2_subdev *sd)
{
struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
struct vb2_queue *q = &fimc->vb_queue;
struct video_device *vfd = &fimc->ve.vdev;
int ret;
memset(vfd, 0, sizeof(*vfd));
atomic_set(&fimc->out_path, FIMC_IO_DMA);
snprintf(vfd->name, sizeof(vfd->name), "fimc-lite.%d.capture",
fimc->index);
vfd->fops = &fimc_lite_fops;
vfd->ioctl_ops = &fimc_lite_ioctl_ops;
vfd->v4l2_dev = sd->v4l2_dev;
vfd->minor = -1;
vfd->release = <API key>;
vfd->queue = q;
fimc->reqbufs_count = 0;
INIT_LIST_HEAD(&fimc->pending_buf_q);
INIT_LIST_HEAD(&fimc->active_buf_q);
memset(q, 0, sizeof(*q));
q->type = <API key>;
q->io_modes = VB2_MMAP | VB2_USERPTR;
q->ops = &fimc_lite_qops;
q->mem_ops = &<API key>;
q->buf_struct_size = sizeof(struct flite_buffer);
q->drv_priv = fimc;
q->timestamp_flags = <API key>;
q->lock = &fimc->lock;
ret = vb2_queue_init(q);
if (ret < 0)
return ret;
fimc->vd_pad.flags = MEDIA_PAD_FL_SINK;
ret = media_entity_init(&vfd->entity, 1, &fimc->vd_pad, 0);
if (ret < 0)
return ret;
video_set_drvdata(vfd, fimc);
fimc->ve.pipe = <API key>(sd);
ret = <API key>(vfd, VFL_TYPE_GRABBER, -1);
if (ret < 0) {
<API key>(&vfd->entity);
fimc->ve.pipe = NULL;
return ret;
}
v4l2_info(sd->v4l2_dev, "Registered %s as /dev/%s\n",
vfd->name, <API key>(vfd));
return 0;
}
static void <API key>(struct v4l2_subdev *sd)
{
struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
if (fimc == NULL)
return;
mutex_lock(&fimc->lock);
if (video_is_registered(&fimc->ve.vdev)) {
<API key>(&fimc->ve.vdev);
<API key>(&fimc->ve.vdev.entity);
fimc->ve.pipe = NULL;
}
mutex_unlock(&fimc->lock);
}
static const struct <API key> <API key> = {
.registered = <API key>,
.unregistered = <API key>,
};
static const struct v4l2_subdev_pad_ops <API key> = {
.enum_mbus_code = <API key>,
.get_selection = <API key>,
.set_selection = <API key>,
.get_fmt = <API key>,
.set_fmt = <API key>,
};
static const struct <API key> <API key> = {
.s_stream = <API key>,
};
static const struct <API key> fimc_lite_core_ops = {
.log_status = <API key>,
};
static struct v4l2_subdev_ops <API key> = {
.core = &fimc_lite_core_ops,
.video = &<API key>,
.pad = &<API key>,
};
static int fimc_lite_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct fimc_lite *fimc = container_of(ctrl->handler, struct fimc_lite,
ctrl_handler);
set_bit(ST_FLITE_CONFIG, &fimc->state);
return 0;
}
static const struct v4l2_ctrl_ops fimc_lite_ctrl_ops = {
.s_ctrl = fimc_lite_s_ctrl,
};
static const struct v4l2_ctrl_config fimc_lite_ctrl = {
.ops = &fimc_lite_ctrl_ops,
.id = <API key> | 0x1001,
.type = <API key>,
.name = "Test Pattern 640x480",
.step = 1,
};
static void <API key>(struct fimc_lite *fimc)
{
struct flite_frame *sink = &fimc->inp_frame;
struct flite_frame *source = &fimc->out_frame;
sink->fmt = &fimc_lite_formats[0];
sink->f_width = FLITE_DEFAULT_WIDTH;
sink->f_height = <API key>;
sink->rect.width = FLITE_DEFAULT_WIDTH;
sink->rect.height = <API key>;
sink->rect.left = 0;
sink->rect.top = 0;
*source = *sink;
}
static int <API key>(struct fimc_lite *fimc)
{
struct v4l2_ctrl_handler *handler = &fimc->ctrl_handler;
struct v4l2_subdev *sd = &fimc->subdev;
int ret;
v4l2_subdev_init(sd, &<API key>);
sd->flags |= <API key>;
snprintf(sd->name, sizeof(sd->name), "FIMC-LITE.%d", fimc->index);
fimc->subdev_pads[FLITE_SD_PAD_SINK].flags = MEDIA_PAD_FL_SINK;
fimc->subdev_pads[<API key>].flags = MEDIA_PAD_FL_SOURCE;
fimc->subdev_pads[<API key>].flags = MEDIA_PAD_FL_SOURCE;
ret = media_entity_init(&sd->entity, FLITE_SD_PADS_NUM,
fimc->subdev_pads, 0);
if (ret)
return ret;
<API key>(handler, 1);
fimc->test_pattern = <API key>(handler, &fimc_lite_ctrl,
NULL);
if (handler->error) {
<API key>(&sd->entity);
return handler->error;
}
sd->ctrl_handler = handler;
sd->internal_ops = &<API key>;
sd->entity.ops = &<API key>;
sd->owner = THIS_MODULE;
v4l2_set_subdevdata(sd, fimc);
return 0;
}
static void <API key>(struct fimc_lite *fimc)
{
struct v4l2_subdev *sd = &fimc->subdev;
<API key>(sd);
<API key>(&sd->entity);
<API key>(&fimc->ctrl_handler);
v4l2_set_subdevdata(sd, NULL);
}
static void fimc_lite_clk_put(struct fimc_lite *fimc)
{
if (IS_ERR(fimc->clock))
return;
clk_unprepare(fimc->clock);
clk_put(fimc->clock);
fimc->clock = ERR_PTR(-EINVAL);
}
static int fimc_lite_clk_get(struct fimc_lite *fimc)
{
int ret;
fimc->clock = clk_get(&fimc->pdev->dev, FLITE_CLK_NAME);
if (IS_ERR(fimc->clock))
return PTR_ERR(fimc->clock);
ret = clk_prepare(fimc->clock);
if (ret < 0) {
clk_put(fimc->clock);
fimc->clock = ERR_PTR(-EINVAL);
}
return ret;
}
static const struct of_device_id flite_of_match[];
static int fimc_lite_probe(struct platform_device *pdev)
{
struct flite_drvdata *drv_data = NULL;
struct device *dev = &pdev->dev;
const struct of_device_id *of_id;
struct fimc_lite *fimc;
struct resource *res;
int ret;
if (!dev->of_node)
return -ENODEV;
fimc = devm_kzalloc(dev, sizeof(*fimc), GFP_KERNEL);
if (!fimc)
return -ENOMEM;
of_id = of_match_node(flite_of_match, dev->of_node);
if (of_id)
drv_data = (struct flite_drvdata *)of_id->data;
fimc->index = of_alias_get_id(dev->of_node, "fimc-lite");
if (!drv_data || fimc->index >= drv_data->num_instances ||
fimc->index < 0) {
dev_err(dev, "Wrong %s node alias\n",
dev->of_node->full_name);
return -EINVAL;
}
fimc->dd = drv_data;
fimc->pdev = pdev;
init_waitqueue_head(&fimc->irq_queue);
spin_lock_init(&fimc->slock);
mutex_init(&fimc->lock);
res = <API key>(pdev, IORESOURCE_MEM, 0);
fimc->regs = <API key>(dev, res);
if (IS_ERR(fimc->regs))
return PTR_ERR(fimc->regs);
res = <API key>(pdev, IORESOURCE_IRQ, 0);
if (res == NULL) {
dev_err(dev, "Failed to get IRQ resource\n");
return -ENXIO;
}
ret = fimc_lite_clk_get(fimc);
if (ret)
return ret;
ret = devm_request_irq(dev, res->start, flite_irq_handler,
0, dev_name(dev), fimc);
if (ret) {
dev_err(dev, "Failed to install irq (%d)\n", ret);
goto err_clk_put;
}
/* The video node will be created within the subdev's registered() op */
ret = <API key>(fimc);
if (ret)
goto err_clk_put;
<API key>(pdev, fimc);
pm_runtime_enable(dev);
if (!pm_runtime_enabled(dev)) {
ret = clk_enable(fimc->clock);
if (ret < 0)
goto err_sd;
}
fimc->alloc_ctx = <API key>(dev);
if (IS_ERR(fimc->alloc_ctx)) {
ret = PTR_ERR(fimc->alloc_ctx);
goto err_clk_dis;
}
<API key>(fimc);
dev_dbg(dev, "FIMC-LITE.%d registered successfully\n",
fimc->index);
return 0;
err_clk_dis:
if (!pm_runtime_enabled(dev))
clk_disable(fimc->clock);
err_sd:
<API key>(fimc);
err_clk_put:
fimc_lite_clk_put(fimc);
return ret;
}
#ifdef CONFIG_PM_RUNTIME
static int <API key>(struct device *dev)
{
struct fimc_lite *fimc = dev_get_drvdata(dev);
clk_enable(fimc->clock);
return 0;
}
static int <API key>(struct device *dev)
{
struct fimc_lite *fimc = dev_get_drvdata(dev);
clk_disable(fimc->clock);
return 0;
}
#endif
#ifdef CONFIG_PM_SLEEP
static int fimc_lite_resume(struct device *dev)
{
struct fimc_lite *fimc = dev_get_drvdata(dev);
struct flite_buffer *buf;
unsigned long flags;
int i;
spin_lock_irqsave(&fimc->slock, flags);
if (!test_and_clear_bit(ST_LPM, &fimc->state) ||
!test_bit(ST_FLITE_IN_USE, &fimc->state)) {
<API key>(&fimc->slock, flags);
return 0;
}
flite_hw_reset(fimc);
<API key>(&fimc->slock, flags);
if (!test_and_clear_bit(ST_FLITE_SUSPENDED, &fimc->state))
return 0;
INIT_LIST_HEAD(&fimc->active_buf_q);
fimc_pipeline_call(&fimc->ve, open,
&fimc->ve.vdev.entity, false);
fimc_lite_hw_init(fimc, atomic_read(&fimc->out_path) == FIMC_IO_ISP);
clear_bit(ST_FLITE_SUSPENDED, &fimc->state);
for (i = 0; i < fimc->reqbufs_count; i++) {
if (list_empty(&fimc->pending_buf_q))
break;
buf = <API key>(fimc);
buffer_queue(&buf->vb);
}
return 0;
}
static int fimc_lite_suspend(struct device *dev)
{
struct fimc_lite *fimc = dev_get_drvdata(dev);
bool suspend = test_bit(ST_FLITE_IN_USE, &fimc->state);
int ret;
if (test_and_set_bit(ST_LPM, &fimc->state))
return 0;
ret = <API key>(fimc, suspend);
if (ret < 0 || !fimc_lite_active(fimc))
return ret;
return fimc_pipeline_call(&fimc->ve, close);
}
#endif /* CONFIG_PM_SLEEP */
static int fimc_lite_remove(struct platform_device *pdev)
{
struct fimc_lite *fimc = <API key>(pdev);
struct device *dev = &pdev->dev;
pm_runtime_disable(dev);
<API key>(dev);
<API key>(fimc);
<API key>(fimc->alloc_ctx);
fimc_lite_clk_put(fimc);
dev_info(dev, "Driver unloaded\n");
return 0;
}
static const struct dev_pm_ops fimc_lite_pm_ops = {
<API key>(fimc_lite_suspend, fimc_lite_resume)
SET_RUNTIME_PM_OPS(<API key>, <API key>,
NULL)
};
/* EXYNOS4212, EXYNOS4412 */
static struct flite_drvdata <API key> = {
.max_width = 8192,
.max_height = 8192,
.out_width_align = 8,
.win_hor_offs_align = 2,
.out_hor_offs_align = 8,
.max_dma_bufs = 1,
.num_instances = 2,
};
/* EXYNOS5250 */
static struct flite_drvdata <API key> = {
.max_width = 8192,
.max_height = 8192,
.out_width_align = 8,
.win_hor_offs_align = 2,
.out_hor_offs_align = 8,
.max_dma_bufs = 32,
.num_instances = 3,
};
static const struct of_device_id flite_of_match[] = {
{
.compatible = "samsung,<API key>",
.data = &<API key>,
},
{
.compatible = "samsung,<API key>",
.data = &<API key>,
},
{ /* sentinel */ },
};
MODULE_DEVICE_TABLE(of, flite_of_match);
static struct platform_driver fimc_lite_driver = {
.probe = fimc_lite_probe,
.remove = fimc_lite_remove,
.driver = {
.of_match_table = flite_of_match,
.name = FIMC_LITE_DRV_NAME,
.owner = THIS_MODULE,
.pm = &fimc_lite_pm_ops,
}
};
<API key>(fimc_lite_driver);
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" FIMC_LITE_DRV_NAME);
|
#include "ntoskrnl.h"
#define NDEBUG
#include "debug.h"
ULONG
NTAPI
CmCheckRegistry(IN PCMHIVE RegistryHive,
IN ULONG Flags)
{
/* FIXME: HACK! */
DPRINT1("CmCheckRegistry(0x%p, %lu) is UNIMPLEMENTED!\n", RegistryHive, Flags);
return 0;
}
|
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
#include "config.h"
#include <string.h>
#include <gconf/gconf-client.h>
#include <libempathy/empathy-utils.h>
#include "empathy-conf.h"
#define DEBUG_FLAG EMPATHY_DEBUG_OTHER
#include <libempathy/empathy-debug.h>
#define EMPATHY_CONF_ROOT "/apps/empathy"
#define <API key> "/desktop/gnome/interface"
#define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyConf)
typedef struct {
GConfClient *gconf_client;
} EmpathyConfPriv;
typedef struct {
EmpathyConf *conf;
<API key> func;
gpointer user_data;
} <API key>;
static void conf_finalize (GObject *object);
G_DEFINE_TYPE (EmpathyConf, empathy_conf, G_TYPE_OBJECT);
static EmpathyConf *global_conf = NULL;
static void
<API key> (EmpathyConfClass *class)
{
GObjectClass *object_class;
object_class = G_OBJECT_CLASS (class);
object_class->finalize = conf_finalize;
<API key> (object_class, sizeof (EmpathyConfPriv));
}
static void
empathy_conf_init (EmpathyConf *conf)
{
EmpathyConfPriv *priv = <API key> (conf,
EMPATHY_TYPE_CONF, EmpathyConfPriv);
conf->priv = priv;
priv->gconf_client = <API key> ();
<API key> (priv->gconf_client,
EMPATHY_CONF_ROOT,
<API key>,
NULL);
<API key> (priv->gconf_client,
<API key>,
<API key>,
NULL);
}
static void
conf_finalize (GObject *object)
{
EmpathyConfPriv *priv;
priv = GET_PRIV (object);
<API key> (priv->gconf_client,
EMPATHY_CONF_ROOT,
NULL);
<API key> (priv->gconf_client,
<API key>,
NULL);
g_object_unref (priv->gconf_client);
G_OBJECT_CLASS (<API key>)->finalize (object);
}
EmpathyConf *
empathy_conf_get (void)
{
if (!global_conf) {
global_conf = g_object_new (EMPATHY_TYPE_CONF, NULL);
}
return global_conf;
}
void
<API key> (void)
{
if (global_conf) {
g_object_unref (global_conf);
global_conf = NULL;
}
}
gboolean
<API key> (EmpathyConf *conf,
const gchar *key,
gint value)
{
EmpathyConfPriv *priv;
<API key> (EMPATHY_IS_CONF (conf), FALSE);
DEBUG ("Setting int:'%s' to %d", key, value);
priv = GET_PRIV (conf);
return <API key> (priv->gconf_client,
key,
value,
NULL);
}
gboolean
<API key> (EmpathyConf *conf,
const gchar *key,
gint *value)
{
EmpathyConfPriv *priv;
GError *error = NULL;
*value = 0;
<API key> (EMPATHY_IS_CONF (conf), FALSE);
<API key> (value != NULL, FALSE);
priv = GET_PRIV (conf);
*value = <API key> (priv->gconf_client,
key,
&error);
if (error) {
g_error_free (error);
return FALSE;
}
return TRUE;
}
gboolean
<API key> (EmpathyConf *conf,
const gchar *key,
gboolean value)
{
EmpathyConfPriv *priv;
<API key> (EMPATHY_IS_CONF (conf), FALSE);
DEBUG ("Setting bool:'%s' to %d ---> %s", key, value,
value ? "true" : "false");
priv = GET_PRIV (conf);
return <API key> (priv->gconf_client,
key,
value,
NULL);
}
gboolean
<API key> (EmpathyConf *conf,
const gchar *key,
gboolean *value)
{
EmpathyConfPriv *priv;
GError *error = NULL;
*value = FALSE;
<API key> (EMPATHY_IS_CONF (conf), FALSE);
<API key> (value != NULL, FALSE);
priv = GET_PRIV (conf);
*value = <API key> (priv->gconf_client,
key,
&error);
if (error) {
g_error_free (error);
return FALSE;
}
return TRUE;
}
gboolean
<API key> (EmpathyConf *conf,
const gchar *key,
const gchar *value)
{
EmpathyConfPriv *priv;
<API key> (EMPATHY_IS_CONF (conf), FALSE);
DEBUG ("Setting string:'%s' to '%s'", key, value);
priv = GET_PRIV (conf);
return <API key> (priv->gconf_client,
key,
value,
NULL);
}
gboolean
<API key> (EmpathyConf *conf,
const gchar *key,
gchar **value)
{
EmpathyConfPriv *priv;
GError *error = NULL;
*value = NULL;
<API key> (EMPATHY_IS_CONF (conf), FALSE);
priv = GET_PRIV (conf);
*value = <API key> (priv->gconf_client,
key,
&error);
if (error) {
g_error_free (error);
return FALSE;
}
return TRUE;
}
gboolean
<API key> (EmpathyConf *conf,
const gchar *key,
GSList *value)
{
EmpathyConfPriv *priv;
<API key> (EMPATHY_IS_CONF (conf), FALSE);
priv = GET_PRIV (conf);
return <API key> (priv->gconf_client,
key,
GCONF_VALUE_STRING,
value,
NULL);
}
gboolean
<API key> (EmpathyConf *conf,
const gchar *key,
GSList **value)
{
EmpathyConfPriv *priv;
GError *error = NULL;
*value = NULL;
<API key> (EMPATHY_IS_CONF (conf), FALSE);
priv = GET_PRIV (conf);
*value = <API key> (priv->gconf_client,
key,
GCONF_VALUE_STRING,
&error);
if (error) {
g_error_free (error);
return FALSE;
}
return TRUE;
}
static void
<API key> (<API key> *data)
{
g_object_unref (data->conf);
g_slice_free (<API key>, data);
}
static void
conf_notify_func (GConfClient *client,
guint id,
GConfEntry *entry,
gpointer user_data)
{
<API key> *data;
data = user_data;
data->func (data->conf,
gconf_entry_get_key (entry),
data->user_data);
}
guint
<API key> (EmpathyConf *conf,
const gchar *key,
<API key> func,
gpointer user_data)
{
EmpathyConfPriv *priv;
guint id;
<API key> *data;
<API key> (EMPATHY_IS_CONF (conf), 0);
priv = GET_PRIV (conf);
data = g_slice_new (<API key>);
data->func = func;
data->user_data = user_data;
data->conf = g_object_ref (conf);
id = <API key> (priv->gconf_client,
key,
conf_notify_func,
data,
(GFreeFunc) <API key>,
NULL);
return id;
}
gboolean
<API key> (EmpathyConf *conf,
guint id)
{
EmpathyConfPriv *priv;
<API key> (EMPATHY_IS_CONF (conf), FALSE);
priv = GET_PRIV (conf);
<API key> (priv->gconf_client, id);
return TRUE;
}
|
<?php
require_once('../conexiones/conexione.php');
mysql_select_db($base_datos, $conectar);
<API key>("America/Bogota");
include ("../<API key>/<API key>.php");
//$cod_factura = $_GET['cod_factura'];
$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$tabla = $_GET['tabla'];
$tipo = $_GET['tipo'];
$fecha = date("Y/m/d");
$hora = date("H:i:s");
$salida = "";
$nombre = $tabla.'_'.$fecha.'_Hora_'.$hora.'-'.$tipo.'-'.$fecha_ini.'-'.$fecha_fin.'.csv';
$sql = mysql_query("SELECT * FROM $tabla WHERE fecha_anyo BETWEEN '$fecha_ini' AND '$fecha_fin'");
$total_columnas = mysql_num_fields($sql);
// Obtener El Nombre de Campo
/*
for ($i = 0; $i < $total_columnas; $i++) {
$encabezado = mysql_field_name($sql, $i);
$salida .= '"'.$encabezado.'",';
}
$salida .="\n";
*/
// Obtener los Registros de la tabla
while ($datos = mysql_fetch_array($sql)) {
for ($i = 0; $i < $total_columnas; $i++) {
$salida .=''.$datos["$i"].',';
//$salida .='"'.$datos["$i"].'",';
}
$salida .="\n";
}
// DESCARGAR ARCHIVO
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$nombre);
echo $salida;
exit;
?>
|
<html lang="en">
<head>
<title>GDB/MI Ada Tasking Commands - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="GDB_002fMI.html#GDB_002fMI" title="GDB/MI">
<link rel="prev" href="<API key>.html#<API key>" title="GDB/MI Thread Commands">
<link rel="next" href="<API key>.html#<API key>" title="GDB/MI Program Execution">
<link href="http:
<!
Copyright (C) 1988-2015 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being ``Free Software'' and ``Free Software Needs
Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
and with the Back-Cover Texts as in (a) below.
(a) The FSF's Back-Cover Text is: ``You are free to copy and modify
this GNU Manual. Buying copies from GNU Press supports the FSF in
developing GNU and promoting software freedom.''
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="GDB%<API key>"></a>
<a name="<API key>"></a>
Next: <a rel="next" accesskey="n" href="<API key>.html#<API key>">GDB/MI Program Execution</a>,
Previous: <a rel="previous" accesskey="p" href="<API key>.html#<API key>">GDB/MI Thread Commands</a>,
Up: <a rel="up" accesskey="u" href="GDB_002fMI.html#GDB_002fMI">GDB/MI</a>
<hr>
</div>
<h3 class="section">27.12 <span class="sc">gdb/mi</span> Ada Tasking Commands</h3>
<h4 class="subheading">The <code>-ada-task-info</code> Command</h4>
<p><a name="<API key>"></a>
<h5 class="subsubheading">Synopsis</h5>
<pre class="smallexample"> -ada-task-info [ <var>task-id</var> ]
</pre>
<p>Reports information about either a specific Ada task, if the
<var>task-id</var> parameter is present, or about all Ada tasks.
<h5 class="subsubheading"><span class="sc">gdb</span> Command</h5>
<p>The ‘<samp><span class="samp">info tasks</span></samp>’ command prints the same information
about all Ada tasks (see <a href="Ada-Tasks.html#Ada-Tasks">Ada Tasks</a>).
<h5 class="subsubheading">Result</h5>
<p>The result is a table of Ada tasks. The following columns are
defined for each Ada task:
<dl>
<dt>‘<samp><span class="samp">current</span></samp>’<dd>This field exists only for the current thread. It has the value ‘<samp><span class="samp">*</span></samp>’.
<br><dt>‘<samp><span class="samp">id</span></samp>’<dd>The identifier that <span class="sc">gdb</span> uses to refer to the Ada task.
<br><dt>‘<samp><span class="samp">task-id</span></samp>’<dd>The identifier that the target uses to refer to the Ada task.
<br><dt>‘<samp><span class="samp">thread-id</span></samp>’<dd>The identifier of the thread corresponding to the Ada task.
<p>This field should always exist, as Ada tasks are always implemented
on top of a thread. But if <span class="sc">gdb</span> cannot find this corresponding
thread for any reason, the field is omitted.
<br><dt>‘<samp><span class="samp">parent-id</span></samp>’<dd>This field exists only when the task was created by another task.
In this case, it provides the ID of the parent task.
<br><dt>‘<samp><span class="samp">priority</span></samp>’<dd>The base priority of the task.
<br><dt>‘<samp><span class="samp">state</span></samp>’<dd>The current state of the task. For a detailed description of the
possible states, see <a href="Ada-Tasks.html#Ada-Tasks">Ada Tasks</a>.
<br><dt>‘<samp><span class="samp">name</span></samp>’<dd>The name of the task.
</dl>
<h5 class="subsubheading">Example</h5>
<pre class="smallexample"> -ada-task-info
^done,tasks={nr_rows="3",nr_cols="8",
hdr=[{width="1",alignment="-1",col_name="current",colhdr=""},
{width="3",alignment="1",col_name="id",colhdr="ID"},
{width="9",alignment="1",col_name="task-id",colhdr="TID"},
{width="4",alignment="1",col_name="thread-id",colhdr=""},
{width="4",alignment="1",col_name="parent-id",colhdr="P-ID"},
{width="3",alignment="1",col_name="priority",colhdr="Pri"},
{width="22",alignment="-1",col_name="state",colhdr="State"},
{width="1",alignment="2",col_name="name",colhdr="Name"}],
body=[{current="*",id="1",task-id=" 644010",thread-id="1",priority="48",
state="Child Termination Wait",name="main_task"}]}
(gdb)
</pre>
<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%% SECTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
</body></html>
|
<html lang="en">
<head>
<title>sin - Untitled</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Untitled">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Math.html#Math" title="Math">
<link rel="prev" href="signbit.html#signbit" title="signbit">
<link rel="next" href="sinh.html#sinh" title="sinh">
<link href="http:
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="sin"></a>
Next: <a rel="next" accesskey="n" href="sinh.html#sinh">sinh</a>,
Previous: <a rel="previous" accesskey="p" href="signbit.html#signbit">signbit</a>,
Up: <a rel="up" accesskey="u" href="Math.html#Math">Math</a>
<hr>
</div>
<h3 class="section">1.54 <code>sin</code>, <code>sinf</code>, <code>cos</code>, <code>cosf</code>—sine or cosine</h3>
<p><a name="index-sin-144"></a><a name="index-sinf-145"></a><a name="index-cos-146"></a><a name="index-cosf-147"></a><strong>Synopsis</strong>
<pre class="example"> #include <math.h>
double sin(double <var>x</var>);
float sinf(float <var>x</var>);
double cos(double <var>x</var>);
float cosf(float <var>x</var>);
</pre>
<p><strong>Description</strong><br>
<code>sin</code> and <code>cos</code> compute (respectively) the sine and cosine
of the argument <var>x</var>. Angles are specified in radians.
<p><code>sinf</code> and <code>cosf</code> are identical, save that they take and
return <code>float</code> values.
<pre class="sp">
</pre>
<strong>Returns</strong><br>
The sine or cosine of <var>x</var> is returned.
<pre class="sp">
</pre>
<strong>Portability</strong><br>
<code>sin</code> and <code>cos</code> are ANSI C.
<code>sinf</code> and <code>cosf</code> are extensions.
<pre class="sp">
</pre>
</body></html>
|
#include "config.h"
#include <gegl.h>
#include "core-types.h"
#include "gimp.h"
#include "gimp-gradients.h"
#include "gimpcontext.h"
#include "gimpcontainer.h"
#include "gimpdatafactory.h"
#include "gimpgradient.h"
#include "gimp-intl.h"
#define FG_BG_RGB_KEY "<API key>"
#define FG_BG_HARDEDGE_KEY "<API key>"
#define FG_BG_HSV_CCW_KEY "<API key>"
#define FG_BG_HSV_CW_KEY "<API key>"
#define FG_TRANSPARENT_KEY "<API key>"
/* local function prototypes */
static GimpGradient * <API key> (Gimp *gimp,
const gchar *name,
const gchar *id);
/* public functions */
void
gimp_gradients_init (Gimp *gimp)
{
GimpGradient *gradient;
g_return_if_fail (GIMP_IS_GIMP (gimp));
/* FG to BG (RGB) */
gradient = <API key> (gimp,
_("FG to BG (RGB)"),
FG_BG_RGB_KEY);
gradient->segments->left_color_type = <API key>;
gradient->segments->right_color_type = <API key>;
<API key> (gimp->user_context, gradient);
/* FG to BG (Hardedge) */
gradient = <API key> (gimp,
_("FG to BG (Hardedge)"),
FG_BG_HARDEDGE_KEY);
gradient->segments->left = 0.00;
gradient->segments->middle = 0.25;
gradient->segments->right = 0.50;
gradient->segments->left_color_type = <API key>;
gradient->segments->right_color_type = <API key>;
gradient->segments->next = <API key> ();
gradient->segments->next->prev = gradient->segments;
gradient->segments->next->left = 0.50;
gradient->segments->next->middle = 0.75;
gradient->segments->next->right = 1.00;
gradient->segments->next->left_color_type = <API key>;
gradient->segments->next->right_color_type = <API key>;
/* FG to BG (HSV counter-clockwise) */
gradient = <API key> (gimp,
_("FG to BG (HSV counter-clockwise)"),
FG_BG_HSV_CCW_KEY);
gradient->segments->left_color_type = <API key>;
gradient->segments->right_color_type = <API key>;
gradient->segments->color = <API key>;
/* FG to BG (HSV clockwise hue) */
gradient = <API key> (gimp,
_("FG to BG (HSV clockwise hue)"),
FG_BG_HSV_CW_KEY);
gradient->segments->left_color_type = <API key>;
gradient->segments->right_color_type = <API key>;
gradient->segments->color = <API key>;
/* FG to Transparent */
gradient = <API key> (gimp,
_("FG to Transparent"),
FG_TRANSPARENT_KEY);
gradient->segments->left_color_type = <API key>;
gradient->segments->right_color_type = <API key>;
}
/* private functions */
static GimpGradient *
<API key> (Gimp *gimp,
const gchar *name,
const gchar *id)
{
GimpGradient *gradient;
gradient = GIMP_GRADIENT (gimp_gradient_new (<API key> (gimp),
name));
<API key> (GIMP_DATA (gradient), id);
gimp_container_add (<API key> (gimp->gradient_factory),
GIMP_OBJECT (gradient));
g_object_unref (gradient);
g_object_set_data (G_OBJECT (gimp), id, gradient);
return gradient;
}
|
obj-$(CONFIG_ECS_DRIVER) += ecs-core.o
obj-$(<API key>) += ecs-subdev.o ecs-helper.o
obj-$(<API key>) += ov5640.o
obj-$(<API key>) += sp0a20.o
|
# functions to use with HP Hardware RAID (Smart Array and compatible)
function define_HPSSACLI() {
# HP Smart Storage Administrator CLI is either hpacucli, hpssacli or ssacli
if has_binary hpacucli ; then
HPSSACLI=hpacucli
elif has_binary hpssacli ; then
HPSSACLI=hpssacli
elif has_binary ssacli ; then
HPSSACLI=ssacli
fi
}
function <API key>() {
# call $HPSSACLI for the slot $1 and find the array that contains the drive $2
while read ; do
case $REPLY in
*array*)
ARRAY="${REPLY##*array }"
ARRAY="${ARRAY%% *}"
;;
*drive*$2*)
echo $ARRAY
return 0
;;
esac
done < <($HPSSACLI ctrl slot=$1 show config)
return 1 # here we come only if we did not find the drive
}
|
# This file is part of Iris.
# Iris is free software: you can redistribute it and/or modify it under
# (at your option) any later version.
# Iris is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
"""Unit tests for the `iris.quickplot.points` function."""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests
from iris.tests.unit.plot import <API key>
if tests.MPL_AVAILABLE:
import iris.quickplot as qplt
@tests.skip_plot
class TestStringCoordPlot(<API key>):
def test_yaxis_labels(self):
qplt.points(self.cube, coords=('bar', 'str_coord'))
self.<API key>('yaxis')
def test_xaxis_labels(self):
qplt.points(self.cube, coords=('str_coord', 'bar'))
self.<API key>('xaxis')
if __name__ == "__main__":
tests.main()
|
package com.laytonsmith.abstraction;
import com.laytonsmith.abstraction.enums.MCDisplaySlot;
import java.util.Set;
public interface MCScoreboard {
public void clearSlot(MCDisplaySlot slot);
public MCObjective getObjective(MCDisplaySlot slot);
public MCObjective getObjective(String name);
/**
*
* @return Set of all objectives on this scoreboard
*/
public Set<MCObjective> getObjectives();
public Set<MCObjective> <API key>(String criteria);
/**
*
* @return Set of all players tracked by this scoreboard
*/
public Set<String> getEntries();
public MCTeam getPlayerTeam(MCOfflinePlayer player);
public Set<MCScore> getScores(String entry);
public MCTeam getTeam(String teamName);
public Set<MCTeam> getTeams();
public MCObjective <API key>(String name, String criteria);
public MCTeam registerNewTeam(String name);
public void resetScores(String entry);
}
|
#pragma once
#include <wrl.h>
namespace DX
{
// Helper class for animation and simulation timing.
class StepTimer
{
public:
StepTimer() :
m_elapsedTicks(0),
m_totalTicks(0),
m_leftOverTicks(0),
m_frameCount(0),
m_framesPerSecond(0),
m_framesThisSecond(0),
m_qpcSecondCounter(0),
m_isFixedTimeStep(false),
<API key>(TicksPerSecond / 60)
{
if (!<API key>(&m_qpcFrequency))
{
throw ref new Platform::FailureException();
}
if (!<API key>(&m_qpcLastTime))
{
throw ref new Platform::FailureException();
}
// Initialize max delta to 1/10 of a second.
m_qpcMaxDelta = m_qpcFrequency.QuadPart / 10;
}
// Get elapsed time since the previous Update call.
uint64 GetElapsedTicks() const { return m_elapsedTicks; }
double GetElapsedSeconds() const { return TicksToSeconds(m_elapsedTicks); }
// Get total time since the start of the program.
uint64 GetTotalTicks() const { return m_totalTicks; }
double GetTotalSeconds() const { return TicksToSeconds(m_totalTicks); }
// Get total number of updates since start of the program.
uint32 GetFrameCount() const { return m_frameCount; }
// Get the current framerate.
uint32 GetFramesPerSecond() const { return m_framesPerSecond; }
// Set whether to use fixed or variable timestep mode.
void SetFixedTimeStep(bool isFixedTimestep) { m_isFixedTimeStep = isFixedTimestep; }
// Set how often to call Update when in fixed timestep mode.
void <API key>(uint64 targetElapsed) { <API key> = targetElapsed; }
void <API key>(double targetElapsed) { <API key> = SecondsToTicks(targetElapsed); }
// Integer format represents time using 10,000,000 ticks per second.
static const uint64 TicksPerSecond = 10000000;
static double TicksToSeconds(uint64 ticks) { return static_cast<double>(ticks) / TicksPerSecond; }
static uint64 SecondsToTicks(double seconds) { return static_cast<uint64>(seconds * TicksPerSecond); }
// After an intentional timing discontinuity (for instance a blocking IO operation)
// call this to avoid having the fixed timestep logic attempt a set of catch-up
// Update calls.
void ResetElapsedTime()
{
if (!<API key>(&m_qpcLastTime))
{
throw ref new Platform::FailureException();
}
m_leftOverTicks = 0;
m_framesPerSecond = 0;
m_framesThisSecond = 0;
m_qpcSecondCounter = 0;
}
// Update timer state, calling the specified Update function the appropriate number of times.
template<typename TUpdate>
void Tick(const TUpdate& update)
{
// Query the current time.
LARGE_INTEGER currentTime;
if (!<API key>(¤tTime))
{
throw ref new Platform::FailureException();
}
uint64 timeDelta = currentTime.QuadPart - m_qpcLastTime.QuadPart;
m_qpcLastTime = currentTime;
m_qpcSecondCounter += timeDelta;
// Clamp excessively large time deltas (e.g. after paused in the debugger).
if (timeDelta > m_qpcMaxDelta)
{
timeDelta = m_qpcMaxDelta;
}
// Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp.
timeDelta *= TicksPerSecond;
timeDelta /= m_qpcFrequency.QuadPart;
uint32 lastFrameCount = m_frameCount;
if (m_isFixedTimeStep)
{
// Fixed timestep update logic
// If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp
// the clock to exactly match the target value. This prevents tiny and irrelevant errors
// from accumulating over time. Without this clamping, a game that requested a 60 fps
// fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually
// accumulate enough tiny errors that it would drop a frame. It is better to just round
// small deviations down to zero to leave things running smoothly.
if (abs(static_cast<int64>(timeDelta - <API key>)) < TicksPerSecond / 4000)
{
timeDelta = <API key>;
}
m_leftOverTicks += timeDelta;
while (m_leftOverTicks >= <API key>)
{
m_elapsedTicks = <API key>;
m_totalTicks += <API key>;
m_leftOverTicks -= <API key>;
m_frameCount++;
update();
}
}
else
{
// Variable timestep update logic.
m_elapsedTicks = timeDelta;
m_totalTicks += timeDelta;
m_leftOverTicks = 0;
m_frameCount++;
update();
}
// Track the current framerate.
if (m_frameCount != lastFrameCount)
{
m_framesThisSecond++;
}
if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency.QuadPart))
{
m_framesPerSecond = m_framesThisSecond;
m_framesThisSecond = 0;
m_qpcSecondCounter %= m_qpcFrequency.QuadPart;
}
}
private:
// Source timing data uses QPC units.
LARGE_INTEGER m_qpcFrequency;
LARGE_INTEGER m_qpcLastTime;
uint64 m_qpcMaxDelta;
// Derived timing data uses a canonical tick format.
uint64 m_elapsedTicks;
uint64 m_totalTicks;
uint64 m_leftOverTicks;
// Members for tracking the framerate.
uint32 m_frameCount;
uint32 m_framesPerSecond;
uint32 m_framesThisSecond;
uint64 m_qpcSecondCounter;
// Members for configuring fixed timestep mode.
bool m_isFixedTimeStep;
uint64 <API key>;
};
}
|
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Solidity AST to EVM bytecode compiler.
*/
#pragma once
#include <ostream>
#include <functional>
#include <libsolidity/ASTVisitor.h>
#include <libsolidity/CompilerContext.h>
#include <libevmasm/Assembly.h>
namespace dev {
namespace solidity {
class Compiler: private ASTConstVisitor
{
public:
explicit Compiler(bool _optimize = false, unsigned _runs = 200):
m_optimize(_optimize),
m_optimizeRuns(_runs),
m_context(),
m_returnTag(m_context.newTag())
{
}
void compileContract(ContractDefinition const& _contract,
std::map<ContractDefinition const*, bytes const*> const& _contracts);
bytes <API key>() { return m_context.<API key>(); }
bytes getRuntimeBytecode() { return m_context.<API key>(m_runtimeSub); }
@arg _sourceCodes is the map of input files to source code strings
@arg _inJsonFromat shows whether the out should be in Json format
Json::Value streamAssembly(std::ostream& _stream, StringMap const& _sourceCodes = StringMap(), bool _inJsonFormat = false) const
{
return m_context.streamAssembly(_stream, _sourceCodes, _inJsonFormat);
}
@returns Assembly items of the normal compiler context
eth::AssemblyItems const& getAssemblyItems() const { return m_context.getAssembly().getItems(); }
@returns Assembly items of the runtime compiler context
eth::AssemblyItems const& <API key>() const { return m_context.getAssembly().getSub(m_runtimeSub).getItems(); }
@returns the entry label of the given function. Might return an AssemblyItem of type
UndefinedItem if it does not exist yet.
eth::AssemblyItem <API key>(FunctionDefinition const& _function) const;
private:
Registers the non-function objects inside the contract with the context.
void initializeContext(ContractDefinition const& _contract,
std::map<ContractDefinition const*, bytes const*> const& _contracts);
Adds the code that is run at creation time. Should be run after exchanging the run-time context
with a new and initialized context. Adds the constructor code.
void <API key>(ContractDefinition const& _contract, CompilerContext const& _runtimeContext);
void <API key>(FunctionDefinition const& _constructor);
void appendConstructor(FunctionDefinition const& _constructor);
void <API key>(ContractDefinition const& _contract);
Creates code that unpacks the arguments for the given function represented by a vector of TypePointers.
From memory if @a _fromMemory is true, otherwise from call data.
Expects source offset on the stack.
void <API key>(
TypePointers const& _typeParameters,
bool _fromMemory = false,
u256 _startOffset = u256(-1)
);
void <API key>(TypePointers const& _typeParameters);
void <API key>(ContractDefinition const& _contract);
void <API key>(ContractDefinition const& _contract);
Initialises all memory arrays in the local variables to point to an empty location.
void <API key>(std::vector<VariableDeclaration const*> _variables);
Pushes the initialised value of the given type to the stack. If the type is a memory
reference type, allocates memory and pushes the memory pointer.
Not to be used for storage references.
void initialiseInMemory(Type const& _type);
virtual bool visit(VariableDeclaration const& <API key>) override;
virtual bool visit(FunctionDefinition const& _function) override;
virtual bool visit(IfStatement const& _ifStatement) override;
virtual bool visit(WhileStatement const& _whileStatement) override;
virtual bool visit(ForStatement const& _forStatement) override;
virtual bool visit(Continue const& _continue) override;
virtual bool visit(Break const& _break) override;
virtual bool visit(Return const& _return) override;
virtual bool visit(<API key> const& <API key>) override;
virtual bool visit(ExpressionStatement const& <API key>) override;
virtual bool visit(<API key> const&) override;
Appends one layer of function modifier code of the current function, or the function
body itself if the last modifier was reached.
void <API key>();
void <API key>(VariableDeclaration const& _variable);
void compileExpression(Expression const& _expression, TypePointer const& _targetType = TypePointer());
bool const m_optimize;
unsigned const m_optimizeRuns;
CompilerContext m_context;
size_t m_runtimeSub = size_t(-1); ///< Identifier of the runtime sub-assembly
CompilerContext m_runtimeContext;
std::vector<eth::AssemblyItem> m_breakTags; ///< tag to jump to for a "break" statement
std::vector<eth::AssemblyItem> m_continueTags; ///< tag to jump to for a "continue" statement
eth::AssemblyItem m_returnTag; ///< tag to jump to for a "return" statement
unsigned m_modifierDepth = 0;
FunctionDefinition const* m_currentFunction = nullptr;
unsigned <API key> = 0; ///< this number of stack elements need to be removed before jump to m_returnTag
// arguments for base constructors, filled in derived-to-base order
std::map<FunctionDefinition const*, std::vector<ASTPointer<Expression>> const*> m_baseArguments;
};
}
}
|
SET(CTEST_PROJECT_NAME "hikob-git-${PLATFORM}")
SET(<API key> "00:00:00 EST")
IF(NOT DEFINED CTEST_DROP_METHOD)
SET(CTEST_DROP_METHOD "http")
ENDIF(NOT DEFINED CTEST_DROP_METHOD)
IF(CTEST_DROP_METHOD STREQUAL "http")
SET(CTEST_DROP_SITE "tools.vpn.hikob.com")
SET(CTEST_DROP_LOCATION "/cdash/submit.php?project=hikob-git-${PLATFORM}")
SET(CTEST_TRIGGER_SITE "tools.vpn.hikob.com")
ENDIF(CTEST_DROP_METHOD STREQUAL "http")
|
package cn.nukkit.block;
import cn.nukkit.Player;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemTool;
import cn.nukkit.level.Level;
import cn.nukkit.level.sound.NoteBoxSound;
import cn.nukkit.network.protocol.BlockEventPacket;
public class BlockNoteblock extends BlockSolid {
public BlockNoteblock() {
this(0);
}
public BlockNoteblock(int meta) {
super(meta);
}
@Override
public String getName() {
return "Note Block";
}
@Override
public int getId() {
return NOTEBLOCK;
}
@Override
public int getToolType() {
return ItemTool.TYPE_AXE;
}
@Override
public double getHardness() {
return 0.8D;
}
@Override
public double getResistance() {
return 4D;
}
public boolean canBeActivated() {
return true;
}
public int getStrength() {
return this.meta;
}
public void increaseStrength() {
if (this.meta < 24) {
this.meta++;
} else {
this.meta = 0;
}
}
public int getInstrument() {
Block below = this.down();
switch (below.getId()) {
case WOODEN_PLANK:
case NOTEBLOCK:
case CRAFTING_TABLE:
return NoteBoxSound.INSTRUMENT_BASS;
case SAND:
case SANDSTONE:
case SOUL_SAND:
return NoteBoxSound.INSTRUMENT_TABOUR;
case GLASS:
case GLASS_PANEL:
case GLOWSTONE_BLOCK:
return NoteBoxSound.INSTRUMENT_CLICK;
case COAL_ORE:
case DIAMOND_ORE:
case EMERALD_ORE:
case <API key>:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case REDSTONE_ORE:
return NoteBoxSound.<API key>;
default:
return NoteBoxSound.INSTRUMENT_PIANO;
}
}
public void emitSound() {
BlockEventPacket pk = new BlockEventPacket();
pk.x = (int) this.x;
pk.y = (int) this.y;
pk.z = (int) this.z;
pk.case1 = this.getInstrument();
pk.case2 = this.getStrength();
this.getLevel().addChunkPacket((int) this.x >> 4, (int) this.z >> 4, pk);
this.getLevel().addSound(new NoteBoxSound(this, this.getInstrument(), this.getStrength()));
}
public boolean onActivate(Item item) {
return this.onActivate(item, null);
}
public boolean onActivate(Item item, Player player) {
Block up = this.up();
if (up.getId() == Block.AIR) {
this.increaseStrength();
this.emitSound();
return true;
} else {
return false;
}
}
@Override
public int onUpdate(int type) {
if (type == Level.BLOCK_UPDATE_NORMAL || type == Level.<API key>) {
//TODO: redstone
}
return 0;
}
}
|
#!/usr/bin/perl
use strict;
use warnings;
use Test::More tests => 34;
BEGIN { use_ok('li_carrays') }
require_ok('li_carrays');
# array_class
{
my $length = 5;
my $xyArray = new li_carrays::XYArray($length);
for (my $i=0; $i<$length; $i++) {
my $xy = $xyArray->getitem($i);
$xy->{x} = $i*10;
$xy->{y} = $i*100;
$xyArray->setitem($i, $xy);
}
for (my $i=0; $i<$length; $i++) {
is($xyArray->getitem($i)->{x}, $i*10);
is($xyArray->getitem($i)->{y}, $i*100);
}
}
{
# global array variable
my $length = 3;
my $xyArrayPointer = $li_carrays::globalXYArray;
my $xyArray = li_carrays::XYArray::frompointer($xyArrayPointer);
for (my $i=0; $i<$length; $i++) {
my $xy = $xyArray->getitem($i);
$xy->{x} = $i*10;
$xy->{y} = $i*100;
$xyArray->setitem($i, $xy);
}
for (my $i=0; $i<$length; $i++) {
is($xyArray->getitem($i)->{x}, $i*10);
is($xyArray->getitem($i)->{y}, $i*100);
}
}
# array_functions
{
my $length = 5;
my $abArray = li_carrays::new_ABArray($length);
for (my $i=0; $i<$length; $i++) {
my $ab = li_carrays::ABArray_getitem($abArray, $i);
$ab->{a} = $i*10;
$ab->{b} = $i*100;
li_carrays::ABArray_setitem($abArray, $i, $ab);
}
for (my $i=0; $i<$length; $i++) {
is(li_carrays::ABArray_getitem($abArray, $i)->{a}, $i*10);
is(li_carrays::ABArray_getitem($abArray, $i)->{b}, $i*100);
}
li_carrays::delete_ABArray($abArray);
}
{
# global array variable
my $length = 3;
my $abArray = $li_carrays::globalABArray;
for (my $i=0; $i<$length; $i++) {
my $ab = li_carrays::ABArray_getitem($abArray, $i);
$ab->{a} = $i*10;
$ab->{b} = $i*100;
li_carrays::ABArray_setitem($abArray, $i, $ab);
}
for (my $i=0; $i<$length; $i++) {
is(li_carrays::ABArray_getitem($abArray, $i)->{a}, $i*10);
is(li_carrays::ABArray_getitem($abArray, $i)->{b}, $i*100);
}
}
|
package org.hsqldb.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/* $Id: SqlTool.java,v 1.72 2007/06/29 12:23:47 unsaved Exp $ */
/**
* Sql Tool. A command-line and/or interactive SQL tool.
* (Note: For every Javadoc block comment, I'm using a single blank line
* immediately after the description, just like's Sun's examples in
* their Coding Conventions document).
*
* See JavaDocs for the main method for syntax of how to run.
* This class is mostly used in a static (a.o.t. object) way, because most
* of the work is done in the static main class.
* This class should be refactored so that the main work is done in an
* object method, and the static main invokes the object method.
* Then programmatic users could use instances of this class in the normal
* Java way.
*
* @see #main()
* @version $Revision: 1.72 $
* @author Blaine Simpson unsaved@users
*/
public class SqlTool {
private static final String DEFAULT_RCFILE =
System.getProperty("user.home") + "/sqltool.rc";
// N.b. the following is static!
private static String revnum = null;
public static final int SQLTOOLERR_EXITVAL = 1;
public static final int SYNTAXERR_EXITVAL = 11;
public static final int RCERR_EXITVAL = 2;
public static final int SQLERR_EXITVAL = 3;
public static final int IOERR_EXITVAL = 4;
public static final int FILEERR_EXITVAL = 5;
public static final int INPUTERR_EXITVAL = 6;
public static final int CONNECTERR_EXITVAL = 7;
/**
* The configuration identifier to use when connection parameters are
* specified on the command line
*/
private static String CMDLINE_ID = "cmdline";
static private SqltoolRB rb = null;
// Must use a shared static RB object, since we need to get messages
// inside of static methods.
// This means that the locale will be set the first time this class
// is accessed. Subsequent calls will not update the RB if the locale
// changes (could have it check and reload the RB if this becomes an
// issue).
static {
revnum = "333";
try {
rb = new SqltoolRB();
rb.validate();
rb.<API key>(
<API key>.NOOP_BEHAVIOR);
rb.<API key>(
<API key>.NOOP_BEHAVIOR);
} catch (RuntimeException re) {
System.err.println("Failed to initialize resource bundle");
throw re;
}
}
public static String LS = System.getProperty("line.separator");
/** Utility nested class for internal use. */
private static class BadCmdline extends Exception {
static final long serialVersionUID = -<API key>;
BadCmdline() {}
}
/** Utility object for internal use. */
private static BadCmdline bcl = new BadCmdline();
/** For trapping of exceptions inside this class.
* These are always handled inside this class.
*/
private static class PrivateException extends Exception {
static final long serialVersionUID = -<API key>;
PrivateException() {
super();
}
PrivateException(String s) {
super(s);
}
}
public static class SqlToolException extends Exception {
static final long serialVersionUID = <API key>;
int exitValue = 1;
SqlToolException(String message, int exitValue) {
super(message);
this.exitValue = exitValue;
}
SqlToolException(int exitValue, String message) {
this(message, exitValue);
}
SqlToolException(int exitValue) {
super();
this.exitValue = exitValue;
}
}
/**
* Prompt the user for a password.
*
* @param username The user the password is for
* @return The password the user entered
*/
private static String promptForPassword(String username)
throws PrivateException {
BufferedReader console;
String password;
password = null;
try {
console = new BufferedReader(new InputStreamReader(System.in));
// Prompt for password
System.out.print(rb.getString(SqltoolRB.PASSWORDFOR_PROMPT,
RCData.expandSysPropVars(username)));
// Read the password from the command line
password = console.readLine();
if (password == null) {
password = "";
} else {
password = password.trim();
}
} catch (IOException e) {
throw new PrivateException(e.getMessage());
}
return password;
}
/**
* Parses a comma delimited string of name value pairs into a
* <code>Map</code> object.
*
* @param varString The string to parse
* @param varMap The map to save the paired values into
* @param lowerCaseKeys Set to <code>true</code> if the map keys should be
* converted to lower case
*/
private static void varParser(String varString, Map varMap,
boolean lowerCaseKeys)
throws PrivateException {
int equals;
String var;
String val;
String[] allvars;
if ((varMap == null) || (varString == null)) {
throw new <API key>(
"varMap or varString are null in SqlTool.varParser call");
}
allvars = varString.split("\\s*,\\s*");
for (int i = 0; i < allvars.length; i++) {
equals = allvars[i].indexOf('=');
if (equals < 1) {
throw new PrivateException(
rb.getString(SqltoolRB.<API key>));
}
var = allvars[i].substring(0, equals).trim();
val = allvars[i].substring(equals + 1).trim();
if (var.length() < 1) {
throw new PrivateException(
rb.getString(SqltoolRB.<API key>));
}
if (lowerCaseKeys) {
var = var.toLowerCase();
}
varMap.put(var, val);
}
}
/**
* A static wrapper for objectMain, so that that method may be executed
* as a Java "program".
*
* Throws only RuntimExceptions or Errors, because this method is intended
* to System.exit() for all but disasterous system problems, for which
* the inconvenience of a a stack trace would be the least of your worries.
*
* If you don't want SqlTool to System.exit(), then use the method
* objectMain() instead of this method.
*
* @see objectMain(String[])
*/
public static void main(String[] args) {
try {
SqlTool.objectMain(args);
} catch (SqlToolException fr) {
if (fr.getMessage() != null) {
System.err.println(fr.getMessage());
}
System.exit(fr.exitValue);
}
System.exit(0);
}
/**
* Connect to a JDBC Database and execute the commands given on
* stdin or in SQL file(s).
*
* This method is changed for HSQLDB 1.8.0.8 and 1.9.0.x to never
* System.exit().
*
* @param arg Run "java... org.hsqldb.util.SqlTool --help" for syntax.
* @throws SqlToolException Upon any fatal error, with useful
* reason as the exception's message.
*/
static public void objectMain(String[] arg) throws SqlToolException {
/*
* The big picture is, we parse input args; load a RCData;
* get a JDBC Connection with the RCData; instantiate and
* execute as many SqlFiles as we need to.
*/
String rcFile = null;
File tmpFile = null;
String sqlText = null;
String driver = null;
String targetDb = null;
String varSettings = null;
boolean debug = false;
File[] scriptFiles = null;
int i = -1;
boolean listMode = false;
boolean interactive = false;
boolean noinput = false;
boolean noautoFile = false;
boolean autoCommit = false;
Boolean coeOverride = null;
Boolean stdinputOverride = null;
String rcParams = null;
String rcUrl = null;
String rcUsername = null;
String rcPassword = null;
String rcCharset = null;
String rcTruststore = null;
Map rcFields = null;
String parameter;
try {
while ((i + 1 < arg.length) && arg[i + 1].startsWith("
i++;
if (arg[i].length() == 2) {
break;
}
parameter = arg[i].substring(2).toLowerCase();
if (parameter.equals("help")) {
System.out.println(rb.getString(SqltoolRB.SQLTOOL_SYNTAX,
revnum, RCData.DEFAULT_JDBC_DRIVER));
return;
}
if (parameter.equals("abortonerr")) {
if (coeOverride != null) {
throw new SqlToolException(SYNTAXERR_EXITVAL,
rb.getString(
SqltoolRB.<API key>));
}
coeOverride = Boolean.FALSE;
} else if (parameter.equals("continueonerr")) {
if (coeOverride != null) {
throw new SqlToolException(SYNTAXERR_EXITVAL,
rb.getString(
SqltoolRB.<API key>));
}
coeOverride = Boolean.TRUE;
} else if (parameter.equals("list")) {
listMode = true;
} else if (parameter.equals("rcfile")) {
if (++i == arg.length) {
throw bcl;
}
rcFile = arg[i];
} else if (parameter.equals("setvar")) {
if (++i == arg.length) {
throw bcl;
}
varSettings = arg[i];
} else if (parameter.equals("sql")) {
noinput = true; // but turn back on if file "-" specd.
if (++i == arg.length) {
throw bcl;
}
sqlText = arg[i];
} else if (parameter.equals("debug")) {
debug = true;
} else if (parameter.equals("noautofile")) {
noautoFile = true;
} else if (parameter.equals("autocommit")) {
autoCommit = true;
} else if (parameter.equals("stdinput")) {
noinput = false;
stdinputOverride = Boolean.TRUE;
} else if (parameter.equals("noinput")) {
noinput = true;
stdinputOverride = Boolean.FALSE;
} else if (parameter.equals("driver")) {
if (++i == arg.length) {
throw bcl;
}
driver = arg[i];
} else if (parameter.equals("inlinerc")) {
if (++i == arg.length) {
throw bcl;
}
rcParams = arg[i];
} else {
throw bcl;
}
}
if (!listMode) {
// If an inline RC file was specified, don't worry about the targetDb
if (rcParams == null) {
if (++i == arg.length) {
throw bcl;
}
targetDb = arg[i];
}
}
int scriptIndex = 0;
if (sqlText != null) {
try {
tmpFile = File.createTempFile("sqltool-", ".sql");
//(new java.io.FileWriter(tmpFile)).write(sqlText);
java.io.FileWriter fw = new java.io.FileWriter(tmpFile);
try {
fw.write("/* " + (new java.util.Date()) + ". "
+ SqlTool.class.getName()
+ " command-line SQL. */" + LS + LS);
fw.write(sqlText + LS);
fw.flush();
} finally {
fw.close();
}
} catch (IOException ioe) {
throw new SqlToolException(IOERR_EXITVAL,
rb.getString(SqltoolRB.SQLTEMPFILE_FAIL,
ioe.toString()));
}
}
if (stdinputOverride != null) {
noinput = !stdinputOverride.booleanValue();
}
interactive = (!noinput) && (arg.length <= i + 1);
if (arg.length == i + 2 && arg[i + 1].equals("-")) {
if (stdinputOverride == null) {
noinput = false;
}
} else if (arg.length > i + 1) {
// I.e., if there are any SQL files specified.
scriptFiles = new File[arg.length - i - 1
+ ((stdinputOverride == null
||!stdinputOverride.booleanValue()) ? 0 : 1)];
if (debug) {
System.err.println("scriptFiles has "
+ scriptFiles.length + " elements");
}
while (i + 1 < arg.length) {
scriptFiles[scriptIndex++] = new File(arg[++i]);
}
if (stdinputOverride != null
&& stdinputOverride.booleanValue()) {
scriptFiles[scriptIndex++] = null;
noinput = true;
}
}
} catch (BadCmdline bcl) {
throw new SqlToolException(SYNTAXERR_EXITVAL,
rb.getString(SqltoolRB.SQLTOOL_SYNTAX,
revnum, RCData.DEFAULT_JDBC_DRIVER));
}
RCData conData = null;
// Use the inline RC file if it was specified
if (rcParams != null) {
rcFields = new HashMap();
try {
varParser(rcParams, rcFields, true);
} catch (PrivateException e) {
throw new SqlToolException(SYNTAXERR_EXITVAL, e.getMessage());
}
rcUrl = (String) rcFields.remove("url");
rcUsername = (String) rcFields.remove("user");
rcCharset = (String) rcFields.remove("charset");
rcTruststore = (String) rcFields.remove("truststore");
rcPassword = (String) rcFields.remove("password");
// Don't ask for password if what we have already is invalid!
if (rcUrl == null || rcUrl.length() < 1)
throw new SqlToolException(RCERR_EXITVAL, rb.getString(
SqltoolRB.<API key>));
if (rcUsername == null || rcUsername.length() < 1)
throw new SqlToolException(RCERR_EXITVAL, rb.getString(
SqltoolRB.<API key>));
if (rcPassword != null && rcPassword.length() > 0)
throw new SqlToolException(RCERR_EXITVAL, rb.getString(
SqltoolRB.<API key>));
if (rcFields.size() > 0) {
throw new SqlToolException(INPUTERR_EXITVAL,
rb.getString(SqltoolRB.<API key>,
rcFields.keySet().toString()));
}
if (rcPassword == null) try {
rc<API key>(rcUsername);
} catch (PrivateException e) {
throw new SqlToolException(INPUTERR_EXITVAL,
rb.getString(SqltoolRB.PASSWORD_READFAIL,
e.getMessage()));
}
try {
conData = new RCData(CMDLINE_ID, rcUrl, rcUsername,
rcPassword, driver, rcCharset,
rcTruststore);
} catch (Exception e) {
throw new SqlToolException(RCERR_EXITVAL, rb.getString(
SqltoolRB.<API key>, e.getMessage()));
}
} else {
try {
conData = new RCData(new File((rcFile == null)
? DEFAULT_RCFILE
: rcFile), targetDb);
} catch (Exception e) {
throw new SqlToolException(RCERR_EXITVAL, rb.getString(
SqltoolRB.<API key>,
targetDb, e.getMessage()));
}
}
if (listMode) {
return;
}
if (debug) {
conData.report();
}
Connection conn = null;
try {
conn = conData.getConnection(
driver, System.getProperty("sqlfile.charset"),
System.getProperty("javax.net.ssl.trustStore"));
conn.setAutoCommit(autoCommit);
DatabaseMetaData md = null;
if (interactive && (md = conn.getMetaData()) != null) {
System.out.println(
rb.getString(SqltoolRB.JDBC_ESTABLISHED,
md.<API key>(),
md.<API key>(),
md.getUserName()));
}
} catch (Exception e) {
//e.printStackTrace();
// Let's not continue as if nothing is wrong.
throw new SqlToolException(CONNECTERR_EXITVAL,
rb.getString(SqltoolRB.CONNECTION_FAIL,
conData.url, conData.username, e.getMessage()));
}
File[] emptyFileArray = {};
File[] singleNullFileArray = { null };
File autoFile = null;
if (interactive &&!noautoFile) {
autoFile = new File(System.getProperty("user.home")
+ "/auto.sql");
if ((!autoFile.isFile()) ||!autoFile.canRead()) {
autoFile = null;
}
}
if (scriptFiles == null) {
// I.e., if no SQL files given on command-line.
// Input file list is either nothing or {null} to read stdin.
scriptFiles = (noinput ? emptyFileArray
: singleNullFileArray);
}
int numFiles = scriptFiles.length;
if (tmpFile != null) {
numFiles += 1;
}
if (autoFile != null) {
numFiles += 1;
}
SqlFile[] sqlFiles = new SqlFile[numFiles];
Map userVars = new HashMap();
if (varSettings != null) try {
varParser(varSettings, userVars, false);
} catch (PrivateException pe) {
throw new SqlToolException(RCERR_EXITVAL, pe.getMessage());
}
// We print version before execing this one.
int <API key> = -1;
try {
int fileIndex = 0;
if (autoFile != null) {
sqlFiles[fileIndex++] = new SqlFile(autoFile, false,
userVars);
}
if (tmpFile != null) {
sqlFiles[fileIndex++] = new SqlFile(tmpFile, false, userVars);
}
for (int j = 0; j < scriptFiles.length; j++) {
if (<API key> < 0 && interactive) {
<API key> = fileIndex;
}
sqlFiles[fileIndex++] = new SqlFile(scriptFiles[j],
interactive, userVars);
}
} catch (IOException ioe) {
try {
conn.close();
} catch (Exception e) {}
throw new SqlToolException(FILEERR_EXITVAL, ioe.getMessage());
}
try {
for (int j = 0; j < sqlFiles.length; j++) {
if (j == <API key>) {
System.out.print("SqlTool v. " + revnum
+ ". ");
}
sqlFiles[j].execute(conn, coeOverride);
}
// Following two Exception types are handled properly inside of
// SqlFile. We just need to return an appropriate error status.
} catch (SqlToolError ste) {
throw new SqlToolException(SQLTOOLERR_EXITVAL);
} catch (SQLException se) {
// SqlTool will only throw an SQLException if it is in
// "\c false" mode.
throw new SqlToolException(SQLERR_EXITVAL);
} finally {
try {
conn.close();
} catch (Exception e) {}
}
// Taking file removal out of final block because this is good debug
// info to keep around if the program aborts.
if (tmpFile != null && !tmpFile.delete()) {
System.err.println(conData.url + rb.getString(
SqltoolRB.<API key>, tmpFile.toString()));
}
}
}
|
package App::Prove::State;
use strict;
use warnings;
use File::Find;
use File::Spec;
use Carp;
use App::Prove::State::Result;
use TAP::Parser::YAMLish::Reader ();
use TAP::Parser::YAMLish::Writer ();
use base 'TAP::Base';
BEGIN {
__PACKAGE__->mk_methods('result_class');
}
use constant IS_WIN32 => ( $^O =~ /^(MS)?Win32$/ );
use constant NEED_GLOB => IS_WIN32;
=head1 NAME
App::Prove::State - State storage for the C<prove> command.
=head1 VERSION
Version 3.38
=cut
our $VERSION = '3.38';
=head1 DESCRIPTION
The C<prove> command supports a C<--state> option that instructs it to
store persistent state across runs. This module implements that state
and the operations that may be performed on it.
=head1 SYNOPSIS
# Re-run failed tests
$ prove --state=failed,save -rbv
=cut
=head1 METHODS
=head2 Class Methods
=head3 C<new>
Accepts a hashref with the following key/value pairs:
=over 4
=item * C<store>
The filename of the data store holding the data that App::Prove::State reads.
=item * C<extensions> (optional)
The test name extensions. Defaults to C<.t>.
=item * C<result_class> (optional)
The name of the C<result_class>. Defaults to C<App::Prove::State::Result>.
=back
=cut
# override TAP::Base::new:
sub new {
my $class = shift;
my %args = %{ shift || {} };
my $self = bless {
select => [],
seq => 1,
store => delete $args{store},
extensions => ( delete $args{extensions} || ['.t'] ),
result_class =>
( delete $args{result_class} || 'App::Prove::State::Result' ),
}, $class;
$self->{_} = $self->result_class->new(
{ tests => {},
generation => 1,
}
);
my $store = $self->{store};
$self->load($store)
if defined $store && -f $store;
return $self;
}
=head2 C<result_class>
Getter/setter for the name of the class used for tracking test results. This
class should either subclass from C<App::Prove::State::Result> or provide an
identical interface.
=cut
=head2 C<extensions>
Get or set the list of extensions that files must have in order to be
considered tests. Defaults to ['.t'].
=cut
sub extensions {
my $self = shift;
$self->{extensions} = shift if @_;
return $self->{extensions};
}
=head2 C<results>
Get the results of the last test run. Returns a C<result_class()> instance.
=cut
sub results {
my $self = shift;
$self->{_} || $self->result_class->new;
}
=head2 C<commit>
Save the test results. Should be called after all tests have run.
=cut
sub commit {
my $self = shift;
if ( $self->{should_save} ) {
$self->save;
}
}
=head2 Instance Methods
=head3 C<apply_switch>
$self->apply_switch('failed,save');
Apply a list of switch options to the state, updating the internal
object state as a result. Nothing is returned.
Diagnostics:
- "Illegal state option: %s"
=over
=item C<last>
Run in the same order as last time
=item C<failed>
Run only the failed tests from last time
=item C<passed>
Run only the passed tests from last time
=item C<all>
Run all tests in normal order
=item C<hot>
Run the tests that most recently failed first
=item C<todo>
Run the tests ordered by number of todos.
=item C<slow>
Run the tests in slowest to fastest order.
=item C<fast>
Run test tests in fastest to slowest order.
=item C<new>
Run the tests in newest to oldest order.
=item C<old>
Run the tests in oldest to newest order.
=item C<save>
Save the state on exit.
=back
=cut
sub apply_switch {
my $self = shift;
my @opts = @_;
my $last_gen = $self->results->generation - 1;
my $last_run_time = $self->results->last_run_time;
my $now = $self->get_time;
my @switches = map { split /,/ } @opts;
my %handler = (
last => sub {
$self->_select(
limit => shift,
where => sub { $_->generation >= $last_gen },
order => sub { $_->sequence }
);
},
failed => sub {
$self->_select(
limit => shift,
where => sub { $_->result != 0 },
order => sub { -$_->result }
);
},
passed => sub {
$self->_select(
limit => shift,
where => sub { $_->result == 0 }
);
},
all => sub {
$self->_select( limit => shift );
},
todo => sub {
$self->_select(
limit => shift,
where => sub { $_->num_todo != 0 },
order => sub { -$_->num_todo; }
);
},
hot => sub {
$self->_select(
limit => shift,
where => sub { defined $_->last_fail_time },
order => sub { $now - $_->last_fail_time }
);
},
slow => sub {
$self->_select(
limit => shift,
order => sub { -$_->elapsed }
);
},
fast => sub {
$self->_select(
limit => shift,
order => sub { $_->elapsed }
);
},
new => sub {
$self->_select(
limit => shift,
order => sub { -$_->mtime }
);
},
old => sub {
$self->_select(
limit => shift,
order => sub { $_->mtime }
);
},
fresh => sub {
$self->_select(
limit => shift,
where => sub { $_->mtime >= $last_run_time }
);
},
save => sub {
$self->{should_save}++;
},
adrian => sub {
unshift @switches, qw( hot all save );
},
);
while ( defined( my $ele = shift @switches ) ) {
my ( $opt, $arg )
= ( $ele =~ /^([^:]+):(.*)/ )
? ( $1, $2 )
: ( $ele, undef );
my $code = $handler{$opt}
|| croak "Illegal state option: $opt";
$code->($arg);
}
return;
}
sub _select {
my ( $self, %spec ) = @_;
push @{ $self->{select} }, \%spec;
}
=head3 C<get_tests>
Given a list of args get the names of tests that should run
=cut
sub get_tests {
my $self = shift;
my $recurse = shift;
my @argv = @_;
my %seen;
my @selected = $self->_query;
unless ( @argv || @{ $self->{select} } ) {
@argv = $recurse ? '.' : 't';
croak qq{No tests named and '@argv' directory not found}
unless -d $argv[0];
}
push @selected, $self->_get_raw_tests( $recurse, @argv ) if @argv;
return grep { !$seen{$_}++ } @selected;
}
sub _query {
my $self = shift;
if ( my @sel = @{ $self->{select} } ) {
warn "No saved state, selection will be empty\n"
unless $self->results->num_tests;
return map { $self->_query_clause($_) } @sel;
}
return;
}
sub _query_clause {
my ( $self, $clause ) = @_;
my @got;
my $results = $self->results;
my $where = $clause->{where} || sub {1};
# Select
for my $name ( $results->test_names ) {
next unless -f $name;
local $_ = $results->test($name);
push @got, $name if $where->();
}
# Sort
if ( my $order = $clause->{order} ) {
@got = map { $_->[0] }
sort {
( defined $b->[1] <=> defined $a->[1] )
|| ( ( $a->[1] || 0 ) <=> ( $b->[1] || 0 ) )
} map {
[ $_,
do { local $_ = $results->test($_); $order->() }
]
} @got;
}
if ( my $limit = $clause->{limit} ) {
@got = splice @got, 0, $limit if @got > $limit;
}
return @got;
}
sub _get_raw_tests {
my $self = shift;
my $recurse = shift;
my @argv = @_;
my @tests;
# Do globbing on Win32.
if (NEED_GLOB) {
eval "use File::Glob::Windows"; # [49732]
@argv = map { glob "$_" } @argv;
}
my $extensions = $self->{extensions};
for my $arg (@argv) {
if ( '-' eq $arg ) {
push @argv => <STDIN>;
chomp(@argv);
next;
}
push @tests,
sort -d $arg
? $recurse
? $self-><API key>( $arg, $extensions )
: map { glob( File::Spec->catfile( $arg, "*$_" ) ) }
@{$extensions}
: $arg;
}
return @tests;
}
sub <API key> {
my ( $self, $dir, $extensions ) = @_;
my @tests;
my $ext_string = join( '|', map {quotemeta} @{$extensions} );
find(
{ follow => 1, #21938
follow_skip => 2,
wanted => sub {
-f
&& /(?:$ext_string)$/
&& push @tests => $File::Find::name;
}
},
$dir
);
return @tests;
}
=head3 C<observe_test>
Store the results of a test.
=cut
# Store:
# last fail time
# last pass time
# last run time
# most recent result
# most recent todos
# total failures
# total passes
# state generation
# parser
sub observe_test {
my ( $self, $test_info, $parser ) = @_;
my $name = $test_info->[0];
my $fail = scalar( $parser->failed ) + ( $parser->has_problems ? 1 : 0 );
my $todo = scalar( $parser->todo );
my $start_time = $parser->start_time;
my $end_time = $parser->end_time,
my $test = $self->results->test($name);
$test->sequence( $self->{seq}++ );
$test->generation( $self->results->generation );
$test->run_time($end_time);
$test->result($fail);
$test->num_todo($todo);
$test->elapsed( $end_time - $start_time );
$test->parser($parser);
if ($fail) {
$test->total_failures( $test->total_failures + 1 );
$test->last_fail_time($end_time);
}
else {
$test->total_passes( $test->total_passes + 1 );
$test->last_pass_time($end_time);
}
}
=head3 C<save>
Write the state to a file.
=cut
sub save {
my ($self) = @_;
my $store = $self->{store} or return;
$self->results->last_run_time( $self->get_time );
my $writer = TAP::Parser::YAMLish::Writer->new;
local *FH;
open FH, ">$store" or croak "Can't write $store ($!)";
$writer->write( $self->results->raw, \*FH );
close FH;
}
=head3 C<load>
Load the state from a file
=cut
sub load {
my ( $self, $name ) = @_;
my $reader = TAP::Parser::YAMLish::Reader->new;
local *FH;
open FH, "<$name" or croak "Can't read $name ($!)";
# XXX this is temporary
$self->{_} = $self->result_class->new(
$reader->read(
sub {
my $line = <FH>;
defined $line && chomp $line;
return $line;
}
)
);
# $writer->write( $self->{tests} || {}, \*FH );
close FH;
$self->_regen_seq;
$self->_prune_and_stamp;
$self->results->generation( $self->results->generation + 1 );
}
sub _prune_and_stamp {
my $self = shift;
my $results = $self->results;
my @tests = $self->results->tests;
for my $test (@tests) {
my $name = $test->name;
if ( my @stat = stat $name ) {
$test->mtime( $stat[9] );
}
else {
$results->remove($name);
}
}
}
sub _regen_seq {
my $self = shift;
for my $test ( $self->results->tests ) {
$self->{seq} = $test->sequence + 1
if defined $test->sequence && $test->sequence >= $self->{seq};
}
}
1;
|
<?php
namespace Drupal\language\Form;
use Drupal\Core\Block\<API key>;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\<API key>;
use Drupal\Core\Entity\<API key>;
use Drupal\Core\Extension\<API key>;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\language\<API key>;
use Drupal\language\<API key>;
use Drupal\language\Plugin\LanguageNegotiation\<API key>;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Configure the selected language negotiation method for this site.
*/
class <API key> extends ConfigFormBase {
/**
* Stores the configuration object for language.types.
*
* @var \Drupal\Core\Config\Config
*/
protected $languageTypes;
/**
* The language manager.
*
* @var \Drupal\language\<API key>
*/
protected $languageManager;
/**
* The language negotiator.
*
* @var \Drupal\language\<API key>
*/
protected $negotiator;
/**
* The block manager.
*
* @var \Drupal\Core\Block\<API key>
*/
protected $blockManager;
/**
* The block storage.
*
* @var \Drupal\Core\Entity\<API key>|null
*/
protected $blockStorage;
/**
* The theme handler.
*
* @var \Drupal\Core\Extension\<API key>
*/
protected $themeHandler;
/**
* Constructs a <API key> object.
*
* @param \Drupal\Core\Config\<API key> $config_factory
* The factory for configuration objects.
* @param \Drupal\language\<API key> $language_manager
* The language manager.
* @param \Drupal\language\<API key> $negotiator
* The language negotiation methods manager.
* @param \Drupal\Core\Block\<API key> $block_manager
* The block manager.
* @param \Drupal\Core\Extension\<API key> $theme_handler
* The theme handler.
* @param \Drupal\Core\Entity\<API key> $block_storage
* The block storage, or NULL if not available.
*/
public function __construct(<API key> $config_factory, <API key> $language_manager, <API key> $negotiator, <API key> $block_manager, <API key> $theme_handler, <API key> $block_storage = NULL) {
parent::__construct($config_factory);
$this->languageTypes = $this->config('language.types');
$this->languageManager = $language_manager;
$this->negotiator = $negotiator;
$this->blockManager = $block_manager;
$this->themeHandler = $theme_handler;
$this->blockStorage = $block_storage;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$entity_manager = $container->get('entity.manager');
$block_storage = $entity_manager->hasHandler('block', 'storage') ? $entity_manager->getStorage('block') : NULL;
return new static(
$container->get('config.factory'),
$container->get('language_manager'),
$container->get('language_negotiator'),
$container->get('plugin.manager.block'),
$container->get('theme_handler'),
$block_storage
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return '<API key>';
}
/**
* {@inheritdoc}
*/
protected function <API key>() {
return ['language.types'];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$configurable = $this->languageTypes->get('configurable');
$form = [
'#theme' => '<API key>',
'#language_types_info' => $this->languageManager-><API key>(),
'#<API key>' => $this->negotiator-><API key>(),
];
$form['#language_types'] = [];
foreach ($form['#language_types_info'] as $type => $info) {
// Show locked language types only if they are configurable.
if (empty($info['locked']) || in_array($type, $configurable)) {
$form['#language_types'][] = $type;
}
}
foreach ($form['#language_types'] as $type) {
$this->configureFormTable($form, $type);
}
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#button_type' => 'primary',
'#value' => $this->t('Save settings'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$configurable_types = $form['#language_types'];
$stored_values = $this->languageTypes->get('configurable');
$customized = [];
$method_weights_type = [];
foreach ($configurable_types as $type) {
$customized[$type] = in_array($type, $stored_values);
$method_weights = [];
$enabled_methods = $form_state->getValue([$type, 'enabled']);
$enabled_methods[<API key>::METHOD_ID] = TRUE;
$<API key> = $form_state->getValue([$type, 'weight']);
if ($form_state->hasValue([$type, 'configurable'])) {
$customized[$type] = !$form_state->isValueEmpty([$type, 'configurable']);
}
foreach ($<API key> as $method_id => $weight) {
if ($enabled_methods[$method_id]) {
$method_weights[$method_id] = $weight;
}
}
$method_weights_type[$type] = $method_weights;
$this->languageTypes->set('negotiation.' . $type . '.method_weights', $<API key>)->save();
}
// Update non-configurable language types and the related language
// negotiation configuration.
$this->negotiator->updateConfiguration(array_keys(array_filter($customized)));
// Update the language negotiations after setting the configurability.
foreach ($method_weights_type as $type => $method_weights) {
$this->negotiator->saveConfiguration($type, $method_weights);
}
// Clear block definitions cache since the available blocks and their names
// may have been changed based on the configurable types.
if ($this->blockStorage) {
// If there is an active language switcher for a language type that has
// been made not configurable, deactivate it first.
$non_configurable = array_keys(array_diff($customized, array_filter($customized)));
$this-><API key>($non_configurable);
}
$this->blockManager-><API key>();
$form_state->setRedirect('language.negotiation');
drupal_set_message($this->t('Language detection configuration saved.'));
}
/**
* Builds a language negotiation method configuration table.
*
* @param array $form
* The language negotiation configuration form.
* @param string $type
* The language type to generate the table for.
*/
protected function configureFormTable(array &$form, $type) {
$info = $form['#language_types_info'][$type];
$table_form = [
'#title' => $this->t('@type language detection', ['@type' => $info['name']]),
'#tree' => TRUE,
'#description' => $info['description'],
'#<API key>' => [],
'#show_operations' => FALSE,
'weight' => ['#tree' => TRUE],
];
// Only show configurability checkbox for the unlocked language types.
if (empty($info['locked'])) {
$configurable = $this->languageTypes->get('configurable');
$table_form['configurable'] = [
'#type' => 'checkbox',
'#title' => $this->t('Customize %language_name language detection to differ from Interface text language detection settings', ['%language_name' => $info['name']]),
'#default_value' => in_array($type, $configurable),
'#attributes' => ['class' => ['<API key>']],
'#attached' => [
'library' => [
'language/drupal.language.admin'
],
],
];
}
$negotiation_info = $form['#<API key>'];
$enabled_methods = $this->languageTypes->get('negotiation.' . $type . '.enabled') ?: [];
$methods_weight = $this->languageTypes->get('negotiation.' . $type . '.method_weights') ?: [];
// Add missing data to the methods lists.
foreach ($negotiation_info as $method_id => $method) {
if (!isset($methods_weight[$method_id])) {
$methods_weight[$method_id] = isset($method['weight']) ? $method['weight'] : 0;
}
}
// Order methods list by weight.
asort($methods_weight);
foreach ($methods_weight as $method_id => $weight) {
// A language method might be no more available if the defining module has
// been disabled after the last configuration saving.
if (!isset($negotiation_info[$method_id])) {
continue;
}
$enabled = isset($enabled_methods[$method_id]);
$method = $negotiation_info[$method_id];
// List the method only if the current type is defined in its 'types' key.
// If it is not defined default to all the configurable language types.
$types = array_flip(isset($method['types']) ? $method['types'] : $form['#language_types']);
if (isset($types[$type])) {
$table_form['#<API key>'][$method_id] = $method;
$method_name = $method['name'];
$table_form['weight'][$method_id] = [
'#type' => 'weight',
'#title' => $this->t('Weight for @title language detection method', ['@title' => Unicode::strtolower($method_name)]),
'#title_display' => 'invisible',
'#default_value' => $weight,
'#attributes' => ['class' => ["<API key>-$type"]],
'#delta' => 20,
];
$table_form['title'][$method_id] = ['#plain_text' => $method_name];
$table_form['enabled'][$method_id] = [
'#type' => 'checkbox',
'#title' => $this->t('Enable @title language detection method', ['@title' => Unicode::strtolower($method_name)]),
'#title_display' => 'invisible',
'#default_value' => $enabled,
];
if ($method_id === <API key>::METHOD_ID) {
$table_form['enabled'][$method_id]['#default_value'] = TRUE;
$table_form['enabled'][$method_id]['#attributes'] = ['disabled' => 'disabled'];
}
$table_form['description'][$method_id] = ['#markup' => $method['description']];
$config_op = [];
if (isset($method['config_route_name'])) {
$config_op['configure'] = [
'title' => $this->t('Configure'),
'url' => Url::fromRoute($method['config_route_name']),
];
// If there is at least one operation enabled show the operation
// column.
$table_form['#show_operations'] = TRUE;
}
$table_form['operation'][$method_id] = [
'#type' => 'operations',
'#links' => $config_op,
];
}
}
$form[$type] = $table_form;
}
/**
* Disables the language switcher blocks.
*
* @param array $language_types
* An array containing all language types whose language switchers need to
* be disabled.
*/
protected function <API key>(array $language_types) {
$theme = $this->themeHandler->getDefault();
$blocks = $this->blockStorage->loadByProperties(['theme' => $theme]);
foreach ($language_types as $language_type) {
foreach ($blocks as $block) {
if ($block->getPluginId() == 'language_block:' . $language_type) {
$block->delete();
}
}
}
}
}
|
<?php
class Appconfig extends CI_Model
{
public function exists($key)
{
$this->db->from('app_config');
$this->db->where('app_config.key', $key);
return ($this->db->get()->num_rows() == 1);
}
public function get_all()
{
$this->db->from('app_config');
$this->db->order_by('key', 'asc');
return $this->db->get();
}
public function get($key)
{
$query = $this->db->get_where('app_config', array('key' => $key), 1);
if($query->num_rows() == 1)
{
return $query->row()->value;
}
return '';
}
public function save($key, $value)
{
$config_data = array(
'key' => $key,
'value' => $value
);
if(!$this->exists($key))
{
return $this->db->insert('app_config', $config_data);
}
$this->db->where('key', $key);
return $this->db->update('app_config', $config_data);
}
public function batch_save($data)
{
$success = TRUE;
//Run these queries as a transaction, we want to make sure we do all or nothing
$this->db->trans_start();
foreach($data as $key=>$value)
{
$success &= $this->save($key, $value);
}
$this->db->trans_complete();
$success &= $this->db->trans_status();
return $success;
}
public function delete($key)
{
return $this->db->delete('app_config', array('key' => $key));
}
public function delete_all()
{
return $this->db->empty_table('app_config');
}
}
?>
|
/*! \file <API key>.hpp
\brief <API key>.hpp contains algorithms for string matching like backward_search, ...
\author Simon Gog
*/
#ifndef <API key>
#define <API key>
#include "int_vector.hpp"
#include <stdexcept> // for exceptions
#include <iostream>
#include <cassert>
#include <stack>
#include <utility>
namespace sdsl
{
/*!
\author Simon Gog
*/
namespace algorithm
{
//! Backward search for a character c on an interval \f$[\ell..r]\f$ of the suffix array.
/*!
* \param csa The csa in which the backward_search should be done.
* \param l Left border of the lcp-interval \f$ [\ell..r]\f$.
* \param r Right border of the lcp-interval \f$ [\ell..r]\f$.
* \param c The character c which is the starting character of the suffixes in the resulting interval \f$ [\ell_{new}..r_{new}] \f$ .
* \param l_res Reference to the resulting left border.
* \param r_res Reference to the resulting right border.
* \return The size of the new interval [\ell_{new}..r_{new}].
* \pre \f$ 0 \leq \ell \leq r < csa.size() \f$
*
* \par Time complexity
* \f$ \Order{ t_{rank\_bwt} } \f$
* \par References
* Ferragina, P. and Manzini, G. 2000. Opportunistic data structures with applications. FOCS 2000.
*/
template<class Csa>
static typename Csa::csa_size_type backward_search(
const Csa& csa,
typename Csa::size_type l,
typename Csa::size_type r,
typename Csa::char_type c,
typename Csa::size_type& l_res,
typename Csa::size_type& r_res
)
{
assert(l <= r); assert(r < csa.size());
typename Csa::size_type c_begin = csa.C[csa.char2comp[c]];
l_res = c_begin + csa.rank_bwt(l, c); // count c in bwt[0..l-1]
r_res = c_begin + csa.rank_bwt(r+1, c) - 1; // count c in bwt[0..r]
assert(r_res+1-l_res >= 0);
return r_res+1-l_res;
}
//! Backward search for a pattern pat on an interval \f$[\ell..r]\f$ of the suffix array.
/*!
* \param csa The csa in which the backward_search should be done.
* \param l Left border of the lcp-interval \f$ [\ell..r]\f$.
* \param r Right border of the lcp-interval \f$ [\ell..r]\f$.
* \param pat The string which is the prefix of the suffixes in the resulting interval \f$ [\ell_{new}..r_{new}] \f$ .
* \param len The length of pat.
* \param l_res Reference to the resulting left border.
* \param r_res Reference to the resulting right border.
* \return The size of the new interval [\ell_{new}..r_{new}].
* \pre \f$ 0 \leq \ell \leq r < csa.size() \f$
*
* \par Time complexity
* \f$ \Order{ len \cdot t_{rank\_bwt} } \f$
* \par References
* Ferragina, P. and Manzini, G. 2000. Opportunistic data structures with applications. FOCS 2000.
*/
template<class Csa>
static typename Csa::csa_size_type backward_search(const Csa& csa, typename Csa::size_type l,
typename Csa::size_type r, typename Csa::pattern_type pat,
typename Csa::size_type len, typename Csa::size_type& l_res, typename Csa::size_type& r_res)
{
typename Csa::size_type i = 0;
l_res = l; r_res = r;
while (i < len and backward_search(csa, l_res, r_res, pat[len-i-1], l_res, r_res)) {
++i;
}
return r_res+1-l_res;
}
// TODO: forward search. Include original text???
//! Counts the number of occurences of pattern pat in the string of the compressed suffix array csa.
/*!
* \param csa The compressed suffix array.
* \param pat The pattern for which we count the occurences in the string of the compressed suffix array.
* \param len The length of the pattern.
* \return The number of occurences of pattern pat in the string of the compressed suffix array.
*
* \par Time complexity
* \f$ \Order{ t_{backward\_search} } \f$
*/
template<class Csa>
static typename Csa::csa_size_type count(const Csa& csa, typename Csa::pattern_type pat, typename Csa::size_type len)
{
if (len > csa.size())
return 0;
typename Csa::size_type t1,t2; t1=t2=0; // dummy varaiable for the backward_search call
return backward_search(csa, 0, csa.size()-1, pat, len, t1, t2);
}
//! Calculates all occurences of pattern pat in the string of the compressed suffix array csa.
/*!
* \param csa The compressed suffix array.
* \param pat The pattern for which we get the occurences in the string of the compressed suffix array.
* \param len The length of the pattern.
* \param occ A resizable random access container in which the occurences are stored.
* \return The number of occurences of pattern pat of lenght len in the string of the compressed suffix array.
*
* \par Time complexity
* \f$ \Order{ t_{backward\_search} + z \cdot t_{SA} } \f$, where \f$z\f$ is the number of
* occurences of pat in the text of the compressed suffix array.
*/
template<class Csa, class <API key>>
static typename Csa::csa_size_type locate(const Csa& csa, typename Csa::pattern_type pattern,
typename Csa::size_type pattern_len, <API key>& occ)
{
typename Csa::size_type occ_begin, occ_end, occs;
occs = backward_search(csa, 0, csa.size()-1, pattern, pattern_len, occ_begin, occ_end);
occ.resize(occs);
for (typename Csa::size_type i=0; i < occs; ++i) {
occ[i] = csa[occ_begin+i];
}
return occs;
}
//! Returns the substring T[begin..end] of the original text T from the corresponding compressed suffix array.
/*!
* \param csa The compressed suffix array.
* \param begin Index of the starting position (inclusive) of the substring in the original text.
* \param end Index of the end position (inclusive) of the substring in the original text.
* \param text A pointer to the extracted text. The memory has to be initialized before the call of the function!
* \pre text has to be initialized with enough memory (end-begin+2 bytes) to hold the extracted text.
* \pre \f$begin <= end\f$ and \f$ end < csa.size() \f$
* \par Time complexity
* \f$ \Order{ (end-begin+1) \cdot t_{\Psi} + t_{SA^{-1}} } \f$
*/
// Is it cheaper to call T[i] = BWT[iSA[i+1]]??? Additional ranks but H_0 average access
// TODO: extract backward!!! is faster in most cases!
template<class Csa>
static void extract(const Csa& csa, typename Csa::size_type begin, typename Csa::size_type end, unsigned char* text)
{
assert(end <= csa.size());
assert(begin <= end);
for (typename Csa::size_type i=begin, order = csa(begin); i<=end; ++i, order = csa.psi[order]) {
uint16_t c_begin = 1, c_end = 257, mid;
while (c_begin < c_end) {
mid = (c_begin+c_end)>>1;
if (csa.C[mid] <= order) {
c_begin = mid+1;
} else {
c_end = mid;
}
}
text[i-begin] = csa.comp2char[c_begin-1];
}
if (text[end-begin]!=0)
text[end-begin+1] = 0; // set terminal character
}
//! Reconstructs the text from position \f$begin\f$ to position \f$end\f$ (inclusive) from the compressed suffix array.
/*!
* \param csa The compressed suffix array.
* \param begin Starting position (inclusive) of the text to extract.
* \param end End position (inclusive) of the text to extract.
* \return A std::string holding the extracted text.
* \pre \f$begin <= end\f$ and \f$ end < csa.size() \f$
* \par Time complexity
* \f$ \Order{ (end-begin+1) \cdot t_{\Psi} + t_{SA^{-1}} } \f$
*/
// TODO: use extract with four parameters to implement this method
template<class Csa>
static std::string extract(const Csa& csa, typename Csa::size_type begin, typename Csa::size_type end)
{
assert(end <= csa.size());
assert(begin <= end);
std::string result(end-begin+1,' ');
for (typename Csa::size_type i=begin, order = csa(begin); i<=end; ++i, order = csa.psi[order]) {
uint16_t c_begin = 1, c_end = 257, mid;
while (c_begin < c_end) {
mid = (c_begin+c_end)>>1;
if (csa.C[mid] <= order) {
c_begin = mid+1;
} else {
c_end = mid;
}
}
result[i-begin] = csa.comp2char[c_begin-1];
}
return result;
}
//! Forward search for a character c on the path on depth \f$d\f$ to node \f$v\f$.
/*!
* \param cst The compressed suffix tree.
* \param v The node at the endpoint of the current edge.
* \param d The current depth of the path. 0 = first character on each edge of the root node.
* \param c The character c which should be matched at the path on depth \f$d\f$ to node \f$v\f$.
* \param char_pos One position in the text, which corresponds to the text that is already matched. If v=cst.root() and d=0 => char_pos=0.
*
* \par Time complexity
* \f$ \Order{ t_{\Psi} } \f$ or \f$ \Order{t_{cst.child}} \f$
*/
template<class Cst>
typename Cst::cst_size_type forward_search(const Cst& cst, typename Cst::node_type& v,
const typename Cst::size_type d, const typename Cst::char_type c,
typename Cst::size_type& char_pos)
{
unsigned char cc = cst.csa.char2comp[c]; // check if c occures in the text of the csa
if (cc==0 and cc!=c)
return 0;
typename Cst::size_type depth_node = cst.depth(v);
if (d < depth_node) {
char_pos = cst.csa.psi[char_pos];
if (char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1])
return 0;
return cst.<API key>(v);
} else if (d == depth_node) {
v = cst.child(v, c, char_pos);
if (v == cst.root())
return 0;
else
return cst.<API key>(v);
} else {
throw std::invalid_argument("depth d should be smaller or equal than node depth of v!");
return 0;
}
}
//! Forward search for a pattern pat on the path on depth \f$d\f$ to node \f$v\f$.
/*!
* \param cst The compressed suffix tree.
* \param v The node at the endpoint of the current edge.
* \param d The current depth of the path. 0 = first character on each edge of the root node.
* \param pat The character c which should be matched at the path on depth \f$d\f$ to node \f$v\f$.
* \param len The length of the pattern.
* \param char_pos One position in the text, which corresponds to the text that is already matched. If v=cst.root() and d=0 => char_pos=0.
*
* \par Time complexity
* \f$ \Order{ t_{\Psi} } \f$ or \f$ \Order{t_{cst.child}} \f$
*/
template<class Cst>
typename Cst::cst_size_type forward_search(const Cst& cst, typename Cst::node_type& v,
typename Cst::size_type d, typename Cst::pattern_type pat, typename Cst::size_type len,
typename Cst::size_type& char_pos
)
{
if (len==0)
return cst.<API key>(v);
typename Cst::size_type i=0, size=0;
while (i < len and (size=forward_search(cst, v, d, pat[i], char_pos))) {
++d;
++i;
}
return size;
}
//! Calculates the count method for a (compressed) suffix tree of type Cst.
/*! \param cst A const reference to the (compressed) suffix tree.
* \param pat The pattern we seach the number of occurences.
* \param len The length of the pattern.
* \return Number of occurences of the pattern in the text of the (compressed) suffix tree.
*/
template<class Cst>
typename Cst::cst_size_type count(const Cst& cst, typename Cst::pattern_type pat, typename Cst::size_type len)
{
typename Cst::node_type v = cst.root();
typename Cst::size_type char_pos = 0;
return forward_search(cst, v, 0, pat, len, char_pos);
}
//! Calculates the locate method for a (compressed) suffix tree of type Cst.
/*! \param cst A const reference to the (compressed) suffix tree.
* \param pat The pattern for which we seach the occurences for.
* \param len The length of the pattern.
* \param occ A reference to a random access container in which we store the occurences of pattern in the text of the (compressed suffix array).
* \return Number of occurences of the pattern in the text of the (compressed) suffix tree.
*/
template<class Cst, class <API key>>
typename Cst::cst_size_type locate(const Cst& cst, typename Cst::pattern_type pat,
typename Cst::size_type len, <API key>& occ)
{
typedef typename Cst::size_type size_type;
typename Cst::node_type v = cst.root();
size_type char_pos = 0;
typename Cst::cst_size_type occs = forward_search(cst, v, 0, pat, len, char_pos);
occ.resize(occs);
if (occs == 0)
return 0; // because v equals cst.root()
size_type left = cst.lb(v); // get range in the
size_type right = cst.rb(v);
for (size_type i=left; i <= right; ++i)
occ[i-left] = cst.csa[i];
return occs;
}
//! Calculate the concatenation of edge labels from the root to the node v of the (compressed) suffix tree of type Cst.
/*!
* \param cst A const reference to the compressed suffix tree.
* \param v The node where the concatenation of the edge labels ends.
* \param text A pointer in which the string representing the concatenation of edge labels form the root to the node v will be stored.
* \pre text has to be initialized with enough memory (\f$ cst.depth(v)+1\f$ bytes) to hold the extracted text.
*/
template<class Cst>
void extract(const Cst& cst, const typename Cst::node_type& v, unsigned char* text)
{
if (v == cst.root()) {
text[0] = 0;
return;
}
// first get the suffix array entry of the leftmost leaf in the subtree rooted at v
typename Cst::size_type begin = cst.csa[cst.lb(v)];
// then call the extract method on the compressed suffix array
extract(cst.csa, begin, begin + cst.depth(v) - 1, text);
}
//! Calculate the concatenation of edge labels from the root to the node v of the (compressed) suffix tree of type Cst.
/*!
* \param cst A const reference to the compressed suffix tree.
* \param v The node where the concatenation of the edge labels ends.
* \return The string of the concatenated edge labels from the root to the node v.
*/
template<class Cst>
std::string extract(const Cst& cst, const typename Cst::node_type& v)
{
if (v==cst.root()) {
return std::string();
}
// first get the suffix array entry of the leftmost leaf in the subtree rooted at v
typename Cst::size_type begin = cst.csa[cst.lb(v)];
// then call the extract method on the compressed suffix array
return extract(cst.csa, begin, begin + cst.depth(v) - 1);
}
/*
template<class Cst>
typename Cst::size_type count(
const Cst &cst,
typename Cst::pattern_type pattern,
typename Cst::size_type pattern_len){
if(pattern_len==0){
return 0;
}
typedef typename Cst::size_type size_type;
typedef typename Cst::node_type node_type;
node_type node = cst.root();
for(size_type i=0, char_pos=0; cst.depth(node) < pattern_len; ++i){
node_type newnode = cst.child(node, (unsigned char)pattern[cst.depth(node)], char_pos);
if( newnode == cst.root() )// root node, no match found
return 0;
// else the first character of the newnode matches the pattern at position depth(node)
for(size_type j=cst.depth(node)+1; j < cst.depth(newnode) and j < pattern_len; ++j){
char_pos = cst.csa.psi[char_pos];
size_type cc = cst.csa.char2comp[pattern[j]];
if(char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1] )
return 0;
}
node = newnode;
}
return cst.<API key>(node);
}
*/
/*
template<class Cst, class <API key>>
typename Cst::size_type locate(
const Cst &cst,
typename Cst::pattern_type pattern,
typename Cst::size_type pattern_len,
<API key> &occ){
occ.resize(0);
typedef typename Cst::size_type size_type;
typedef typename Cst::node_type node_type;
node_type node = cst.root();
for(size_type i=0, char_pos=0; cst.depth(node) < pattern_len; ++i){
node_type newnode = cst.child(node, (unsigned char)pattern[cst.depth(node)], char_pos);
if( newnode == cst.root() )// root node, no match found
return 0;
// else the first character of the newnode matches the pattern at position depth(node)
for(size_type j=cst.depth(node)+1; j < cst.depth(newnode) and j < pattern_len; ++j){
char_pos = cst.csa.psi[char_pos];
size_type cc = cst.csa.char2comp[pattern[j]];
if(char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1] )
return 0;
}
node = newnode;
}
size_type occs = cst.<API key>(node);
occ.resize(occs);
size_type left = cst.<API key>(node);
size_type right = cst.<API key>(node);
for(size_type i=left; i <= right; ++i)
occ[i-left] = cst.csa[i];
return occs;
}
*/
/*
template<class Csa, class Lcp, class Bp_support>
typename cst_sct<Csa, Lcp, Bp_support>::size_type count(
const cst_sct<Csa, Lcp, Bp_support> &cst,
typename cst_sct<Csa, Lcp, Bp_support>::pattern_type pattern,
typename cst_sct<Csa, Lcp, Bp_support>::size_type pattern_len){
if(pattern_len==0){
return 0;
}
typedef typename cst_sct<Csa, Lcp, Bp_support>::size_type size_type;
typedef typename cst_sct<Csa, Lcp, Bp_support>::node_type node_type;
node_type node = cst.root();
for(size_type i=0, char_pos=0; node.l < pattern_len; ++i){
node_type newnode = cst.child(node, (unsigned char)pattern[node.l], char_pos);
if( newnode.l == 0 )// root node, no match found
return 0;
// else the first character of the newnode matches the pattern at position node.l
for(size_type j=node.l+1; j < newnode.l and j< pattern_len; ++j){
char_pos = cst.csa.psi[char_pos];
size_type cc = cst.csa.char2comp[pattern[j]];
if(char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1] )
return 0;
}
node = newnode;
}
return cst.<API key>(node);
}
*/
} // end namespace algorithm
} // end namespace sdsl
#endif
|
#endregion
using System;
using OpenRA.Network;
using OpenRA.Widgets;
namespace OpenRA.Mods.Common.Widgets.Logic
{
public class GameTimerLogic
{
[ObjectCreator.UseCtor]
public GameTimerLogic(Widget widget, OrderManager orderManager, World world)
{
var timer = widget.GetOrNull<LabelWidget>("GAME_TIMER");
var status = widget.GetOrNull<LabelWidget>("GAME_TIMER_STATUS");
var startTick = Ui.LastTickTime;
Func<bool> shouldShowStatus = () => (world.Paused || world.Timestep != Game.Timestep)
&& (Ui.LastTickTime - startTick) / 1000 % 2 == 0;
Func<string> statusText = () =>
{
if (world.Paused || world.Timestep == 0)
return "Paused";
if (world.Timestep == 1)
return "Max Speed";
return "{0}% Speed".F(Game.Timestep * 100 / world.Timestep);
};
if (timer != null)
{
timer.GetText = () =>
{
if (status == null && shouldShowStatus())
return statusText();
return WidgetUtils.FormatTime(world.WorldTick);
};
}
if (status != null)
{
// Blink the status line
status.IsVisible = shouldShowStatus;
status.GetText = statusText;
}
var percentage = widget.GetOrNull<LabelWidget>("<API key>");
if (percentage != null)
{
var connection = orderManager.Connection as ReplayConnection;
if (connection != null && connection.TickCount != 0)
percentage.GetText = () => "({0}%)".F(orderManager.NetFrameNumber * 100 / connection.TickCount);
else
timer.Bounds.Width += percentage.Bounds.Width;
}
}
}
}
|
# This file is part of GNU Radio
# GNU Radio is free software; you can redistribute it and/or modify
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
# GNU Radio is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain
|
<?php
// Moodle is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Moodle is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
defined('MOODLE_INTERNAL') || die();
class qformat_default {
public $displayerrors = true;
public $category = null;
public $questions = array();
public $course = null;
public $filename = '';
public $realfilename = '';
public $matchgrades = 'error';
public $catfromfile = 0;
public $contextfromfile = 0;
public $cattofile = 0;
public $contexttofile = 0;
public $questionids = array();
public $importerrors = 0;
public $stoponerror = true;
public $translator = null;
public $canaccessbackupdata = true;
protected $importcontext = null;
// functions to indicate import/export functionality
// override to return true if implemented
/** @return bool whether this plugin provides import functionality. */
public function provide_import() {
return false;
}
/** @return bool whether this plugin provides export functionality. */
public function provide_export() {
return false;
}
/** The string mime-type of the files that this plugin reads or writes. */
public function mime_type() {
return mimeinfo('type', $this-><API key>());
}
/**
* @return string the file extension (including .) that is normally used for
* files handled by this plugin.
*/
public function <API key>() {
return '.txt';
}
/**
* Check if the given file is capable of being imported by this plugin.
*
* Note that expensive or detailed integrity checks on the file should
* not be performed by this method. Simple file type or magic-number tests
* would be suitable.
*
* @param stored_file $file the file to check
* @return bool whether this plugin can import the file
*/
public function can_import_file($file) {
return ($file->get_mimetype() == $this->mime_type());
}
// Accessor methods
/**
* set the category
* @param object category the category object
*/
public function setCategory($category) {
if (count($this->questions)) {
debugging('You shouldn\'t call setCategory after setQuestions');
}
$this->category = $category;
$this->importcontext = context::instance_by_id($this->category->contextid);
}
/**
* Set the specific questions to export. Should not include questions with
* parents (sub questions of cloze question type).
* Only used for question export.
* @param array of question objects
*/
public function setQuestions($questions) {
if ($this->category !== null) {
debugging('You shouldn\'t call setQuestions after setCategory');
}
$this->questions = $questions;
}
/**
* set the course class variable
* @param course object Moodle course variable
*/
public function setCourse($course) {
$this->course = $course;
}
/**
* set an array of contexts.
* @param array $contexts Moodle course variable
*/
public function setContexts($contexts) {
$this->contexts = $contexts;
$this->translator = new <API key>($this->contexts);
}
/**
* set the filename
* @param string filename name of file to import/export
*/
public function setFilename($filename) {
$this->filename = $filename;
}
/**
* set the "real" filename
* (this is what the user typed, regardless of wha happened next)
* @param string realfilename name of file as typed by user
*/
public function setRealfilename($realfilename) {
$this->realfilename = $realfilename;
}
/**
* set matchgrades
* @param string matchgrades error or nearest for grades
*/
public function setMatchgrades($matchgrades) {
$this->matchgrades = $matchgrades;
}
/**
* set catfromfile
* @param bool catfromfile allow categories embedded in import file
*/
public function setCatfromfile($catfromfile) {
$this->catfromfile = $catfromfile;
}
/**
* set contextfromfile
* @param bool $contextfromfile allow contexts embedded in import file
*/
public function setContextfromfile($contextfromfile) {
$this->contextfromfile = $contextfromfile;
}
/**
* set cattofile
* @param bool cattofile exports categories within export file
*/
public function setCattofile($cattofile) {
$this->cattofile = $cattofile;
}
/**
* set contexttofile
* @param bool cattofile exports categories within export file
*/
public function setContexttofile($contexttofile) {
$this->contexttofile = $contexttofile;
}
/**
* set stoponerror
* @param bool stoponerror stops database write if any errors reported
*/
public function setStoponerror($stoponerror) {
$this->stoponerror = $stoponerror;
}
/**
* @param bool $canaccess Whether the current use can access the backup data folder. Determines
* where export files are saved.
*/
public function <API key>($canaccess) {
$this->canaccessbackupdata = $canaccess;
}
/**
* Handle parsing error
*/
protected function error($message, $text='', $questionname='') {
$importerrorquestion = get_string('importerrorquestion', 'question');
echo "<div class=\"importerror\">\n";
echo "<strong>$importerrorquestion $questionname</strong>";
if (!empty($text)) {
$text = s($text);
echo "<blockquote>$text</blockquote>\n";
}
echo "<strong>$message</strong>\n";
echo "</div>";
$this->importerrors++;
}
/**
* Import for questiontype plugins
* Do not override.
* @param data mixed The segment of data containing the question
* @param question object processed (so far) by standard import code if appropriate
* @param extra mixed any additional format specific data that may be passed by the format
* @param qtypehint hint about a question type from format
* @return object question object suitable for save_options() or false if cannot handle
*/
public function <API key>($data, $question = null, $extra = null,
$qtypehint = '') {
// work out what format we are using
$formatname = substr(get_class($this), strlen('qformat_'));
$methodname = "import_from_$formatname";
//first try importing using a hint from format
if (!empty($qtypehint)) {
$qtype = question_bank::get_qtype($qtypehint, false);
if (is_object($qtype) && method_exists($qtype, $methodname)) {
$question = $qtype->$methodname($data, $question, $this, $extra);
if ($question) {
return $question;
}
}
}
// loop through installed questiontypes checking for
// function to handle this question
foreach (question_bank::get_all_qtypes() as $qtype) {
if (method_exists($qtype, $methodname)) {
if ($question = $qtype->$methodname($data, $question, $this, $extra)) {
return $question;
}
}
}
return false;
}
/**
* Perform any required pre-processing
* @return bool success
*/
public function importpreprocess() {
return true;
}
/**
* Process the file
* This method should not normally be overidden
* @param object $category
* @return bool success
*/
public function importprocess($category) {
global $USER, $CFG, $DB, $OUTPUT;
// reset the timer in case file upload was slow
set_time_limit(0);
// STAGE 1: Parse the file
echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
if (! $lines = $this->readdata($this->filename)) {
echo $OUTPUT->notification(get_string('cannotread', 'question'));
return false;
}
if (!$questions = $this->readquestions($lines)) { // Extract all the questions
echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
return false;
}
// STAGE 2: Write data to database
echo $OUTPUT->notification(get_string('importingquestions', 'question',
$this->count_questions($questions)), 'notifysuccess');
// check for errors before we continue
if ($this->stoponerror and ($this->importerrors>0)) {
echo $OUTPUT->notification(get_string('importparseerror', 'question'));
return true;
}
// get list of valid answer grades
$gradeoptionsfull = question_bank::<API key>();
// check answer grades are valid
// (now need to do this here because of 'stop on error': MDL-10689)
$gradeerrors = 0;
$goodquestions = array();
foreach ($questions as $question) {
if (!empty($question->fraction) and (is_array($question->fraction))) {
$fractions = $question->fraction;
$invalidfractions = array();
foreach ($fractions as $key => $fraction) {
$newfraction = match_grade_options($gradeoptionsfull, $fraction,
$this->matchgrades);
if ($newfraction === false) {
$invalidfractions[] = $fraction;
} else {
$fractions[$key] = $newfraction;
}
}
if ($invalidfractions) {
echo $OUTPUT->notification(get_string('invalidgrade', 'question',
implode(', ', $invalidfractions)));
++$gradeerrors;
continue;
} else {
$question->fraction = $fractions;
}
}
$goodquestions[] = $question;
}
$questions = $goodquestions;
// check for errors before we continue
if ($this->stoponerror && $gradeerrors > 0) {
return false;
}
// count number of questions processed
$count = 0;
foreach ($questions as $question) { // Process and store each question
// reset the php timeout
set_time_limit(0);
// check for category modifiers
if ($question->qtype == 'category') {
if ($this->catfromfile) {
// find/create category object
$catpath = $question->category;
$newcategory = $this-><API key>($catpath);
if (!empty($newcategory)) {
$this->category = $newcategory;
}
}
continue;
}
$question->context = $this->importcontext;
$count++;
echo "<hr /><p><b>$count</b>. ".$this-><API key>($question)."</p>";
$question->category = $this->category->id;
$question->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
$question->createdby = $USER->id;
$question->timecreated = time();
$question->modifiedby = $USER->id;
$question->timemodified = time();
$fileoptions = array(
'subdirs' => true,
'maxfiles' => -1,
'maxbytes' => 0,
);
$question->id = $DB->insert_record('question', $question);
if (isset($question->questiontextitemid)) {
$question->questiontext = <API key>($question->questiontextitemid,
$this->importcontext->id, 'question', 'questiontext', $question->id,
$fileoptions, $question->questiontext);
} else if (isset($question->questiontextfiles)) {
foreach ($question->questiontextfiles as $file) {
question_bank::get_qtype($question->qtype)->import_file(
$this->importcontext, 'question', 'questiontext', $question->id, $file);
}
}
if (isset($question-><API key>)) {
$question->generalfeedback = <API key>($question-><API key>,
$this->importcontext->id, 'question', 'generalfeedback', $question->id,
$fileoptions, $question->generalfeedback);
} else if (isset($question-><API key>)) {
foreach ($question-><API key> as $file) {
question_bank::get_qtype($question->qtype)->import_file(
$this->importcontext, 'question', 'generalfeedback', $question->id, $file);
}
}
$DB->update_record('question', $question);
$this->questionids[] = $question->id;
// Now to save all the answers and type-specific options
$result = question_bank::get_qtype($question->qtype)-><API key>($question);
if (!empty($CFG->usetags) && isset($question->tags)) {
require_once($CFG->dirroot . '/tag/lib.php');
tag_set('question', $question->id, $question->tags);
}
if (!empty($result->error)) {
echo $OUTPUT->notification($result->error);
return false;
}
if (!empty($result->notice)) {
echo $OUTPUT->notification($result->notice);
return true;
}
// Give the question a unique version stamp determined by question_hash()
$DB->set_field('question', 'version', question_hash($question),
array('id' => $question->id));
}
return true;
}
/**
* Count all non-category questions in the questions array.
*
* @param array questions An array of question objects.
* @return int The count.
*
*/
protected function count_questions($questions) {
$count = 0;
if (!is_array($questions)) {
return $count;
}
foreach ($questions as $question) {
if (!is_object($question) || !isset($question->qtype) ||
($question->qtype == 'category')) {
continue;
}
$count++;
}
return $count;
}
/**
* find and/or create the category described by a delimited list
* e.g. $course$/tom/dick/harry or tom/dick/harry
*
* removes any context string no matter whether $getcontext is set
* but if $getcontext is set then ignore the context and use selected category context.
*
* @param string catpath delimited category path
* @param int courseid course to search for categories
* @return mixed category object or null if fails
*/
protected function <API key>($catpath) {
global $DB;
$catnames = $this->split_category_path($catpath);
$parent = 0;
$category = null;
// check for context id in path, it might not be there in pre 1.9 exports
$matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
if ($matchcount == 1) {
$contextid = $this->translator->string_to_context($matches[1]);
array_shift($catnames);
} else {
$contextid = false;
}
if ($this->contextfromfile && $contextid !== false) {
$context = context::instance_by_id($contextid);
require_capability('moodle/question:add', $context);
} else {
$context = context::instance_by_id($this->category->contextid);
}
$this->importcontext = $context;
// Now create any categories that need to be created.
foreach ($catnames as $catname) {
if ($category = $DB->get_record('question_categories',
array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
$parent = $category->id;
} else {
require_capability('moodle/question:managecategory', $context);
// create the new category
$category = new stdClass();
$category->contextid = $context->id;
$category->name = $catname;
$category->info = '';
$category->parent = $parent;
$category->sortorder = 999;
$category->stamp = make_unique_id_code();
$id = $DB->insert_record('question_categories', $category);
$category->id = $id;
$parent = $id;
}
}
return $category;
}
/**
* Return complete file within an array, one item per line
* @param string filename name of file
* @return mixed contents array or false on failure
*/
protected function readdata($filename) {
if (is_readable($filename)) {
$filearray = file($filename);
// If the first line of the file starts with a UTF-8 BOM, remove it.
$filearray[0] = core_text::trim_utf8_bom($filearray[0]);
// Check for Macintosh OS line returns (ie file on one line), and fix.
if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
return explode("\r", $filearray[0]);
} else {
return $filearray;
}
}
return false;
}
/**
* Parses an array of lines into an array of questions,
* where each item is a question object as defined by
* readquestion(). Questions are defined as anything
* between blank lines.
*
* NOTE this method used to take $context as a second argument. However, at
* the point where this method was called, it was impossible to know what
* context the quetsions were going to be saved into, so the value could be
* wrong. Also, none of the standard question formats were using this argument,
* so it was removed. See MDL-32220.
*
* If your format does not use blank lines as a delimiter
* then you will need to override this method. Even then
* try to use readquestion for each question
* @param array lines array of lines from readdata
* @return array array of question objects
*/
protected function readquestions($lines) {
$questions = array();
$currentquestion = array();
foreach ($lines as $line) {
$line = trim($line);
if (empty($line)) {
if (!empty($currentquestion)) {
if ($question = $this->readquestion($currentquestion)) {
$questions[] = $question;
}
$currentquestion = array();
}
} else {
$currentquestion[] = $line;
}
}
if (!empty($currentquestion)) { // There may be a final question
if ($question = $this->readquestion($currentquestion)) {
$questions[] = $question;
}
}
return $questions;
}
/**
* return an "empty" question
* Somewhere to specify question parameters that are not handled
* by import but are required db fields.
* This should not be overridden.
* @return object default question
*/
protected function defaultquestion() {
global $CFG;
static $<API key> = null;
if (is_null($<API key>)) {
$<API key> = get_config('quiz', 'shuffleanswers');
}
$question = new stdClass();
$question->shuffleanswers = $<API key>;
$question->defaultmark = 1;
$question->image = "";
$question->usecase = 0;
$question->multiplier = array();
$question->questiontextformat = FORMAT_MOODLE;
$question->generalfeedback = '';
$question-><API key> = FORMAT_MOODLE;
$question->correctfeedback = '';
$question-><API key> = '';
$question->incorrectfeedback = '';
$question->answernumbering = 'abc';
$question->penalty = 0.3333333;
$question->length = 1;
// this option in case the questiontypes class wants
// to know where the data came from
$question->export_process = true;
$question->import_process = true;
return $question;
}
/**
* Construct a reasonable default question name, based on the start of the question text.
* @param string $questiontext the question text.
* @param string $default default question name to use if the constructed one comes out blank.
* @return string a reasonable question name.
*/
public function <API key>($questiontext, $default) {
$name = $this->clean_question_name(shorten_text($questiontext, 80));
if ($name) {
return $name;
} else {
return $default;
}
}
/**
* Ensure that a question name does not contain anything nasty, and will fit in the DB field.
* @param string $name the raw question name.
* @return string a safe question name.
*/
public function clean_question_name($name) {
$name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
$name = trim($name);
$trimlength = 251;
while (core_text::strlen($name) > 255 && $trimlength > 0) {
$name = shorten_text($name, $trimlength);
$trimlength -= 10;
}
return $name;
}
/**
* Add a blank combined feedback to a question object.
* @param object question
* @return object question
*/
protected function <API key>($question) {
$question->correctfeedback['text'] = '';
$question->correctfeedback['format'] = $question->questiontextformat;
$question->correctfeedback['files'] = array();
$question-><API key>['text'] = '';
$question-><API key>['format'] = $question->questiontextformat;
$question-><API key>['files'] = array();
$question->incorrectfeedback['text'] = '';
$question->incorrectfeedback['format'] = $question->questiontextformat;
$question->incorrectfeedback['files'] = array();
return $question;
}
/**
* Given the data known to define a question in
* this format, this function converts it into a question
* object suitable for processing and insertion into Moodle.
*
* If your format does not use blank lines to delimit questions
* (e.g. an XML format) you must override 'readquestions' too
* @param $lines mixed data that represents question
* @return object question object
*/
protected function readquestion($lines) {
$<API key> = get_string('<API key>', 'question');
echo "<p>$<API key></p>";
return null;
}
/**
* Override if any post-processing is required
* @return bool success
*/
public function importpostprocess() {
return true;
}
/**
* Provide export functionality for plugin questiontypes
* Do not override
* @param name questiontype name
* @param question object data to export
* @param extra mixed any addition format specific data needed
* @return string the data to append to export or false if error (or unhandled)
*/
protected function <API key>($name, $question, $extra=null) {
// work out the name of format in use
$formatname = substr(get_class($this), strlen('qformat_'));
$methodname = "export_to_$formatname";
$qtype = question_bank::get_qtype($name, false);
if (method_exists($qtype, $methodname)) {
return $qtype->$methodname($question, $this, $extra);
}
return false;
}
/**
* Do any pre-processing that may be required
* @param bool success
*/
public function exportpreprocess() {
return true;
}
/**
* Enable any processing to be done on the content
* just prior to the file being saved
* default is to do nothing
* @param string output text
* @param string processed output text
*/
protected function presave_process($content) {
return $content;
}
/**
* Do the export
* For most types this should not need to be overrided
* @return stored_file
*/
public function exportprocess() {
global $CFG, $OUTPUT, $DB, $USER;
// get the questions (from database) in this category
// only get q's with no parents (no cloze subquestions specifically)
if ($this->category) {
$questions = <API key>($this->category, true);
} else {
$questions = $this->questions;
}
$count = 0;
// results are first written into string (and then to a file)
// so create/initialize the string here
$expout = "";
// track which category questions are in
// if it changes we will record the category change in the output
// file if selected. 0 means that it will get printed before the 1st question
$trackcategory = 0;
// iterate through questions
foreach ($questions as $question) {
// used by file api
$contextid = $DB->get_field('question_categories', 'contextid',
array('id' => $question->category));
$question->contextid = $contextid;
// do not export hidden questions
if (!empty($question->hidden)) {
continue;
}
// do not export random questions
if ($question->qtype == 'random') {
continue;
}
// check if we need to record category change
if ($this->cattofile) {
if ($question->category != $trackcategory) {
$trackcategory = $question->category;
$categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
// create 'dummy' question for category export
$dummyquestion = new stdClass();
$dummyquestion->qtype = 'category';
$dummyquestion->category = $categoryname;
$dummyquestion->name = 'Switch category to ' . $categoryname;
$dummyquestion->id = 0;
$dummyquestion->questiontextformat = '';
$dummyquestion->contextid = 0;
$expout .= $this->writequestion($dummyquestion) . "\n";
}
}
// export the question displaying message
$count++;
if (<API key>($question, 'view', $question->category)) {
$expout .= $this->writequestion($question, $contextid) . "\n";
}
}
// continue path for following error checks
$course = $this->course;
$continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id";
// did we actually process anything
if ($count==0) {
print_error('noquestions', 'question', $continuepath);
}
// final pre-process on exported data
$expout = $this->presave_process($expout);
return $expout;
}
/**
* get the category as a path (e.g., tom/dick/harry)
* @param int id the id of the most nested catgory
* @return string the path
*/
protected function get_category_path($id, $includecontext = true) {
global $DB;
if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
print_error('cannotfindcategory', 'error', '', $id);
}
$contextstring = $this->translator->context_to_string($category->contextid);
$pathsections = array();
do {
$pathsections[] = $category->name;
$id = $category->parent;
} while ($category = $DB->get_record('question_categories', array('id' => $id)));
if ($includecontext) {
$pathsections[] = '$' . $contextstring . '$';
}
$path = $this-><API key>(array_reverse($pathsections));
return $path;
}
/**
* Convert a list of category names, possibly preceeded by one of the
* context tokens like $course$, into a string representation of the
* category path.
*
* Names are separated by / delimiters. And /s in the name are replaced by //.
*
* To reverse the process and split the paths into names, use
* {@link split_category_path()}.
*
* @param array $names
* @return string
*/
protected function <API key>($names) {
$escapednames = array();
foreach ($names as $name) {
$escapedname = str_replace('/', '//', $name);
if (substr($escapedname, 0, 1) == '/') {
$escapedname = ' ' . $escapedname;
}
if (substr($escapedname, -1) == '/') {
$escapedname = $escapedname . ' ';
}
$escapednames[] = $escapedname;
}
return implode('/', $escapednames);
}
/**
* Convert a string, as returned by {@link <API key>()},
* back into an array of category names.
*
* Each category name is cleaned by a call to clean_param(, PARAM_TEXT),
* which matches the cleaning in question/category_form.php.
*
* @param string $path
* @return array of category names.
*/
protected function split_category_path($path) {
$rawnames = preg_split('~(?<!/)/(?!/)~', $path);
$names = array();
foreach ($rawnames as $rawname) {
$names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT);
}
return $names;
}
/**
* Do an post-processing that may be required
* @return bool success
*/
protected function exportpostprocess() {
return true;
}
/**
* convert a single question object into text output in the given
* format.
* This must be overriden
* @param object question question object
* @return mixed question export text or null if not implemented
*/
protected function writequestion($question) {
// if not overidden, then this is an error.
$<API key> = get_string('<API key>', 'question');
echo "<p>$<API key></p>";
return null;
}
/**
* Convert the question text to plain text, so it can safely be displayed
* during import to let the user see roughly what is going on.
*/
protected function <API key>($question) {
return question_utils::to_plain_text($question->questiontext,
$question->questiontextformat);
}
}
class <API key> extends qformat_default {
/**
* A lot of imported files contain unwanted entities.
* This method tries to clean up all known problems.
* @param string str string to correct
* @return string the corrected string
*/
public function cleaninput($str) {
$html_code_list = array(
"'" => "'",
"’" => "'",
"“" => "\"",
"”" => "\"",
"–" => "-",
"—" => "-",
);
$str = strtr($str, $html_code_list);
// Use core_text entities_to_utf8 function to convert only numerical entities.
$str = core_text::entities_to_utf8($str, false);
return $str;
}
/**
* Return the array moodle is expecting
* for an HTML text. No processing is done on $text.
* qformat classes that want to process $text
* for instance to import external images files
* and recode urls in $text must overwrite this method.
* @param array $text some HTML text string
* @return array with keys text, format and files.
*/
public function text_field($text) {
return array(
'text' => trim($text),
'format' => FORMAT_HTML,
'files' => array(),
);
}
/**
* Return the value of a node, given a path to the node
* if it doesn't exist return the default value.
* @param array xml data to read
* @param array path path to node expressed as array
* @param mixed default
* @param bool istext process as text
* @param string error if set value must exist, return false and issue message if not
* @return mixed value
*/
public function getpath($xml, $path, $default, $istext=false, $error='') {
foreach ($path as $index) {
if (!isset($xml[$index])) {
if (!empty($error)) {
$this->error($error);
return false;
} else {
return $default;
}
}
$xml = $xml[$index];
}
if ($istext) {
if (!is_string($xml)) {
$this->error(get_string('invalidxml', 'qformat_xml'));
}
$xml = trim($xml);
}
return $xml;
}
}
|
=pod
=head1 NAME
Locale::Currency - standard codes for currency identification
=head1 SYNOPSIS
use Locale::Currency;
$curr = code2currency('usd'); # $curr gets 'US Dollar'
$code = currency2code('Euro'); # $code gets 'eur'
@codes = all_currency_codes();
@names = all_currency_names();
=head1 DESCRIPTION
This module provides access to standard codes used for identifying
currencies and funds, such as those defined in ISO 4217.
Most of the routines take an optional additional argument which
specifies the code set to use. If not specified, the default ISO
4217 three-letter codes will be used.
=head1 SUPPORTED CODE SETS
There are several different code sets you can use for identifying
currencies. A code set may be specified using either a name, or a
constant that is automatically exported by this module.
For example, the two are equivalent:
$curr = code2currency('usd','alpha');
$curr = code2currency('usd',LOCALE_CURR_ALPHA);
The codesets currently supported are:
=over 4
=item B<alpha, LOCALE_CURR_ALPHA>
This is a set of three-letter (uppercase) codes from ISO 4217 such
as EUR for Euro.
Two of the codes specified by the standard (XTS which is reserved
for testing purposes and XXX which is for transactions where no
currency is involved) are omitted.
This is the default code set.
=item B<num, LOCALE_CURR_NUMERIC>
This is the set of three-digit numeric codes from ISO 4217.
=back
=head1 ROUTINES
=over 4
=item B<code2currency(CODE [,CODESET] [,'retired'])>
=item B<currency2code(NAME [,CODESET] [,'retired'])>
=item B<currency_code2code(CODE ,CODESET ,CODESET2)>
=item B<all_currency_codes([CODESET] [,'retired'])>
=item B<all_currency_names([CODESET] [,'retired'])>
=item B<Locale::Currency::rename_currency(CODE ,NEW_NAME [,CODESET])>
=item B<Locale::Currency::add_currency(CODE ,NAME [,CODESET])>
=item B<Locale::Currency::delete_currency(CODE [,CODESET])>
=item B<Locale::Currency::add_currency_alias(NAME ,NEW_NAME)>
=item B<Locale::Currency::<API key>(NAME)>
=item B<Locale::Currency::<API key>(CODE ,NEW_CODE [,CODESET])>
=item B<Locale::Currency::<API key>(CODE ,NEW_CODE [,CODESET])>
=item B<Locale::Currency::<API key>( CODE [,CODESET])>
These routines are all documented in the L<Locale::Codes::API> man page.
=back
=head1 SEE ALSO
=over 4
=item L<Locale::Codes>
The Locale-Codes distribution.
=item L<Locale::Codes::API>
The list of functions supported by this module.
=item L<http:
The ISO 4217 data.
=back
=head1 AUTHOR
See Locale::Codes for full author history.
Currently maintained by Sullivan Beck (sbeck@cpan.org).
=head1 COPYRIGHT
Copyright (c) 1997-2001 Canon Research Centre Europe (CRE).
Copyright (c) 2001 Michael Hennecke
Copyright (c) 2001-2010 Neil Bowers
Copyright (c) 2010-2016 Sullivan Beck
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut
|
Copyright (c) 2008-2021 Emil Dotchevski and Reverge Studios, Inc.
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http:
#include <boost/qvm/gen/vec_mat_operations2.hpp>
|
"use strict";
tutao.provide('tutao.entity.base.<API key>');
/**
* @constructor
* @param {Object=} data The json data to store in this entity.
*/
tutao.entity.base.<API key> = function(data) {
if (data) {
this.updateData(data);
} else {
this.__format = "0";
this._generatedId = null;
this._permissionListId = null;
}
this._entityHelper = new tutao.entity.EntityHelper(this);
this.prototype = tutao.entity.base.<API key>.prototype;
};
/**
* Updates the data of this entity.
* @param {Object=} data The json data to store in this entity.
*/
tutao.entity.base.<API key>.prototype.updateData = function(data) {
this.__format = data._format;
this._generatedId = data.generatedId;
this._permissionListId = data.permissionListId;
};
/**
* The version of the model this type belongs to.
* @const
*/
tutao.entity.base.<API key>.MODEL_VERSION = '1';
/**
* The encrypted flag.
* @const
*/
tutao.entity.base.<API key>.prototype.ENCRYPTED = false;
/**
* Provides the data of this instances as an object that can be converted to json.
* @return {Object} The json object.
*/
tutao.entity.base.<API key>.prototype.toJsonData = function() {
return {
_format: this.__format,
generatedId: this._generatedId,
permissionListId: this._permissionListId
};
};
/**
* The id of the <API key> type.
*/
tutao.entity.base.<API key>.prototype.TYPE_ID = 0;
/**
* The id of the generatedId attribute.
*/
tutao.entity.base.<API key>.prototype.<API key> = 2;
tutao.entity.base.<API key>.prototype.<API key> = 3;
/**
* Sets the format of this <API key>.
* @param {string} format The format of this <API key>.
*/
tutao.entity.base.<API key>.prototype.setFormat = function(format) {
this.__format = format;
return this;
};
/**
* Provides the format of this <API key>.
* @return {string} The format of this <API key>.
*/
tutao.entity.base.<API key>.prototype.getFormat = function() {
return this.__format;
};
/**
* Sets the generatedId of this <API key>.
* @param {string} generatedId The generatedId of this <API key>.
*/
tutao.entity.base.<API key>.prototype.setGeneratedId = function(generatedId) {
this._generatedId = generatedId;
return this;
};
/**
* Provides the generatedId of this <API key>.
* @return {string} The generatedId of this <API key>.
*/
tutao.entity.base.<API key>.prototype.getGeneratedId = function() {
return this._generatedId;
};
tutao.entity.base.<API key>.prototype.setPermissionListId = function(permissionListId) {
this._permissionListId = permissionListId;
return this;
};
tutao.entity.base.<API key>.prototype.getPermissionListId = function() {
return this._permissionListId;
};
/**
* Provides the entity helper of this entity.
* @return {tutao.entity.EntityHelper} The entity helper.
*/
tutao.entity.base.<API key>.prototype.getEntityHelper = function() {
return this._entityHelper;
};
|
package net.minecraftforge.event.terraingen;
import java.util.Random;
import net.minecraft.block.BlockSapling;
import net.minecraft.block.state.IBlockState;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.eventhandler.Cancelable;
import net.minecraftforge.fml.common.eventhandler.Event.HasResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.event.world.WorldEvent;
/**
* <API key> is fired when a sapling grows into a tree.<br>
* This event is fired during sapling growth in
* {@link BlockSapling#generateTree(World, BlockPos, IBlockState, Random)}.<br>
* <br>
* {@link #pos} contains the coordinates of the growing sapling. <br>
* {@link #rand} contains an instance of Random for use. <br>
* <br>
* This event is not {@link Cancelable}.<br>
* <br>
* This event has a result. {@link HasResult} <br>
* This result determines if the sapling is allowed to grow. <br>
* <br>
* This event is fired on the {@link MinecraftForge#TERRAIN_GEN_BUS}.<br>
**/
@HasResult
public class <API key> extends WorldEvent
{
private final BlockPos pos;
private final Random rand;
public <API key>(World world, Random rand, BlockPos pos)
{
super(world);
this.rand = rand;
this.pos = pos;
}
public BlockPos getPos()
{
return pos;
}
public Random getRand()
{
return rand;
}
}
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, add_months, cint, nowdate, getdate
from frappe.model.document import Document
from erpnext.accounts.doctype.purchase_invoice.purchase_invoice import <API key>
from erpnext.accounts.doctype.asset.depreciation \
import <API key>, <API key>
class Asset(Document):
def validate(self):
self.status = self.get_status()
self.validate_item()
self.set_missing_values()
self.<API key>()
self.<API key>()
self.<API key>()
if self.get("schedules"):
self.<API key>()
# Validate depreciation related accounts
<API key>(self)
def on_submit(self):
self.set_status()
def on_cancel(self):
self.<API key>()
self.<API key>()
self.set_status()
def validate_item(self):
item = frappe.db.get_value("Item", self.item_code,
["is_fixed_asset", "is_stock_item", "disabled"], as_dict=1)
if not item:
frappe.throw(_("Item {0} does not exist").format(self.item_code))
elif item.disabled:
frappe.throw(_("Item {0} has been disabled").format(self.item_code))
elif not item.is_fixed_asset:
frappe.throw(_("Item {0} must be a Fixed Asset Item").format(self.item_code))
elif item.is_stock_item:
frappe.throw(_("Item {0} must be a non-stock item").format(self.item_code))
def set_missing_values(self):
if self.item_code:
item_details = get_item_details(self.item_code)
for field, value in item_details.items():
if not self.get(field):
self.set(field, value)
self.<API key> = (flt(self.<API key>) -
flt(self.<API key>))
def <API key>(self):
if flt(self.<API key>) >= flt(self.<API key>):
frappe.throw(_("Expected Value After Useful Life must be less than Gross Purchase Amount"))
if not flt(self.<API key>):
frappe.throw(_("Gross Purchase Amount is mandatory"), frappe.MandatoryError)
if not self.is_existing_asset:
self.<API key> = 0
self.<API key> = 0
if not self.<API key>:
frappe.throw(_("Next Depreciation Date is mandatory for new asset"))
else:
depreciable_amount = flt(self.<API key>) - flt(self.<API key>)
if flt(self.<API key>) > depreciable_amount:
frappe.throw(_("Opening Accumulated Depreciation must be less than equal to {0}")
.format(depreciable_amount))
if self.<API key>:
if not self.<API key>:
frappe.throw(_("Please set Number of Depreciations Booked"))
else:
self.<API key> = 0
if cint(self.<API key>) > cint(self.<API key>):
frappe.throw(_("Number of Depreciations Booked cannot be greater than Total Number of Depreciations"))
if self.<API key> and getdate(self.<API key>) < getdate(nowdate()):
frappe.msgprint(_("Next Depreciation Date is entered as past date"), title=_('Warning'), indicator='red')
if self.<API key> and getdate(self.<API key>) < getdate(self.purchase_date):
frappe.throw(_("Next Depreciation Date cannot be before Purchase Date"))
if (flt(self.<API key>) > flt(self.<API key>)
and not self.<API key>):
frappe.throw(_("Please set Next Depreciation Date"))
def <API key>(self):
if self.depreciation_method != 'Manual':
self.schedules = []
if not self.get("schedules") and self.<API key>:
<API key> = flt(self.<API key>)
<API key> = cint(self.<API key>) - \
cint(self.<API key>)
if <API key>:
for n in xrange(<API key>):
schedule_date = add_months(self.<API key>,
n * cint(self.<API key>))
depreciation_amount = self.<API key>(<API key>)
<API key> -= flt(depreciation_amount)
self.append("schedules", {
"schedule_date": schedule_date,
"depreciation_amount": depreciation_amount
})
def <API key>(self):
<API key> = flt(self.<API key>)
<API key> = flt(self.<API key>)
for i, d in enumerate(self.get("schedules")):
depreciation_amount = flt(d.depreciation_amount, d.precision("depreciation_amount"))
<API key> -= flt(depreciation_amount)
if i==len(self.get("schedules"))-1 and self.depreciation_method == "Straight Line":
depreciation_amount += flt(<API key> - flt(self.<API key>),
d.precision("depreciation_amount"))
d.depreciation_amount = depreciation_amount
<API key> += d.depreciation_amount
d.<API key> = flt(<API key>, d.precision("<API key>"))
def <API key>(self, depreciable_value):
if self.depreciation_method in ("Straight Line", "Manual"):
depreciation_amount = (flt(self.<API key>) -
flt(self.<API key>)) / (cint(self.<API key>) -
cint(self.<API key>))
else:
factor = 200.0 / self.<API key>
depreciation_amount = flt(depreciable_value * factor / 100, 0)
<API key> = flt(depreciable_value) - depreciation_amount
if <API key> < flt(self.<API key>):
depreciation_amount = flt(depreciable_value) - flt(self.<API key>)
return depreciation_amount
def <API key>(self):
<API key> = \
max([d.<API key> for d in self.get("schedules")])
<API key> = (flt(self.<API key>) -
flt(<API key>))
if self.<API key> < <API key>:
frappe.throw(_("Expected value after useful life must be greater than or equal to {0}")
.format(<API key>))
def <API key>(self):
if self.status not in ("Submitted", "Partially Depreciated", "Fully Depreciated"):
frappe.throw(_("Asset cannot be cancelled, as it is already {0}").format(self.status))
if self.purchase_invoice:
frappe.throw(_("Please cancel Purchase Invoice {0} first").format(self.purchase_invoice))
def <API key>(self):
for d in self.get("schedules"):
if d.journal_entry:
frappe.get_doc("Journal Entry", d.journal_entry).cancel()
d.db_set("journal_entry", None)
self.db_set("<API key>",
(flt(self.<API key>) - flt(self.<API key>)))
def set_status(self, status=None):
'''Get and update status'''
if not status:
status = self.get_status()
self.db_set("status", status)
def get_status(self):
'''Returns status based on whether it is draft, submitted, scrapped or depreciated'''
if self.docstatus == 0:
status = "Draft"
elif self.docstatus == 1:
status = "Submitted"
if self.<API key>:
status = "Scrapped"
elif flt(self.<API key>) <= flt(self.<API key>):
status = "Fully Depreciated"
elif flt(self.<API key>) < flt(self.<API key>):
status = 'Partially Depreciated'
elif self.docstatus == 2:
status = "Cancelled"
return status
@frappe.whitelist()
def <API key>(asset, item_code, <API key>, company, posting_date):
pi = frappe.new_doc("Purchase Invoice")
pi.company = company
pi.currency = frappe.db.get_value("Company", company, "default_currency")
pi.set_posting_time = 1
pi.posting_date = posting_date
pi.append("items", {
"item_code": item_code,
"is_fixed_asset": 1,
"asset": asset,
"expense_account": <API key>(asset),
"qty": 1,
"price_list_rate": <API key>,
"rate": <API key>
})
pi.set_missing_values()
return pi
@frappe.whitelist()
def make_sales_invoice(asset, item_code, company):
si = frappe.new_doc("Sales Invoice")
si.company = company
si.currency = frappe.db.get_value("Company", company, "default_currency")
disposal_account, <API key> = <API key>(company)
si.append("items", {
"item_code": item_code,
"is_fixed_asset": 1,
"asset": asset,
"income_account": disposal_account,
"cost_center": <API key>,
"qty": 1
})
si.set_missing_values()
return si
@frappe.whitelist()
def transfer_asset(args):
import json
args = json.loads(args)
movement_entry = frappe.new_doc("Asset Movement")
movement_entry.update(args)
movement_entry.insert()
movement_entry.submit()
frappe.db.commit()
frappe.msgprint(_("Asset Movement record {0} created").format("<a href='#Form/Asset Movement/{0}'>{0}</a>".format(movement_entry.name)))
@frappe.whitelist()
def get_item_details(item_code):
asset_category = frappe.db.get_value("Item", item_code, "asset_category")
if not asset_category:
frappe.throw(_("Please enter Asset Category in Item {0}").format(item_code))
ret = frappe.db.get_value("Asset Category", asset_category,
["depreciation_method", "<API key>", "<API key>"], as_dict=1)
ret.update({
"asset_category": asset_category
})
return ret
|
/* Written by Paul Eggert. */
#include <config.h>
#include "physmem.h"
#include <unistd.h>
#if HAVE_SYS_PSTAT_H
# include <sys/pstat.h>
#endif
#if HAVE_SYS_SYSMP_H
# include <sys/sysmp.h>
#endif
#if HAVE_SYS_SYSINFO_H && <API key>
# include <sys/sysinfo.h>
# include <machine/hal_sysinfo.h>
#endif
#if HAVE_SYS_TABLE_H
# include <sys/table.h>
#endif
#include <sys/types.h>
#if HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#if HAVE_SYS_SYSCTL_H
# include <sys/sysctl.h>
#endif
#if <API key>
# include <sys/systemcfg.h>
#endif
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
/* MEMORYSTATUSEX is missing from older windows headers, so define
a local replacement. */
typedef struct
{
DWORD dwLength;
DWORD dwMemoryLoad;
DWORDLONG ullTotalPhys;
DWORDLONG ullAvailPhys;
DWORDLONG ullTotalPageFile;
DWORDLONG ullAvailPageFile;
DWORDLONG ullTotalVirtual;
DWORDLONG ullAvailVirtual;
DWORDLONG <API key>;
} lMEMORYSTATUSEX;
typedef WINBOOL (WINAPI *PFN_MS_EX) (lMEMORYSTATUSEX*);
#endif
#define ARRAY_SIZE(a) (sizeof (a) / sizeof ((a)[0]))
/* Return the total amount of physical memory. */
double
physmem_total (void)
{
#if defined _SC_PHYS_PAGES && defined _SC_PAGESIZE
{ /* This works on linux-gnu, solaris2 and cygwin. */
double pages = sysconf (_SC_PHYS_PAGES);
double pagesize = sysconf (_SC_PAGESIZE);
if (0 <= pages && 0 <= pagesize)
return pages * pagesize;
}
#endif
#if <API key>
{ /* This works on hpux11. */
struct pst_static pss;
if (0 <= pstat_getstatic (&pss, sizeof pss, 1, 0))
{
double pages = pss.physical_memory;
double pagesize = pss.page_size;
if (0 <= pages && 0 <= pagesize)
return pages * pagesize;
}
}
#endif
#if HAVE_SYSMP && defined MP_SAGET && defined MPSA_RMINFO && defined _SC_PAGESIZE
{ /* This works on irix6. */
struct rminfo realmem;
if (sysmp (MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0)
{
double pagesize = sysconf (_SC_PAGESIZE);
double pages = realmem.physmem;
if (0 <= pages && 0 <= pagesize)
return pages * pagesize;
}
}
#endif
#if HAVE_GETSYSINFO && defined GSI_PHYSMEM
{ /* This works on Tru64 UNIX V4/5. */
int physmem;
if (getsysinfo (GSI_PHYSMEM, (caddr_t) &physmem, sizeof (physmem),
NULL, NULL, NULL) == 1)
{
double kbytes = physmem;
if (0 <= kbytes)
return kbytes * 1024.0;
}
}
#endif
#if HAVE_SYSCTL && defined HW_PHYSMEM
{ /* This works on *bsd and darwin. */
unsigned int physmem;
size_t len = sizeof physmem;
static int mib[2] = { CTL_HW, HW_PHYSMEM };
if (sysctl (mib, ARRAY_SIZE (mib), &physmem, &len, NULL, 0) == 0
&& len == sizeof (physmem))
return (double) physmem;
}
#endif
#if <API key>
/* This works on AIX. */
return <API key>.physmem;
#endif
#if defined _WIN32
{ /* this works on windows */
PFN_MS_EX pfnex;
HMODULE h = GetModuleHandle ("kernel32.dll");
if (!h)
return 0.0;
/* Use <API key> if available. */
if ((pfnex = (PFN_MS_EX) GetProcAddress (h, "<API key>")))
{
lMEMORYSTATUSEX lms_ex;
lms_ex.dwLength = sizeof lms_ex;
if (!pfnex (&lms_ex))
return 0.0;
return (double) lms_ex.ullTotalPhys;
}
/* Fall back to GlobalMemoryStatus which is always available.
but returns wrong results for physical memory > 4GB. */
else
{
MEMORYSTATUS ms;
GlobalMemoryStatus (&ms);
return (double) ms.dwTotalPhys;
}
}
#endif
/* Guess 64 MB. It's probably an older host, so guess small. */
return 64 * 1024 * 1024;
}
/* Return the amount of physical memory available. */
double
physmem_available (void)
{
#if defined _SC_AVPHYS_PAGES && defined _SC_PAGESIZE
{ /* This works on linux-gnu, solaris2 and cygwin. */
double pages = sysconf (_SC_AVPHYS_PAGES);
double pagesize = sysconf (_SC_PAGESIZE);
if (0 <= pages && 0 <= pagesize)
return pages * pagesize;
}
#endif
#if <API key> && <API key>
{ /* This works on hpux11. */
struct pst_static pss;
struct pst_dynamic psd;
if (0 <= pstat_getstatic (&pss, sizeof pss, 1, 0)
&& 0 <= pstat_getdynamic (&psd, sizeof psd, 1, 0))
{
double pages = psd.psd_free;
double pagesize = pss.page_size;
if (0 <= pages && 0 <= pagesize)
return pages * pagesize;
}
}
#endif
#if HAVE_SYSMP && defined MP_SAGET && defined MPSA_RMINFO && defined _SC_PAGESIZE
{ /* This works on irix6. */
struct rminfo realmem;
if (sysmp (MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0)
{
double pagesize = sysconf (_SC_PAGESIZE);
double pages = realmem.availrmem;
if (0 <= pages && 0 <= pagesize)
return pages * pagesize;
}
}
#endif
#if HAVE_TABLE && defined TBL_VMSTATS
{ /* This works on Tru64 UNIX V4/5. */
struct tbl_vmstats vmstats;
if (table (TBL_VMSTATS, 0, &vmstats, 1, sizeof (vmstats)) == 1)
{
double pages = vmstats.free_count;
double pagesize = vmstats.pagesize;
if (0 <= pages && 0 <= pagesize)
return pages * pagesize;
}
}
#endif
#if HAVE_SYSCTL && defined HW_USERMEM
{ /* This works on *bsd and darwin. */
unsigned int usermem;
size_t len = sizeof usermem;
static int mib[2] = { CTL_HW, HW_USERMEM };
if (sysctl (mib, ARRAY_SIZE (mib), &usermem, &len, NULL, 0) == 0
&& len == sizeof (usermem))
return (double) usermem;
}
#endif
#if defined _WIN32
{ /* this works on windows */
PFN_MS_EX pfnex;
HMODULE h = GetModuleHandle ("kernel32.dll");
if (!h)
return 0.0;
/* Use <API key> if available. */
if ((pfnex = (PFN_MS_EX) GetProcAddress (h, "<API key>")))
{
lMEMORYSTATUSEX lms_ex;
lms_ex.dwLength = sizeof lms_ex;
if (!pfnex (&lms_ex))
return 0.0;
return (double) lms_ex.ullAvailPhys;
}
/* Fall back to GlobalMemoryStatus which is always available.
but returns wrong results for physical memory > 4GB */
else
{
MEMORYSTATUS ms;
GlobalMemoryStatus (&ms);
return (double) ms.dwAvailPhys;
}
}
#endif
/* Guess 25% of physical memory. */
return physmem_total () / 4;
}
#if DEBUG
# include <stdio.h>
# include <stdlib.h>
int
main (void)
{
printf ("%12.f %12.f\n", physmem_total (), physmem_available ());
exit (0);
}
#endif /* DEBUG */
/*
Local Variables:
compile-command: "gcc -DDEBUG -g -O -Wall -W physmem.c"
End:
*/
|
#ifndef IMPORTDIALOG_H
#define IMPORTDIALOG_H
#include "../guisubautomata.h"
// Definition of this class
class ImportDialog {
public:
// Constructor
ImportDialog ( GuiSubautomata* gsubautomata );
// Destructor
virtual ~ImportDialog ();
// Popup initializer
void init ();
protected:
// Data structure
GuiSubautomata* gsubautomata;
Gtk::Dialog* dialog;
Gtk::Button* button_accept;
Gtk::Button* button_cancel;
Gtk::CheckButton *checkbutton_laser, *checkbutton_sonar, *checkbutton_camera;
Gtk::CheckButton *<API key>, *<API key>;
// Private methods
void on_button_accept ();
void on_button_cancel ();
bool on_key_released ( GdkEventKey* event );
};
#endif // IMPORTDIALOG_H
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This is a virtual module that is entirely implemented as an action plugin and runs on the controller
from __future__ import absolute_import, division, print_function
__metaclass__ = type
EXAMPLES = r'''
- name: Store file into /tmp/fetched/host.example.com/tmp/somefile
fetch:
src: /tmp/somefile
dest: /tmp/fetched
- name: Specifying a path directly
fetch:
src: /tmp/somefile
dest: /tmp/prefix-{{ inventory_hostname }}
flat: yes
- name: Specifying a destination path
fetch:
src: /tmp/uniquefile
dest: /tmp/special/
flat: yes
- name: Storing in a path relative to the playbook
fetch:
src: /tmp/uniquefile
dest: special/prefix-{{ inventory_hostname }}
flat: yes
'''
|
/* Written by Bruno Haible, 2010. */
#include <config.h>
/* Specification. */
#include <unistd.h>
#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
char *
getlogin (void)
{
#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
static char login_name[1024];
DWORD sz = sizeof (login_name);
if (GetUserName (login_name, &sz))
return login_name;
#endif
return NULL;
}
|
// |jit-test| error: TestComplete
// onPop can change a normal return into a throw.
load(libdir + "asserts.js");
var g = newGlobal('new-compartment');
var dbg = new Debugger(g);
function test(type, provocation) {
var log;
// Help people figure out which 'test' call failed.
print("type: " + uneval(type));
print("provocation: " + uneval(provocation));
dbg.onDebuggerStatement = function <API key>(f) {
log += 'd';
};
dbg.onEnterFrame = function handleEnterFrame(f) {
log += '(';
assertEq(f.type, type);
f.onPop = function handlePop(c) {
log += ')';
assertEq(c.return, 'compliment');
return { throw: 'snow' };
};
};
log = '';
assertThrowsValue(provocation, 'snow');
assertEq(log, "(d)");
print();
}
g.eval("function f() { debugger; return 'compliment'; }");
test("call", g.f);
test("call", function () { return new g.f; });
test("eval", function () { return g.eval("debugger; \'compliment\';"); });
test("global", function () { return g.evaluate("debugger; \'compliment\';"); });
throw 'TestComplete';
|
<!DOCTYPE html>
<!
Distributed under both the W3C Test Suite License [1] and the W3C
3-clause BSD License [2]. To contribute to a W3C Test Suite, see the
policies and contribution forms [3].
[1] http:
[2] http:
[3] http:
<html>
<head>
<title>Shadow DOM Test: A_05_01_01</title>
<link rel="author" title="Sergey G. Grekhov" href="mailto:sgrekhov@unipro.ru">
<link rel="help" href="http://www.w3.org/TR/2013/<API key>/#event-retargeting">
<meta name="assert" content="Event Retargeting:test that event.target is retargeted when event crosses shadow boundary and vice versa">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="../../../../html/resources/common.js"></script>
</head>
<body>
<div id="log"></div>
<script>
var A_05_01_01_T1 = async_test('A_05_01_01_T1');
A_05_01_01_T1.step(function () {
var iframe = document.createElement('iframe');
iframe.src = '../../resources/blank.html';
document.body.appendChild(iframe);
iframe.onload = A_05_01_01_T1.step_func(function () {
try {
var d = iframe.contentDocument;
var div = d.createElement('div');
d.body.appendChild(div);
var s = div.createShadowRoot();
var div2 = d.createElement('div');
s.appendChild(div2);
var inp = d.createElement('input');
inp.setAttribute('type', 'text');
inp.setAttribute('id', 'inpid');
div2.appendChild(inp);
div2.addEventListener('click', A_05_01_01_T1.step_func(function (event) {
assert_equals(event.target.tagName, 'INPUT', 'Information about target of the event that ' +
'doesn\'t cross the shadow boundaries should not be adjusted');
}), false);
var event = d.createEvent('HTMLEvents');
event.initEvent ("click", true, false);
inp.dispatchEvent(event);
} finally {
iframe.parentNode.removeChild(iframe);
}
A_05_01_01_T1.done();
});
});
var A_05_01_01_T2 = async_test('A_05_01_01_T2');
A_05_01_01_T2.step(function () {
var iframe = document.createElement('iframe');
iframe.src = '../../resources/blank.html';
document.body.appendChild(iframe);
iframe.onload = A_05_01_01_T2.step_func(function () {
try {
var d = iframe.contentDocument;
var div = d.createElement('div');
d.body.appendChild(div);
var s = div.createShadowRoot();
var div2 = d.createElement('div');
s.appendChild(div2);
var inp = d.createElement('input');
inp.setAttribute('type', 'text');
inp.setAttribute('id', 'inpid');
div2.appendChild(inp);
div.addEventListener('click', A_05_01_01_T2.step_func(function (event) {
assert_equals(event.target.tagName, 'DIV', 'Information about event target crossing ' +
'the shadow boundaries should be adjusted');
}), false);
var event = d.createEvent('HTMLEvents');
event.initEvent ("click", true, false);
inp.dispatchEvent(event);
} finally {
iframe.parentNode.removeChild(iframe);
}
A_05_01_01_T2.done();
});
});
</script>
</body>
</html>
|
# encoding: utf-8
# This Source Code Form is subject to the terms of the Mozilla Public
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
import smtplib
import sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from mo_logs import Log
from mo_dots import listwrap
from mo_dots import coalesce
from mo_kwargs import override
class Emailer:
@override
def __init__(
self,
from_address,
to_address,
host,
username,
password,
subject="catchy title",
port=465,
use_ssl=1,
kwargs=None
):
self.settings = kwargs
self.server = None
def __enter__(self):
if self.server is not None:
Log.error("Got a problem")
if self.settings.use_ssl:
self.server = smtplib.SMTP_SSL(self.settings.host, self.settings.port)
else:
self.server = smtplib.SMTP(self.settings.host, self.settings.port)
if self.settings.username and self.settings.password:
self.server.login(self.settings.username, self.settings.password)
return self
def __exit__(self, type, value, traceback):
try:
self.server.quit()
except Exception as e:
Log.warning("Problem with smtp server quit(), ignoring problem", e)
self.server = None
def send_email(self,
from_address=None,
to_address=None,
subject=None,
text_data=None,
html_data=None
):
"""Sends an email.
from_addr is an email address; to_addrs is a list of email adresses.
Addresses can be plain (e.g. "jsmith@example.com") or with real names
(e.g. "John Smith <jsmith@example.com>").
text_data and html_data are both strings. You can specify one or both.
If you specify both, the email will be sent as a MIME multipart
alternative, i.e., the recipient will see the HTML content if his
viewer supports it; otherwise he'll see the text content.
"""
settings = self.settings
from_address = coalesce(from_address, settings["from"], settings.from_address)
to_address = listwrap(coalesce(to_address, settings.to_address, settings.to_addrs))
if not from_address or not to_address:
raise Exception("Both from_addr and to_addrs must be specified")
if not text_data and not html_data:
raise Exception("Must specify either text_data or html_data")
if not html_data:
msg = MIMEText(text_data)
elif not text_data:
msg = MIMEText(html_data, 'html')
else:
msg = MIMEMultipart('alternative')
msg.attach(MIMEText(text_data, 'plain'))
msg.attach(MIMEText(html_data, 'html'))
msg['Subject'] = coalesce(subject, settings.subject)
msg['From'] = from_address
msg['To'] = ', '.join(to_address)
if self.server:
# CALL AS PART OF A SMTP SESSION
self.server.sendmail(from_address, to_address, msg.as_string())
else:
# CALL AS STAND-ALONE
with self:
self.server.sendmail(from_address, to_address, msg.as_string())
if sys.hexversion < 0x020603f0:
# versions earlier than 2.6.3 have a bug in smtplib when sending over SSL:
# Unfortunately the stock version of Python in Snow Leopard is 2.6.1, so
# we patch it here to avoid having to install an updated Python version.
import socket
import ssl
def _get_socket_fixed(self, host, port, timeout):
if self.debuglevel > 0:
print>> sys.stderr, 'connect:', (host, port)
new_socket = socket.create_connection((host, port), timeout)
new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile)
self.file = smtplib.SSLFakeFile(new_socket)
return new_socket
smtplib.SMTP_SSL._get_socket = _get_socket_fixed
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>external.argparse — IPython v0.10 documentation</title>
<link rel="stylesheet" href="../../_static/default.css" type="text/css" />
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var <API key> = {
URL_ROOT: '../../',
VERSION: '0.10',
COLLAPSE_MODINDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../../_static/jquery.js"></script>
<script type="text/javascript" src="../../_static/doctools.js"></script>
<link rel="top" title="IPython v0.10 documentation" href="../../index.html" />
<link rel="up" title="The IPython API" href="../index.html" />
<link rel="next" title="external.configobj" href="IPython.external.configobj.html" />
<link rel="prev" title="external.Itpl" href="IPython.external.Itpl.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../../modindex.html" title="Global Module Index"
accesskey="M">modules</a> |</li>
<li class="right" >
<a href="IPython.external.configobj.html" title="external.configobj"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="IPython.external.Itpl.html" title="external.Itpl"
accesskey="P">previous</a> |</li>
<li><a href="../../index.html">IPython v0.10 documentation</a> »</li>
<li><a href="../index.html" accesskey="U">The IPython API</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="external-argparse">
<h1>external.argparse<a class="headerlink" href="
<div class="section" id="module-IPython.external.argparse">
<h2>Module: <tt class="xref docutils literal"><span class="pre">external.argparse</span></tt><a class="headerlink" href="
<p>Inheritance diagram for <tt class="docutils literal"><span class="pre">IPython.external.argparse</span></tt>:</p>
<img src="../../_images/<API key>.png" usemap="#<API key>" class="inheritance"/><map id="<API key>" name="<API key>">
<area shape="rect" href="#IPython.external.argparse.Action" title="external.argparse.Action" alt="" coords="231,196,336,212"/>
<area shape="rect" href="#IPython.external.argparse.<API key>" title="external.argparse.<API key>" alt="" coords="188,48,380,63"/>
<area shape="rect" href="#IPython.external.argparse.<API key>" title="external.argparse.<API key>" alt="" coords="419,48,583,63"/>
<area shape="rect" href="#IPython.external.argparse.HelpFormatter" title="external.argparse.HelpFormatter" alt="" coords="10,63,146,78"/>
<area shape="rect" href="#IPython.external.argparse.<API key>" title="external.argparse.<API key>" alt="" coords="182,77,386,93"/>
<area shape="rect" href="#IPython.external.argparse.ArgumentParser" title="external.argparse.ArgumentParser" alt="" coords="213,267,355,282"/>
<area shape="rect" href="#IPython.external.argparse.Namespace" title="external.argparse.Namespace" alt="" coords="221,230,347,246"/>
<area shape="rect" href="#IPython.external.argparse.FileType" title="external.argparse.FileType" alt="" coords="23,33,133,48"/>
<area shape="rect" href="#IPython.external.argparse.ArgumentError" title="external.argparse.ArgumentError" alt="" coords="10,3,146,19"/>
</map>
<p>Command-line parsing library</p>
<p>This module is an optparse-inspired command-line parsing library that:</p>
<blockquote>
<ul class="simple">
<li>handles both optional and positional arguments</li>
<li>produces highly informative usage messages</li>
<li>supports parsers that dispatch to sub-parsers</li>
</ul>
</blockquote>
<p>The following is a simple usage example that sums integers from the
command-line and writes the result to a file:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="n">description</span><span class="o">=</span><span class="s">'sum the integers at the command line'</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
<span class="s">'integers'</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s">'int'</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s">'+'</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
<span class="n">help</span><span class="o">=</span><span class="s">'an integer to be summed'</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
<span class="s">'--log'</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s">'w'</span><span class="p">),</span>
<span class="n">help</span><span class="o">=</span><span class="s">'the file where the sum should be written'</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">args</span><span class="o">.</span><span class="n">log</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s">'</span><span class="si">%s</span><span class="s">'</span> <span class="o">%</span> <span class="nb">sum</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">integers</span><span class="p">))</span>
<span class="n">args</span><span class="o">.</span><span class="n">log</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The module contains the following public classes:</p>
<blockquote>
<ul>
<li><dl class="first docutils">
<dt>ArgumentParser – The main entry point for command-line parsing. As the</dt>
<dd><p class="first last">example above shows, the add_argument() method is used to populate
the parser with actions for optional and positional arguments. Then
the parse_args() method is invoked to convert the args at the
command-line into an object with attributes.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>ArgumentError – The exception raised by ArgumentParser objects when</dt>
<dd><p class="first last">there are errors with the parser’s actions. Errors raised while
parsing the command-line are caught by ArgumentParser and emitted
as command-line messages.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>FileType – A factory for defining types of files to be created. As the</dt>
<dd><p class="first last">example above shows, instances of FileType are typically passed as
the type= argument of add_argument() calls.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>Action – The base class for parser actions. Typically actions are</dt>
<dd><p class="first last">selected by passing strings like ‘store_true’ or ‘append_const’ to
the action= argument of add_argument(). However, for greater
customization of ArgumentParser actions, subclasses of Action may
be defined and passed as the action= argument.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>HelpFormatter, <API key>, <API key>,</dt>
<dd><p class="first last"><API key> – Formatter classes which
may be passed as the formatter_class= argument to the
ArgumentParser constructor. HelpFormatter is the default,
<API key> and <API key> tell the parser
not to change the formatting for help text, and
<API key> adds information about argument defaults
to the help.</p>
</dd>
</dl>
</li>
</ul>
</blockquote>
<p>All other classes in this module are considered implementation details.
(Also note that HelpFormatter and <API key> are only
considered public as object names – the API of the formatter objects is
still considered an implementation detail.)</p>
</div>
<div class="section" id="classes">
<h2>Classes<a class="headerlink" href="
<div class="section" id="action">
<h3><a title="IPython.external.argparse.Action" class="reference internal" href="
<dl class="class">
<dt id="IPython.external.argparse.Action">
<!--[IPython.external.argparse.Action]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">Action</tt><big>(</big><em>option_strings</em>, <em>dest</em>, <em>nargs=None</em>, <em>const=None</em>, <em>default=None</em>, <em>type=None</em>, <em>choices=None</em>, <em>required=False</em>, <em>help=None</em>, <em>metavar=None</em><big>)</big><a class="headerlink" href="
<dd><p>Bases: <tt class="xref docutils literal"><span class="pre">IPython.external.argparse._AttributeHolder</span></tt></p>
<p>Information about how to convert command line strings to Python objects.</p>
<p>Action objects are used by an ArgumentParser to represent the information
needed to parse a single argument from one or more strings from the
command line. The keyword arguments to the Action constructor are also
all attributes of Action instances.</p>
<p>Keyword Arguments:</p>
<blockquote>
<ul>
<li><dl class="first docutils">
<dt>option_strings – A list of command-line option strings which</dt>
<dd><p class="first last">should be associated with this action.</p>
</dd>
</dl>
</li>
<li><p class="first">dest – The name of the attribute to hold the created object(s)</p>
</li>
<li><dl class="first docutils">
<dt>nargs – The number of command-line arguments that should be</dt>
<dd><p class="first">consumed. By default, one argument will be consumed and a single
value will be produced. Other values include:</p>
<blockquote>
<ul class="simple">
<li>N (an integer) consumes N arguments (and produces a list)</li>
<li>‘?’ consumes zero or one arguments</li>
<li>‘*’ consumes zero or more arguments (and produces a list)</li>
<li>‘+’ consumes one or more arguments (and produces a list)</li>
</ul>
</blockquote>
<p class="last">Note that the difference between the default and nargs=1 is that
with the default, a single value will be produced, while with
nargs=1, a list containing a single value will be produced.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>const – The value to be produced if the option is specified and the</dt>
<dd><p class="first last">option uses an action that takes no values.</p>
</dd>
</dl>
</li>
<li><p class="first">default – The value to be produced if the option is not specified.</p>
</li>
<li><dl class="first docutils">
<dt>type – The type which the command-line arguments should be converted</dt>
<dd><p class="first last">to, should be one of ‘string’, ‘int’, ‘float’, ‘complex’ or a
callable object that accepts a single string argument. If None,
‘string’ is assumed.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>choices – A container of values that should be allowed. If not None,</dt>
<dd><p class="first last">after a command-line argument has been converted to the appropriate
type, an exception will be raised if it is not a member of this
collection.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>required – True if the action must always be specified at the</dt>
<dd><p class="first last">command line. This is only meaningful for optional command-line
arguments.</p>
</dd>
</dl>
</li>
<li><p class="first">help – The help string describing the argument.</p>
</li>
<li><dl class="first docutils">
<dt>metavar – The name to be used for the option’s argument with the</dt>
<dd><p class="first last">help string. If None, the ‘dest’ value will be used as the name.</p>
</dd>
</dl>
</li>
</ul>
</blockquote>
<dl class="method">
<dt id="IPython.external.argparse.Action.__init__">
<!--[IPython.external.argparse.Action.__init__]--><tt class="descname">__init__</tt><big>(</big><em>option_strings</em>, <em>dest</em>, <em>nargs=None</em>, <em>const=None</em>, <em>default=None</em>, <em>type=None</em>, <em>choices=None</em>, <em>required=False</em>, <em>help=None</em>, <em>metavar=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
</dd></dl>
</div>
<div class="section" id="<API key>">
<h3><a title="IPython.external.argparse.<API key>" class="reference internal" href="
<dl class="class">
<dt id="IPython.external.argparse.<API key>">
<!--[IPython.external.argparse.<API key>]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname"><API key></tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="
<dd><p>Bases: <a title="IPython.external.argparse.HelpFormatter" class="reference internal" href="#IPython.external.argparse.HelpFormatter"><tt class="xref docutils literal"><span class="pre">IPython.external.argparse.HelpFormatter</span></tt></a></p>
<p>Help message formatter which adds default values to argument help.</p>
<p>Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.</p>
<dl class="method">
<dt id="IPython.external.argparse.<API key>.__init__">
<!--[IPython.external.argparse.<API key>.__init__]--><tt class="descname">__init__</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
</dd></dl>
</div>
<div class="section" id="argumenterror">
<h3><a title="IPython.external.argparse.ArgumentError" class="reference internal" href="
<dl class="class">
<dt id="IPython.external.argparse.ArgumentError">
<!--[IPython.external.argparse.ArgumentError]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">ArgumentError</tt><big>(</big><em>argument</em>, <em>message</em><big>)</big><a class="headerlink" href="
<dd><p>Bases: <tt class="xref docutils literal"><span class="pre">exceptions.Exception</span></tt></p>
<p>An error from creating or using an argument (optional or positional).</p>
<p>The string value of this exception is the message, augmented with
information about the argument that caused it.</p>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentError.__init__">
<!--[IPython.external.argparse.ArgumentError.__init__]--><tt class="descname">__init__</tt><big>(</big><em>argument</em>, <em>message</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
</dd></dl>
</div>
<div class="section" id="argumentparser">
<h3><a title="IPython.external.argparse.ArgumentParser" class="reference internal" href="
<dl class="class">
<dt id="IPython.external.argparse.ArgumentParser">
<!--[IPython.external.argparse.ArgumentParser]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">ArgumentParser</tt><big>(</big><em>prog=None</em>, <em>usage=None</em>, <em>description=None</em>, <em>epilog=None</em>, <em>version=None</em>, <em>parents=</em><span class="optional">[</span><span class="optional">]</span>, <em>formatter_class=<class 'IPython.external.argparse.HelpFormatter'></em>, <em>prefix_chars='-'</em>, <em><API key>=None</em>, <em>argument_default=None</em>, <em>conflict_handler='error'</em>, <em>add_help=True</em><big>)</big><a class="headerlink" href="
<dd><p>Bases: <tt class="xref docutils literal"><span class="pre">IPython.external.argparse._AttributeHolder</span></tt>, <tt class="xref docutils literal"><span class="pre">IPython.external.argparse._ActionsContainer</span></tt></p>
<p>Object for parsing command line strings into Python objects.</p>
<dl class="docutils">
<dt>Keyword Arguments:</dt>
<dd><ul class="first last">
<li><p class="first">prog – The name of the program (default: sys.argv[0])</p>
</li>
<li><p class="first">usage – A usage message (default: auto-generated from arguments)</p>
</li>
<li><p class="first">description – A description of what the program does</p>
</li>
<li><p class="first">epilog – Text following the argument descriptions</p>
</li>
<li><p class="first">version – Add a -v/–version option with the given version string</p>
</li>
<li><p class="first">parents – Parsers whose arguments should be copied into this one</p>
</li>
<li><p class="first">formatter_class – HelpFormatter class for printing help messages</p>
</li>
<li><p class="first">prefix_chars – Characters that prefix optional arguments</p>
</li>
<li><dl class="first docutils">
<dt><API key> – Characters that prefix files containing</dt>
<dd><p class="first last">additional arguments</p>
</dd>
</dl>
</li>
<li><p class="first">argument_default – The default value for all arguments</p>
</li>
<li><p class="first">conflict_handler – String indicating how to handle conflicts</p>
</li>
<li><p class="first">add_help – Add a -h/-help option</p>
</li>
</ul>
</dd>
</dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.__init__">
<!--[IPython.external.argparse.ArgumentParser.__init__]--><tt class="descname">__init__</tt><big>(</big><em>prog=None</em>, <em>usage=None</em>, <em>description=None</em>, <em>epilog=None</em>, <em>version=None</em>, <em>parents=</em><span class="optional">[</span><span class="optional">]</span>, <em>formatter_class=<class 'IPython.external.argparse.HelpFormatter'></em>, <em>prefix_chars='-'</em>, <em><API key>=None</em>, <em>argument_default=None</em>, <em>conflict_handler='error'</em>, <em>add_help=True</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.add_subparsers">
<!--[IPython.external.argparse.ArgumentParser.add_subparsers]--><tt class="descname">add_subparsers</tt><big>(</big><em>**kwargs</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.error">
<!--[IPython.external.argparse.ArgumentParser.error]--><tt class="descname">error</tt><big>(</big><em>message: string</em><big>)</big><a class="headerlink" href="
<dd><p>Prints a usage message incorporating the message to stderr and
exits.</p>
<p>If you override this in a subclass, it should not return – it
should either exit or raise an exception.</p>
</dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.exit">
<!--[IPython.external.argparse.ArgumentParser.exit]--><tt class="descname">exit</tt><big>(</big><em>status=0</em>, <em>message=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.format_help">
<!--[IPython.external.argparse.ArgumentParser.format_help]--><tt class="descname">format_help</tt><big>(</big><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.format_usage">
<!--[IPython.external.argparse.ArgumentParser.format_usage]--><tt class="descname">format_usage</tt><big>(</big><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.format_version">
<!--[IPython.external.argparse.ArgumentParser.format_version]--><tt class="descname">format_version</tt><big>(</big><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.parse_args">
<!--[IPython.external.argparse.ArgumentParser.parse_args]--><tt class="descname">parse_args</tt><big>(</big><em>args=None</em>, <em>namespace=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.parse_known_args">
<!--[IPython.external.argparse.ArgumentParser.parse_known_args]--><tt class="descname">parse_known_args</tt><big>(</big><em>args=None</em>, <em>namespace=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.print_help">
<!--[IPython.external.argparse.ArgumentParser.print_help]--><tt class="descname">print_help</tt><big>(</big><em>file=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.print_usage">
<!--[IPython.external.argparse.ArgumentParser.print_usage]--><tt class="descname">print_usage</tt><big>(</big><em>file=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.ArgumentParser.print_version">
<!--[IPython.external.argparse.ArgumentParser.print_version]--><tt class="descname">print_version</tt><big>(</big><em>file=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
</dd></dl>
</div>
<div class="section" id="filetype">
<h3><a title="IPython.external.argparse.FileType" class="reference internal" href="
<dl class="class">
<dt id="IPython.external.argparse.FileType">
<!--[IPython.external.argparse.FileType]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">FileType</tt><big>(</big><em>mode='r'</em>, <em>bufsize=None</em><big>)</big><a class="headerlink" href="
<dd><p>Bases: <tt class="xref docutils literal"><span class="pre">object</span></tt></p>
<p>Factory for creating file object types</p>
<p>Instances of FileType are typically passed as type= arguments to the
ArgumentParser add_argument() method.</p>
<dl class="docutils">
<dt>Keyword Arguments:</dt>
<dd><ul class="first last">
<li><dl class="first docutils">
<dt>mode – A string indicating how the file is to be opened. Accepts the</dt>
<dd><p class="first last">same values as the builtin open() function.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>bufsize – The file’s desired buffer size. Accepts the same values as</dt>
<dd><p class="first last">the builtin open() function.</p>
</dd>
</dl>
</li>
</ul>
</dd>
</dl>
<dl class="method">
<dt id="IPython.external.argparse.FileType.__init__">
<!--[IPython.external.argparse.FileType.__init__]--><tt class="descname">__init__</tt><big>(</big><em>mode='r'</em>, <em>bufsize=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
</dd></dl>
</div>
<div class="section" id="helpformatter">
<h3><a title="IPython.external.argparse.HelpFormatter" class="reference internal" href="
<dl class="class">
<dt id="IPython.external.argparse.HelpFormatter">
<!--[IPython.external.argparse.HelpFormatter]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">HelpFormatter</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="
<dd><p>Bases: <tt class="xref docutils literal"><span class="pre">object</span></tt></p>
<p>Formatter for generating usage messages and argument help strings.</p>
<p>Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.</p>
<dl class="method">
<dt id="IPython.external.argparse.HelpFormatter.__init__">
<!--[IPython.external.argparse.HelpFormatter.__init__]--><tt class="descname">__init__</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.HelpFormatter.add_argument">
<!--[IPython.external.argparse.HelpFormatter.add_argument]--><tt class="descname">add_argument</tt><big>(</big><em>action</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.HelpFormatter.add_arguments">
<!--[IPython.external.argparse.HelpFormatter.add_arguments]--><tt class="descname">add_arguments</tt><big>(</big><em>actions</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.HelpFormatter.add_text">
<!--[IPython.external.argparse.HelpFormatter.add_text]--><tt class="descname">add_text</tt><big>(</big><em>text</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.HelpFormatter.add_usage">
<!--[IPython.external.argparse.HelpFormatter.add_usage]--><tt class="descname">add_usage</tt><big>(</big><em>usage</em>, <em>actions</em>, <em>groups</em>, <em>prefix=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.HelpFormatter.end_section">
<!--[IPython.external.argparse.HelpFormatter.end_section]--><tt class="descname">end_section</tt><big>(</big><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.HelpFormatter.format_help">
<!--[IPython.external.argparse.HelpFormatter.format_help]--><tt class="descname">format_help</tt><big>(</big><big>)</big><a class="headerlink" href="
<dd></dd></dl>
<dl class="method">
<dt id="IPython.external.argparse.HelpFormatter.start_section">
<!--[IPython.external.argparse.HelpFormatter.start_section]--><tt class="descname">start_section</tt><big>(</big><em>heading</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
</dd></dl>
</div>
<div class="section" id="namespace">
<h3><a title="IPython.external.argparse.Namespace" class="reference internal" href="
<dl class="class">
<dt id="IPython.external.argparse.Namespace">
<!--[IPython.external.argparse.Namespace]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">Namespace</tt><big>(</big><em>**kwargs</em><big>)</big><a class="headerlink" href="
<dd><p>Bases: <tt class="xref docutils literal"><span class="pre">IPython.external.argparse._AttributeHolder</span></tt></p>
<p>Simple object for storing attributes.</p>
<p>Implements equality by attribute names and values, and provides a simple
string representation.</p>
<dl class="method">
<dt id="IPython.external.argparse.Namespace.__init__">
<!--[IPython.external.argparse.Namespace.__init__]--><tt class="descname">__init__</tt><big>(</big><em>**kwargs</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
</dd></dl>
</div>
<div class="section" id="<API key>">
<h3><a title="IPython.external.argparse.<API key>" class="reference internal" href="
<dl class="class">
<dt id="IPython.external.argparse.<API key>">
<!--[IPython.external.argparse.<API key>]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname"><API key></tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="
<dd><p>Bases: <a title="IPython.external.argparse.HelpFormatter" class="reference internal" href="#IPython.external.argparse.HelpFormatter"><tt class="xref docutils literal"><span class="pre">IPython.external.argparse.HelpFormatter</span></tt></a></p>
<p>Help message formatter which retains any formatting in descriptions.</p>
<p>Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.</p>
<dl class="method">
<dt id="IPython.external.argparse.<API key>.__init__">
<!--[IPython.external.argparse.<API key>.__init__]--><tt class="descname">__init__</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
</dd></dl>
</div>
<div class="section" id="<API key>">
<h3><a title="IPython.external.argparse.<API key>" class="reference internal" href="
<dl class="class">
<dt id="IPython.external.argparse.<API key>">
<!--[IPython.external.argparse.<API key>]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname"><API key></tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="
<dd><p>Bases: <a title="IPython.external.argparse.<API key>" class="reference internal" href="#IPython.external.argparse.<API key>"><tt class="xref docutils literal"><span class="pre">IPython.external.argparse.<API key></span></tt></a></p>
<p>Help message formatter which retains formatting of all help text.</p>
<p>Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.</p>
<dl class="method">
<dt id="IPython.external.argparse.<API key>.__init__">
<!--[IPython.external.argparse.<API key>.__init__]--><tt class="descname">__init__</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="
<dd></dd></dl>
</dd></dl>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="<API key>">
<h3><a href="../../index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference external" href="">external.argparse</a><ul>
<li><a class="reference external" href="#module-IPython.external.argparse">Module: <tt class="docutils literal"><span class="pre">external.argparse</span></tt></a></li>
<li><a class="reference external" href="#classes">Classes</a><ul>
<li><a class="reference external" href="#action"><tt class="docutils literal"><span class="pre">Action</span></tt></a></li>
<li><a class="reference external" href="#<API key>"><tt class="docutils literal"><span class="pre"><API key></span></tt></a></li>
<li><a class="reference external" href="#argumenterror"><tt class="docutils literal"><span class="pre">ArgumentError</span></tt></a></li>
<li><a class="reference external" href="#argumentparser"><tt class="docutils literal"><span class="pre">ArgumentParser</span></tt></a></li>
<li><a class="reference external" href="#filetype"><tt class="docutils literal"><span class="pre">FileType</span></tt></a></li>
<li><a class="reference external" href="#helpformatter"><tt class="docutils literal"><span class="pre">HelpFormatter</span></tt></a></li>
<li><a class="reference external" href="#namespace"><tt class="docutils literal"><span class="pre">Namespace</span></tt></a></li>
<li><a class="reference external" href="#<API key>"><tt class="docutils literal"><span class="pre"><API key></span></tt></a></li>
<li><a class="reference external" href="#<API key>"><tt class="docutils literal"><span class="pre"><API key></span></tt></a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="IPython.external.Itpl.html" title="previous chapter">external.Itpl</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="IPython.external.configobj.html" title="next chapter">external.configobj</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../../_sources/api/generated/IPython.external.argparse.txt">Show Source</a></li>
</ul>
<h3>Quick search</h3>
<form class="search" action="../../search.html" method="get">
<input type="text" name="q" size="18" /> <input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../../modindex.html" title="Global Module Index"
accesskey="M">modules</a> |</li>
<li class="right" >
<a href="IPython.external.configobj.html" title="external.configobj"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="IPython.external.Itpl.html" title="external.Itpl"
accesskey="P">previous</a> |</li>
<li><a href="../../index.html">IPython v0.10 documentation</a> »</li>
<li><a href="../index.html" accesskey="U">The IPython API</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2008, The IPython Development Team.
Last updated on Aug 04, 2009.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.5.2.
</div>
</body>
</html>
|
# -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='catalogintegration',
name='service_username',
field=models.CharField(default=u'<API key>', help_text='Username created for Course Catalog Integration, e.g. <API key>.', max_length=100),
),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.